Switch branches/tags
kubernetes-1.13.0-alpha.1 kubernetes-1.13.0-alpha.0 kubernetes-1.12.2-beta.0 kubernetes-1.12.1 kubernetes-1.12.1-beta.0 kubernetes-1.12.1-beta.0-invalid kubernetes-1.12.0 kubernetes-1.12.0-rc.2 kubernetes-1.12.0-rc.2-invalid kubernetes-1.12.0-rc.1 kubernetes-1.12.0-rc.1-invalid kubernetes-1.12.0-invalid kubernetes-1.12.0-beta.2 kubernetes-1.12.0-beta.2-invalid kubernetes-1.12.0-beta.1 kubernetes-1.12.0-beta.0 kubernetes-1.12.0-alpha.1 kubernetes-1.12.0-alpha.0 kubernetes-1.11.4-beta.0 kubernetes-1.11.3 kubernetes-1.11.3-beta.0 kubernetes-1.11.2 kubernetes-1.11.2-beta.0 kubernetes-1.11.1 kubernetes-1.11.1-beta.0 kubernetes-1.11.0 kubernetes-1.11.0-rc.3 kubernetes-1.11.0-rc.2 kubernetes-1.11.0-rc.1 kubernetes-1.11.0-beta.2 kubernetes-1.11.0-beta.1 kubernetes-1.11.0-beta.0 kubernetes-1.11.0-alpha.2 kubernetes-1.11.0-alpha.1 kubernetes-1.11.0-alpha.0 kubernetes-1.10.10-beta.0 kubernetes-1.10.9 kubernetes-1.10.9-beta.0 kubernetes-1.10.8 kubernetes-1.10.8-beta.0 kubernetes-1.10.7 kubernetes-1.10.7-beta.0 kubernetes-1.10.6 kubernetes-1.10.6-beta.0 kubernetes-1.10.5 kubernetes-1.10.5-beta.0 kubernetes-1.10.4 kubernetes-1.10.4-beta.0 kubernetes-1.10.3 kubernetes-1.10.3-beta.0 kubernetes-1.10.2 kubernetes-1.10.2-beta.0 kubernetes-1.10.1 kubernetes-1.10.1-beta.0 kubernetes-1.10.0 kubernetes-1.10.0-rc.1 kubernetes-1.10.0-beta.4 kubernetes-1.10.0-beta.3 kubernetes-1.10.0-beta.2 kubernetes-1.10.0-beta.1 kubernetes-1.10.0-beta.0 kubernetes-1.10.0-alpha.3 kubernetes-1.10.0-alpha.2 kubernetes-1.10.0-alpha.1 kubernetes-1.10.0-alpha.0 kubernetes-1.9.12-beta.0 kubernetes-1.9.11 kubernetes-1.9.11-beta.0 kubernetes-1.9.10 kubernetes-1.9.10-beta.0 kubernetes-1.9.9 kubernetes-1.9.9-beta.0 kubernetes-1.9.8 kubernetes-1.9.8-beta.0 kubernetes-1.9.7 kubernetes-1.9.7-beta.0 kubernetes-1.9.6 kubernetes-1.9.6-beta.0 kubernetes-1.9.5 kubernetes-1.9.5-beta.0 kubernetes-1.9.4 kubernetes-1.9.4-beta.0 kubernetes-1.9.3 kubernetes-1.9.3-beta.0 kubernetes-1.9.2 kubernetes-1.9.2-beta.0 kubernetes-1.9.1 kubernetes-1.9.1-beta.0 kubernetes-1.9.0 kubernetes-1.9.0-beta.2 kubernetes-1.9.0-beta.1 kubernetes-1.9.0-beta.0 kubernetes-1.9.0-alpha.3 kubernetes-1.9.0-alpha.2 kubernetes-1.9.0-alpha.1 kubernetes-1.9.0-alpha.0 kubernetes-1.8.16-beta.0 kubernetes-1.8.15 kubernetes-1.8.15-beta.0 kubernetes-1.8.14
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
249 lines (212 sloc) 8.01 KB
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.
package filters
import (
metav1 ""
utilruntime ""
auditinternal ""
// WithAudit decorates a http.Handler with audit logging information for all the
// requests coming to the server. Audit level is decided according to requests'
// attributes and audit policy. Logs are emitted to the audit sink to
// process events. If sink or audit policy is nil, no decoration takes place.
func WithAudit(handler http.Handler, sink audit.Sink, policy policy.Checker, longRunningCheck request.LongRunningRequestCheck) http.Handler {
if sink == nil || policy == nil {
return handler
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
req, ev, omitStages, err := createAuditEventAndAttachToContext(req, policy)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to create audit event: %v", err))
responsewriters.InternalError(w, req, errors.New("failed to create audit event"))
ctx := req.Context()
if ev == nil || ctx == nil {
handler.ServeHTTP(w, req)
ev.Stage = auditinternal.StageRequestReceived
processAuditEvent(sink, ev, omitStages)
// intercept the status code
var longRunningSink audit.Sink
if longRunningCheck != nil {
ri, _ := request.RequestInfoFrom(ctx)
if longRunningCheck(req, ri) {
longRunningSink = sink
respWriter := decorateResponseWriter(w, ev, longRunningSink, omitStages)
// send audit event when we leave this func, either via a panic or cleanly. In the case of long
// running requests, this will be the second audit event.
defer func() {
if r := recover(); r != nil {
defer panic(r)
ev.Stage = auditinternal.StagePanic
ev.ResponseStatus = &metav1.Status{
Code: http.StatusInternalServerError,
Status: metav1.StatusFailure,
Reason: metav1.StatusReasonInternalError,
Message: fmt.Sprintf("APIServer panic'd: %v", r),
processAuditEvent(sink, ev, omitStages)
// if no StageResponseStarted event was sent b/c neither a status code nor a body was sent, fake it here
// But Audit-Id http header will only be sent when http.ResponseWriter.WriteHeader is called.
fakedSuccessStatus := &metav1.Status{
Code: http.StatusOK,
Status: metav1.StatusSuccess,
Message: "Connection closed early",
if ev.ResponseStatus == nil && longRunningSink != nil {
ev.ResponseStatus = fakedSuccessStatus
ev.Stage = auditinternal.StageResponseStarted
processAuditEvent(longRunningSink, ev, omitStages)
ev.Stage = auditinternal.StageResponseComplete
if ev.ResponseStatus == nil {
ev.ResponseStatus = fakedSuccessStatus
processAuditEvent(sink, ev, omitStages)
handler.ServeHTTP(respWriter, req)
// createAuditEventAndAttachToContext is responsible for creating the audit event
// and attaching it to the appropriate request context. It returns:
// - context with audit event attached to it
// - created audit event
// - error if anything bad happened
func createAuditEventAndAttachToContext(req *http.Request, policy policy.Checker) (*http.Request, *auditinternal.Event, []auditinternal.Stage, error) {
ctx := req.Context()
attribs, err := GetAuthorizerAttributes(ctx)
if err != nil {
return req, nil, nil, fmt.Errorf("failed to GetAuthorizerAttributes: %v", err)
level, omitStages := policy.LevelAndStages(attribs)
if level == auditinternal.LevelNone {
// Don't audit.
return req, nil, nil, nil
ev, err := audit.NewEventFromRequest(req, level, attribs)
if err != nil {
return req, nil, nil, fmt.Errorf("failed to complete audit event from request: %v", err)
req = req.WithContext(request.WithAuditEvent(ctx, ev))
return req, ev, omitStages, nil
func processAuditEvent(sink audit.Sink, ev *auditinternal.Event, omitStages []auditinternal.Stage) {
for _, stage := range omitStages {
if ev.Stage == stage {
if ev.Stage == auditinternal.StageRequestReceived {
ev.StageTimestamp = metav1.NewMicroTime(ev.RequestReceivedTimestamp.Time)
} else {
ev.StageTimestamp = metav1.NewMicroTime(time.Now())
func decorateResponseWriter(responseWriter http.ResponseWriter, ev *auditinternal.Event, sink audit.Sink, omitStages []auditinternal.Stage) http.ResponseWriter {
delegate := &auditResponseWriter{
ResponseWriter: responseWriter,
event: ev,
sink: sink,
omitStages: omitStages,
// check if the ResponseWriter we're wrapping is the fancy one we need
// or if the basic is sufficient
_, cn := responseWriter.(http.CloseNotifier)
_, fl := responseWriter.(http.Flusher)
_, hj := responseWriter.(http.Hijacker)
if cn && fl && hj {
return &fancyResponseWriterDelegator{delegate}
return delegate
var _ http.ResponseWriter = &auditResponseWriter{}
// auditResponseWriter intercepts WriteHeader, sets it in the event. If the sink is set, it will
// create immediately an event (for long running requests).
type auditResponseWriter struct {
event *auditinternal.Event
once sync.Once
sink audit.Sink
omitStages []auditinternal.Stage
func (a *auditResponseWriter) setHttpHeader() {
a.ResponseWriter.Header().Set(auditinternal.HeaderAuditID, string(a.event.AuditID))
func (a *auditResponseWriter) processCode(code int) {
a.once.Do(func() {
if a.event.ResponseStatus == nil {
a.event.ResponseStatus = &metav1.Status{}
a.event.ResponseStatus.Code = int32(code)
a.event.Stage = auditinternal.StageResponseStarted
if a.sink != nil {
processAuditEvent(a.sink, a.event, a.omitStages)
func (a *auditResponseWriter) Write(bs []byte) (int, error) {
// the Go library calls WriteHeader internally if no code was written yet. But this will go unnoticed for us
return a.ResponseWriter.Write(bs)
func (a *auditResponseWriter) WriteHeader(code int) {
// fancyResponseWriterDelegator implements http.CloseNotifier, http.Flusher and
// http.Hijacker which are needed to make certain http operation (e.g. watch, rsh, etc)
// working.
type fancyResponseWriterDelegator struct {
func (f *fancyResponseWriterDelegator) CloseNotify() <-chan bool {
return f.ResponseWriter.(http.CloseNotifier).CloseNotify()
func (f *fancyResponseWriterDelegator) Flush() {
func (f *fancyResponseWriterDelegator) Hijack() (net.Conn, *bufio.ReadWriter, error) {
// fake a response status before protocol switch happens
// This will be ignored if WriteHeader() function has already been called.
// It's not guaranteed Audit-ID http header is sent for all requests.
// For example, when user run "kubectl exec", apiserver uses a proxy handler
// to deal with the request, users can only get http headers returned by kubelet node.
return f.ResponseWriter.(http.Hijacker).Hijack()
var _ http.CloseNotifier = &fancyResponseWriterDelegator{}
var _ http.Flusher = &fancyResponseWriterDelegator{}
var _ http.Hijacker = &fancyResponseWriterDelegator{}