Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions hack/observe_behavior/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
logs
118 changes: 118 additions & 0 deletions hack/observe_behavior/audit-format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
Copyright 2025 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

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os"
"strings"
"time"

auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
utilsslices "sigs.k8s.io/kwok/pkg/utils/slices"
"sigs.k8s.io/kwok/pkg/utils/yaml"
)

func main() {

input := os.Stdin
output := os.Stdout

fmt.Fprintln(output, "# Formatted Audit Log")

Check failure on line 38 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintln` is not checked (errcheck)

scanner := bufio.NewScanner(input)
var event auditv1.Event
for scanner.Scan() {
line := scanner.Bytes()
err := json.Unmarshal(line, &event)
if err != nil {
fmt.Fprintf(output, "Error parsing JSON: %v\n", err)

Check failure on line 46 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintf` is not checked (errcheck)
os.Exit(1)
return
}

if event.RequestObject.ContentType != "application/json" {
fmt.Fprintf(output, "---\n# Skipping resource with unsupported content type: %s\n", event.RequestObject.ContentType)

Check failure on line 52 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintf` is not checked (errcheck)
continue
}
yamlData, err := yaml.JSONToYAML(event.RequestObject.Raw)
if err != nil {
fmt.Fprintf(output, "---\n# Error converting to YAML: %v\n", err)

Check failure on line 57 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintf` is not checked (errcheck)
continue
}

timestamp := event.RequestReceivedTimestamp.UTC().Format(time.RFC3339)
operation := strings.SplitN(event.UserAgent, "/", 2)[0]
verb := event.Verb
requestURI := event.RequestURI

info := Info{
Timestamp: timestamp,
Operator: operation,
Verb: verb,
RequestURI: requestURI,
ObjectRef: ObjectRef{
Resource: event.ObjectRef.Resource,
Subresource: event.ObjectRef.Subresource,
Name: event.ObjectRef.Name,
Namespace: event.ObjectRef.Namespace,
},
}
infoYAML, err := yaml.Marshal(info)
if err != nil {
fmt.Printf("# Error marshaling info to YAML: %v\n", err)
continue
}

fmt.Fprintln(output, "---")

Check failure on line 84 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintln` is not checked (errcheck)
output.Write(commentsYAML(infoYAML))

Check failure on line 85 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `output.Write` is not checked (errcheck)
output.Write(yamlData)

Check failure on line 86 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `output.Write` is not checked (errcheck)
}

fmt.Fprintln(output, "---")

Check failure on line 89 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintln` is not checked (errcheck)
if err := scanner.Err(); err != nil {
fmt.Fprintf(output, "Error reading file: %v\n", err)

Check failure on line 91 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `fmt.Fprintf` is not checked (errcheck)
os.Exit(1)
}
}

func commentsYAML(data []byte) []byte {
return bytes.Join(utilsslices.Map(bytes.Split(data, []byte{'\n'}), func(line []byte) []byte {
if len(line) == 0 {
return []byte{}
}
return append([]byte("# "), line...)
}), []byte{'\n'})
}

type Info struct {

Check failure on line 105 in hack/observe_behavior/audit-format.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

exported: exported type Info should have comment or be unexported (revive)
Timestamp string `json:"timestamp"`
Operator string `json:"operator"`
Verb string `json:"verb"`
RequestURI string `json:"requestURI"`
ObjectRef ObjectRef `json:"objectRef"`
}

type ObjectRef struct {
Resource string `json:"resource"`
Subresource string `json:"subresource,omitempty"`
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
}
19 changes: 19 additions & 0 deletions hack/observe_behavior/audit-policy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
apiVersion: audit.k8s.io/v1
kind: Policy
omitManagedFields: True
omitStages:
- RequestReceived
- ResponseStarted
rules:
- level: RequestResponse
resources:
- group: ""
resources:
- pods
- pods/status
- events
verbs:
- create
- patch
- update
- delete
37 changes: 37 additions & 0 deletions hack/observe_behavior/collection.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Copyright 2025 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

rm -f logs/*

kind create cluster --config kind-config.yaml

sleep 5

kubectl create -f test-pod.yaml
kubectl wait --for=condition=Ready pod/test-pod --timeout=60s

sleep 5

kubectl delete -f test-pod.yaml
kubectl wait --for=delete pod/test-pod --timeout=60s


sleep 5

kind delete cluster

cat ./logs/kube-apiserver-audit.log | \
grep test-pod | \
go run audit-format.go > ./logs/audit-log.yaml
31 changes: 31 additions & 0 deletions hack/observe_behavior/kind-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
kubeadmConfigPatches:
- |
kind: ClusterConfiguration
apiServer:
# enable auditing flags on the API server
extraArgs:
audit-log-path: /var/log/kubernetes/kube-apiserver-audit.log
audit-policy-file: /etc/kubernetes/policies/audit-policy.yaml
# mount new files / directories on the control plane
extraVolumes:
- name: audit-policies
hostPath: /etc/kubernetes/policies
mountPath: /etc/kubernetes/policies
readOnly: true
pathType: DirectoryOrCreate
- name: audit-logs
hostPath: /var/log/kubernetes
mountPath: /var/log/kubernetes
readOnly: false
pathType: DirectoryOrCreate
extraMounts:
- hostPath: ./audit-policy.yaml
containerPath: /etc/kubernetes/policies/audit-policy.yaml
readOnly: true
- hostPath: ./logs
containerPath: /var/log/kubernetes
readOnly: false
22 changes: 22 additions & 0 deletions hack/observe_behavior/test-pod.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
apiVersion: v1
kind: Pod
metadata:
name: test-pod
namespace: default
spec:
terminationGracePeriodSeconds: 30
containers:
- image: docker.io/library/nginx:latest
imagePullPolicy: Always
name: nginx
lifecycle:
postStart:
exec:
command:
- sleep
- '10'
preStop:
exec:
command:
- sleep
- '10'
Loading