Skip to content

Commit

Permalink
Add token masking in log filter
Browse files Browse the repository at this point in the history
  • Loading branch information
kramaranya committed Sep 23, 2024
1 parent b76470f commit 14e2774
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
2 changes: 2 additions & 0 deletions cmd/kube-rbac-proxy/app/kube-rbac-proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ func Run(cfg *completedProxyRunOptions) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

klog.SetLogFilter(&SanitizingFilter{})

// If OIDC configuration provided, use oidc authenticator
if cfg.auth.Authentication.OIDC.IssuerURL != "" {
oidcAuthenticator, err := authn.NewOIDCAuthenticator(ctx, cfg.auth.Authentication.OIDC)
Expand Down
70 changes: 70 additions & 0 deletions cmd/kube-rbac-proxy/app/sanitazion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package app

import (
"bytes"
"encoding/json"
)

// SanitizingFilter implements the LogFilter interface from klog with custom functions to detect and mask tokens.
type SanitizingFilter struct{}

// Filter is the filter function for non-formatting logging functions of klog.
func (sf *SanitizingFilter) Filter(args []interface{}) []interface{} {
for i, v := range args {
if strValue, ok := v.(string); ok {
if containsTokenReview(strValue) {
args[i] = maskTokenInLog(strValue)
}
}
}
return args
}

// FilterF is the filter function for formatting logging functions of klog.
func (sf *SanitizingFilter) FilterF(format string, args []interface{}) (string, []interface{}) {
for i, v := range args {
if strValue, ok := v.(string); ok {
if containsTokenReview(strValue) {
args[i] = maskTokenInLog(strValue)
}
}
}
return format, args
}

// FilterS is the filter function for structured logging functions of klog.
func (sf *SanitizingFilter) FilterS(msg string, keysAndValues []interface{}) (string, []interface{}) {
for i, v := range keysAndValues {
if strValue, ok := v.(string); ok {
if containsTokenReview(strValue) {
keysAndValues[i] = maskTokenInLog(strValue)
}
}
}
return msg, keysAndValues
}

func containsTokenReview(logStr string) bool {
return bytes.Contains([]byte(logStr), []byte(`"kind":"TokenReview"`))
}

func maskTokenInLog(logStr string) string {
var logMap map[string]interface{}
if err := json.Unmarshal([]byte(logStr), &logMap); err != nil {
return logStr
}

if spec, ok := logMap["spec"].(map[string]interface{}); ok {
if _, ok := spec["token"]; ok {
spec["token"] = "<masked>"
}
}

var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(logMap); err != nil {
return logStr
}
return buf.String()
}

0 comments on commit 14e2774

Please sign in to comment.