diff --git a/internal/redaction/betterleaks.go b/internal/redaction/betterleaks.go index 567d31126..75a1c78b1 100644 --- a/internal/redaction/betterleaks.go +++ b/internal/redaction/betterleaks.go @@ -79,7 +79,7 @@ var rulesConfig string // betterleaks.toml, the betterleaks version, or the handling of findings in // this file changes what gets redacted, so that policies can tell placeholders // from different rulesets apart. Version 1 is the plain default ruleset. -const RulesetVersion = 4 +const RulesetVersion = 5 var ( defaultScanner = sync.OnceValues(newBetterleaksScanner) diff --git a/internal/redaction/betterleaks.toml b/internal/redaction/betterleaks.toml index 199063def..ca7ff4fe9 100644 --- a/internal/redaction/betterleaks.toml +++ b/internal/redaction/betterleaks.toml @@ -32,6 +32,14 @@ regexTarget = "match" # a quote, a backtick, whitespace, a semicolon, or an escaped line break. regexes = ['''\bSHA256:[A-Za-z0-9+/]{43}(?:[\x60'"\s;]|\\[nr])?$'''] +[[allowlists]] +description = "Issue tracker keys, such as the Jira key in the arguments of a Jira tool call" +targetRules = ["generic-api-key"] +# A key such as {"issueIdOrKey": "PROJ-1234"} has the shape of a keyword and a +# value, and a long project key passes the entropy threshold. A Jira project key +# has at most 10 characters by default. +regexes = ['''^[A-Z][A-Z0-9_]{1,9}-[0-9]+$'''] + [[allowlists]] description = "Code expressions, test durations and the bare key word, which are not password values" targetRules = ["generic-password"] @@ -55,6 +63,29 @@ regexes = [ '''^\([0-9]+(?:\.[0-9]+)?(?:ns|us|µs|ms|s|m|h)\)(?:\\+[nrt].*)?$''', ] +[[allowlists]] +description = "A variable that names a credential, such as Password: registryPassword in code" +targetRules = ["generic-password"] +regexTarget = "match" +# The default rule drops unquoted values in code files, but it reads the file +# type from a path that the scanned document does not have. Only an unquoted +# value shaped like a code identifier is kept: a camelCase or snake_case name +# that holds a credential word, or the bare word secret or token that a code +# delimiter ends, as in "user, password = secret, secret". A quoted value, a +# value with a digit such as abcToken123, and a plain word such as supersecret +# in a config file or a command line, are still redacted. "key" is not a +# credential word here, because passwords such as "monkey" hold it. +regexes = [ + # camelCase with the credential word inside: registryPassword, githubToken. + '''^(?i:passw(?:or)?d|psw|[_.-]pw)\b[ \t]{0,3}(?:=>|:=|=|:)[ \t]{0,5}[a-z][A-Za-z]*(?:Passw|Pwd|Secret|Token|Cred)[A-Za-z]*(?:\\+[nrt].*|[ \t]*[,;)}\]]?|[ \t]+(?:#|//|/\*|--).*)$''', + # camelCase that starts with the credential word: secretValue, tokenFile. + '''^(?i:passw(?:or)?d|psw|[_.-]pw)\b[ \t]{0,3}(?:=>|:=|=|:)[ \t]{0,5}(?:passw|pwd|secret|token|cred)[a-z]*[A-Z][A-Za-z]*(?:\\+[nrt].*|[ \t]*[,;)}\]]?|[ \t]+(?:#|//|/\*|--).*)$''', + # snake_case with the credential word as one part: db_password, client_secret. + '''^(?i:passw(?:or)?d|psw|[_.-]pw)\b[ \t]{0,3}(?:=>|:=|=|:)[ \t]{0,5}[a-z_]*(?:_(?:passw|pwd|secret|token|cred)|(?:passw|pwd|secret|token|cred)[a-z]*_)[a-z_]*(?:\\+[nrt].*|[ \t]*[,;)}\]]?|[ \t]+(?:#|//|/\*|--).*)$''', + # The bare word secret or token, ended by a code delimiter. + '''^(?i:passw(?:or)?d|psw|[_.-]pw)\b[ \t]{0,3}(?:=>|:=|=|:)[ \t]{0,5}(?:secret|token)[ \t]*[,;)}\]]$''', +] + [[allowlists]] description = "Exact password-field CSS selectors used by login helpers" targetRules = ["generic-password"] diff --git a/internal/redaction/precision_test.go b/internal/redaction/precision_test.go index 6adba9735..1555b9643 100644 --- a/internal/redaction/precision_test.go +++ b/internal/redaction/precision_test.go @@ -40,6 +40,11 @@ const ( // sampleSSHFingerprint is the unpadded base64 of a SHA-256 hash, as // OpenSSH prints the fingerprint of a public key after SHA256: sampleSSHFingerprint = "q3Rk8vLm2+Zx7Pw4" + "Tn9sYbHc1/Fd6Gj0" + "Ue5Ai8Ko2Ws" + // sampleIssueKey is a Jira key with a project key long enough to pass the + // entropy threshold of generic-api-key. + sampleIssueKey = "FOOBARQUIX" + "-8172" + // sampleLetterPassword is a password of letters only. + sampleLetterPassword = "correcthorse" + "batterystaple" ruleGenericAPIKey = "generic-api-key" ruleGitHubPAT = "github-pat" @@ -163,6 +168,31 @@ func TestRulesConfigKeepsNonSecrets(t *testing.T) { text: "Good \"git\" signature for " + sampleEmail + " with RSA key SHA256:" + sampleSSHFingerprint + "\n", wantDefaultRule: ruleGenericAPIKey, }, + { + name: "jira key in the arguments of a tool call", + text: "issueIdOrKey: " + sampleIssueKey + "\n", + wantDefaultRule: ruleGenericAPIKey, + }, + { + name: "variable as the value of a password field in go code", + text: "\tpublish(Options{\n\t\tRegistryUsername: registryUser, RegistryPassword: registryPassword,\n\t})\n", + wantDefaultRule: genericPasswordRuleID, + }, + { + name: "variable assigned to a password in a test", + text: "if tc.auth {\n\tuser, password = secret, secret\n}\n", + wantDefaultRule: genericPasswordRuleID, + }, + { + name: "snake_case variable as the value of a password field", + text: "\tconn.Password = db_password\n", + wantDefaultRule: genericPasswordRuleID, + }, + { + name: "camelCase variable that starts with the credential word", + text: "\tcfg.Password = secretValue;\n", + wantDefaultRule: genericPasswordRuleID, + }, } for _, tc := range testCases { @@ -350,6 +380,70 @@ func TestRulesConfigStillRedactsSecrets(t *testing.T) { secret: samplePassword, wantRule: ruleCredentialURI, }, + { + name: "api key in the field of an issue key", + text: "issueIdOrKey: " + sampleAPIKey + "\n", + secret: sampleAPIKey, + wantRule: ruleGenericAPIKey, + }, + { + name: "issue key shape with a project key longer than jira allows", + text: "access_token: " + "QWXZPLMNBVKJ" + "-8172\n", + secret: "QWXZPLMNBVKJ" + "-8172", + wantRule: ruleGenericAPIKey, + }, + { + name: "unquoted password with digits in go code", + text: "\t\tRegistryUsername: registryUser, RegistryPassword: " + samplePassword + ",\n", + secret: samplePassword, + wantRule: genericPasswordRuleID, + keep: "registryUser", + }, + { + // The value names a credential, which the allowlist keeps only + // when it is unquoted. + name: "quoted password of letters only", + text: "user: " + sampleEmail + "\npassword: 'supersecret" + "value'\n", + secret: "supersecret" + "value", + wantRule: genericPasswordRuleID, + }, + { + name: "unquoted password of letters only in a config file", + text: "host: db.internal\nuser: " + sampleEmail + "\npassword: " + sampleLetterPassword + "\n", + secret: sampleLetterPassword, + wantRule: genericPasswordRuleID, + }, + { + name: "unquoted password of letters only in a command line", + text: "--password=" + sampleLetterPassword + " --image=example.com/app\n", + secret: sampleLetterPassword, + wantRule: genericPasswordRuleID, + }, + { + // It holds a credential word, but it is not shaped like a variable. + name: "weak password that holds a credential word in a config file", + text: "host: db.internal\nuser: " + sampleEmail + "\npassword: super" + "secret\n", + secret: "super" + "secret", + wantRule: genericPasswordRuleID, + }, + { + name: "camelCase value with a digit", + text: "user: " + sampleEmail + "\npassword: abcToken" + "123\n", + secret: "abcToken" + "123", + wantRule: genericPasswordRuleID, + }, + { + name: "snake_case value with a digit", + text: "\tconn.Password = db_password" + "2024\n", + secret: "db_password" + "2024", + wantRule: genericPasswordRuleID, + }, + { + name: "plain word as a password flag followed by another flag", + text: "--username=env:REG_USER --password=" + "secret --image=example.com/app\n", + secret: "=secret", + wantRule: genericPasswordRuleID, + }, } for _, tc := range testCases { @@ -408,3 +502,33 @@ func TestRedactAllowMarkerWithDefaultRules(t *testing.T) { assert.Equal(t, map[string]int{ruleGitHubPAT: 1}, report.Allowed) assert.Equal(t, map[string]int{ruleGitHubPAT: 1}, report.ByRule) } + +// TestRedactKeepsIssueKeyInSessionDocument covers a Jira key in an AI coding +// session. A match in the arguments of a tool call used to replace every copy +// of the key, which included the title and the URI of the spec entry. +func TestRedactKeepsIssueKeyInSessionDocument(t *testing.T) { + scanner, err := DefaultScanner() + require.NoError(t, err) + + doc, err := json.Marshal(map[string]any{"data": map[string]any{ + "raw_session": map[string]any{"main": []any{ + map[string]any{"type": "tool_use", "input": map[string]any{"issueIdOrKey": sampleIssueKey}}, + map[string]any{"type": "tool_result", "content": `{"key":"` + sampleIssueKey + `","summary":"Add retries to the upload step"}`}, + }}, + "spec": []any{map[string]any{ + "kind": "ticket", + "title": sampleIssueKey + ": Add retries to the upload step", + "uri": "https://example.atlassian.net/browse/" + sampleIssueKey, + }}, + }}) + require.NoError(t, err) + + _, report, err := New(defaultRulesScanner(t)).Redact(context.Background(), doc) + require.NoError(t, err) + require.Contains(t, report.RuleIDs(), ruleGenericAPIKey, "the default ruleset must replace the key, or this case tests nothing") + + got, report, err := New(scanner).Redact(context.Background(), doc) + require.NoError(t, err) + assert.Equal(t, doc, got) + assert.False(t, report.Changed(), "replaced by %v", report.RuleIDs()) +} diff --git a/pkg/attestation/crafter/materials/aicodingsession/redact.go b/pkg/attestation/crafter/materials/aicodingsession/redact.go index 8d07c96a7..82a6ef0da 100644 --- a/pkg/attestation/crafter/materials/aicodingsession/redact.go +++ b/pkg/attestation/crafter/materials/aicodingsession/redact.go @@ -19,6 +19,7 @@ import ( "context" "encoding/json" "fmt" + "regexp" "strings" "github.com/chainloop-dev/chainloop/internal/redaction" @@ -88,7 +89,7 @@ func Redact(ctx context.Context, evidence []byte) ([]byte, *redaction.Report, er return nil, nil, fmt.Errorf("initialising the secret scanner: %w", err) } - redacted, report, err := redaction.New(scanner, redaction.WithPathFilter(eligible), redaction.WithOpaque(isMedia), redaction.WithAllowMarkers()).Redact(ctx, evidence) + redacted, report, err := redaction.New(scanner, redaction.WithPathFilter(eligible), redaction.WithOpaque(isOpaque), redaction.WithAllowMarkers()).Redact(ctx, evidence) if err != nil { return nil, nil, err } @@ -128,14 +129,18 @@ func eligible(path string) bool { return true } -// isMedia reports whether obj[key] is base64 media in the transcript. -// Redaction does not scan it: the scan is slow, its matches are false, and a -// rewrite breaks the media. The shapes are the ones of the transcripts the -// CLI records, which other agents also follow: +// isOpaque reports whether obj[key] is opaque data in the transcript: base64 +// media, or an id that an agent records. Redaction does not scan it: the scan +// is slow, its matches are false, and a rewrite breaks the media or the id. +// The shapes are the ones of the transcripts the CLI records: // - the data of a base64 source block, {"type":"base64","data":...}; // - the base64 copy of a file in the metadata of a Claude Code tool result, -// next to its media type, {"base64":...,"type":"image/png"}. -func isMedia(path string, obj map[string]any, key string) bool { +// next to its media type, {"base64":...,"type":"image/png"}; +// - the apiCallId of a model call in a GitHub Copilot transcript, a long +// base64 id that generic-api-key matches because the key name holds "api". +// Only a value of that shape is opaque, so any other value under the key +// is still scanned. +func isOpaque(path string, obj map[string]any, key string) bool { if !strings.HasPrefix(path, "/data/raw_session/") { return false } @@ -146,11 +151,18 @@ func isMedia(path string, obj map[string]any, key string) bool { case "base64": mediaType, _ := obj["type"].(string) return strings.Contains(mediaType, "/") + case "apiCallId": + id, _ := obj[key].(string) + return copilotCallID.MatchString(id) } return false } +// copilotCallID is the shape of the apiCallId that GitHub Copilot records: 500 +// characters of standard base64 in the transcripts seen so far. +var copilotCallID = regexp.MustCompile(`^[A-Za-z0-9+/]{100,}={0,2}$`) + // matchPath compares a slash-separated path against a pattern in which "*" // stands for exactly one segment. func matchPath(pattern, path string) bool { diff --git a/pkg/attestation/crafter/materials/aicodingsession/redact_test.go b/pkg/attestation/crafter/materials/aicodingsession/redact_test.go index cd72cd1e6..0193da96f 100644 --- a/pkg/attestation/crafter/materials/aicodingsession/redact_test.go +++ b/pkg/attestation/crafter/materials/aicodingsession/redact_test.go @@ -312,6 +312,41 @@ func TestRedactSkipsMedia(t *testing.T) { } } +// TestRedactSkipsCopilotCallIDs covers the apiCallId of a GitHub Copilot model +// call. A value of its base64 shape is kept, although generic-api-key matches +// it. Any other value under the key is still scanned. +func TestRedactSkipsCopilotCallIDs(t *testing.T) { + callID := strings.Repeat("q3Rk8vLm2+Zx7Pw4Tn9sYbHc1/Fd6Gj0Ue5Ai8Ko2WsVb3Nq7", 10) + + session := func(id string) []byte { + var evidence Evidence + require.NoError(t, json.Unmarshal(readFixture(t, "../testdata/ai-coding-session-minimal.json"), &evidence)) + evidence.Data.RawSession = map[string][]json.RawMessage{"main": { + json.RawMessage(`{"type":"assistant.usage","data":{"model":"m","apiCallId":"` + id + `"},"source_event":{"data":{"apiCallId":"` + id + `"}}}`), + }} + doc, err := json.Marshal(evidence) + require.NoError(t, err) + return doc + } + + scanner, err := redaction.DefaultScanner() + require.NoError(t, err) + _, report, err := redaction.New(scanner, redaction.WithPathFilter(eligible)).Redact(context.Background(), session(callID)) + require.NoError(t, err) + require.True(t, report.Changed(), "the ruleset must match the id, or this case tests nothing") + + doc := session(callID) + got, report, err := Redact(context.Background(), doc) + require.NoError(t, err) + assert.False(t, report.Changed(), "replaced by %v", report.RuleIDs()) + assert.Equal(t, doc, got) + + got, report, err = Redact(context.Background(), session(fixtureGitHubPAT)) + require.NoError(t, err) + assert.True(t, report.Changed()) + assert.NotContains(t, string(got), fixtureGitHubPAT) +} + func TestRedactIsIdempotent(t *testing.T) { in := readFixture(t, "testdata/session-with-secrets.json")