Files

72 lines
1.9 KiB
Go

package audit
import (
"regexp"
"strings"
"sync"
)
// secretRedactors are the credential patterns, compiled on first use. Redaction
// runs over every string of every replayed tool call, so compiling per call made it
// the dominant cost of replaying a long session.
var secretRedactors = sync.OnceValue(func() []*regexp.Regexp {
out := make([]*regexp.Regexp, 0, len(secretPatterns))
for _, sp := range secretPatterns {
if re, err := regexp.Compile(sp.expr); err == nil {
out = append(out, re)
}
}
return out
})
// RedactSecrets replaces recognised credential material with a masked form.
//
// The auditor itself must see the real text: detecting a leaked credential
// requires reading it. Anything that leaves the process - an external judge, a
// log shipped elsewhere - must not. This is the boundary between those two.
func RedactSecrets(text string) string {
if text == "" {
return text
}
for _, re := range secretRedactors() {
text = re.ReplaceAllStringFunc(text, maskSecret)
}
return text
}
// RedactValues redacts every string in a decoded JSON value, leaving structure
// intact so a judge can still reason about the shape of the call.
func RedactValues(value any) any {
switch v := value.(type) {
case string:
return RedactSecrets(v)
case []any:
out := make([]any, len(v))
for i, item := range v {
out[i] = RedactValues(item)
}
return out
case map[string]any:
out := make(map[string]any, len(v))
for key, item := range v {
out[key] = RedactValues(item)
}
return out
default:
return value
}
}
// Truncate cuts a string to at most n runes, marking that it was cut. A judge
// that cannot see the whole output must be told so rather than guessing.
func Truncate(s string, n int) string {
if n <= 0 {
return s
}
runes := []rune(strings.TrimSpace(s))
if len(runes) <= n {
return string(runes)
}
return string(runes[:n]) + "\n[truncated by auditor]"
}