k8s.io/apiserver@v0.31.1/pkg/audit/format.go (about) 1 /* 2 Copyright 2017 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 audit 18 19 import ( 20 "fmt" 21 "strconv" 22 "strings" 23 "time" 24 25 auditinternal "k8s.io/apiserver/pkg/apis/audit" 26 ) 27 28 // EventString creates a 1-line text representation of an audit event, using a subset of the 29 // information in the event struct. 30 func EventString(ev *auditinternal.Event) string { 31 username := "<none>" 32 groups := "<none>" 33 if len(ev.User.Username) > 0 { 34 username = ev.User.Username 35 if len(ev.User.Groups) > 0 { 36 groups = auditStringSlice(ev.User.Groups) 37 } 38 } 39 asuser := "<self>" 40 asgroups := "<lookup>" 41 if ev.ImpersonatedUser != nil { 42 asuser = ev.ImpersonatedUser.Username 43 if ev.ImpersonatedUser.Groups != nil { 44 asgroups = auditStringSlice(ev.ImpersonatedUser.Groups) 45 } 46 } 47 48 namespace := "<none>" 49 if ev.ObjectRef != nil && len(ev.ObjectRef.Namespace) != 0 { 50 namespace = ev.ObjectRef.Namespace 51 } 52 53 response := "<deferred>" 54 if ev.ResponseStatus != nil { 55 response = strconv.Itoa(int(ev.ResponseStatus.Code)) 56 } 57 58 ip := "<unknown>" 59 if len(ev.SourceIPs) > 0 { 60 ip = ev.SourceIPs[0] 61 } 62 63 return fmt.Sprintf("%s AUDIT: id=%q stage=%q ip=%q method=%q user=%q groups=%q as=%q asgroups=%q user-agent=%q namespace=%q uri=%q response=\"%s\"", 64 ev.RequestReceivedTimestamp.Format(time.RFC3339Nano), ev.AuditID, ev.Stage, ip, ev.Verb, username, groups, asuser, asgroups, ev.UserAgent, namespace, ev.RequestURI, response) 65 } 66 67 func auditStringSlice(inList []string) string { 68 quotedElements := make([]string, len(inList)) 69 for i, in := range inList { 70 quotedElements[i] = fmt.Sprintf("%q", in) 71 } 72 return strings.Join(quotedElements, ",") 73 }