| 1 |
/* |
| 2 |
Copyright 2021 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package filters |
| 18 |
|
| 19 |
import ( |
| 20 |
"net/http" |
| 21 |
|
| 22 |
"k8s.io/apimachinery/pkg/types" |
| 23 |
auditinternal "k8s.io/apiserver/pkg/apis/audit" |
| 24 |
"k8s.io/apiserver/pkg/audit" |
| 25 |
|
| 26 |
"github.com/google/uuid" |
| 27 |
) |
| 28 |
|
| 29 |
// WithAuditInit initializes the audit context and attaches the Audit-ID associated with a request. |
| 30 |
// |
| 31 |
// a. If the caller does not specify a value for Audit-ID in the request header, we generate a new audit ID |
| 32 |
// b. We echo the Audit-ID value to the caller via the response Header 'Audit-ID'. |
| 33 |
func WithAuditInit(handler http.Handler) http.Handler { |
| 34 |
return withAuditInit(handler, func() string { |
| 35 |
return uuid.New().String() |
| 36 |
}) |
| 37 |
} |
| 38 |
|
| 39 |
func withAuditInit(handler http.Handler, newAuditIDFunc func() string) http.Handler { |
| 40 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 41 |
ctx := audit.WithAuditContext(r.Context()) |
| 42 |
r = r.WithContext(ctx) |
| 43 |
|
| 44 |
auditID := r.Header.Get(auditinternal.HeaderAuditID) |
| 45 |
if len(auditID) == 0 { |
| 46 |
auditID = newAuditIDFunc() |
| 47 |
} |
| 48 |
|
| 49 |
// Note: we save the user specified value of the Audit-ID header as is, no truncation is performed. |
| 50 |
audit.WithAuditID(ctx, types.UID(auditID)) |
| 51 |
|
| 52 |
// We echo the Audit-ID in to the response header. |
| 53 |
// It's not guaranteed Audit-ID http header is sent for all requests. |
| 54 |
// For example, when user run "kubectl exec", apiserver uses a proxy handler |
| 55 |
// to deal with the request, users can only get http headers returned by kubelet node. |
| 56 |
// |
| 57 |
// This filter will also be used by other aggregated api server(s). For an aggregated API |
| 58 |
// we don't want to see the same audit ID appearing more than once. |
| 59 |
if value := w.Header().Get(auditinternal.HeaderAuditID); len(value) == 0 { |
| 60 |
w.Header().Set(auditinternal.HeaderAuditID, auditID) |
| 61 |
} |
| 62 |
|
| 63 |
handler.ServeHTTP(w, r) |
| 64 |
}) |
| 65 |
} |