Skip to content
Merged
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
57 changes: 53 additions & 4 deletions acceleration/internal/store/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,35 @@ var shapedCredentials = []shapedCredential{
// escape) or a quote, so an encoded one also takes the encoded parameters after it.
var queryCredential = regexp.MustCompile(`(?i)((?:[?&"]|&|\\u0026|%(?:25)*3F|%(?:25)*26)(?:key|token)(?:=|\\u003d|%(?:25)*3D))[^&\s"\x27#\\]+`)

// encodedCredential is a credential name and an encoded equals sign (%3D, or %253D twice
// encoded) with the value after it, where no ? or & stands before the name: the text of an
// encoded query cut at the parameter ("key%3D<hex>"), or a parameter after another separator
// such as %22. The names are the ones credentialText takes, and as it takes them: api_key,
// access_token, password, secret and the others wherever they stand, in any case and with or
// without their separator (x_api_key, accessToken, clientSecret), and id_token after an
// underscore or a boundary. Key and token, which end other names, take a boundary before them:
// the start of the text, a character that is not a letter, digit or underscore, or an encoded
// character, once or twice encoded (%22, %2522), so monkey%3D1, max_token%3D256 and
// sort_key%3Ddate stay. The name and the boundary are kept. The value is read as
// queryCredential reads it, whatever its length: a parameter named key is a key. A name with a
// plain = is the rule of credentialText and queryCredential.
var encodedCredential = regexp.MustCompile(`(?i)((?:^|[^A-Za-z0-9_]|%(?:25)*[0-9A-Fa-f]{2}|\\[a-z]|\\u[0-9A-Fa-f]{4})(?:key|token|id[_-]?token)|_id[_-]?token|api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|private[_-]?key|password|secret)(%(?:25)*3D)[^&\s"\x27#\\]+`)

// vendorKeyMessage is a provider's refusal that names the key it was sent, with no = or : to
// say so: "Invalid API key <32 hex>", "Incorrect API key provided: <key>", invalid_api_key, or
// the same for an API token. The key is the 16 characters or more of the key alphabet, base64
// (+ /, and = only as the padding at its end) and base64url (- _) included, after the phrase,
// so a request id of 8 hex digits after "Invalid API key." stays, and so does a glued
// name=value after it (model=..., request_id=...). A quote before the key, or a quote escaped as a JSON body has it
// (\"), stays with the phrase. The phrase stays and the key is taken out, unless it is a word
// (see redactVendorKeyMessage).
var vendorKeyMessage = regexp.MustCompile(`(?i)\b((?:invalid|incorrect)[\s_-]+(?:x-)?api[\s_-]?(?:key|token)\b(?:\s+provided)?\s*[:=]?\s*(?:\\?["\x27])?)([A-Za-z0-9_+/-]{16,}={0,2})()`)

// vendorKeyBefore is the same refusal with the key before the verdict: "The API key '<key>' is
// invalid", with single quotes, double quotes (raw or JSON-escaped) or none. The key has the
// same 16 character floor, and the phrase around it stays.
var vendorKeyBefore = regexp.MustCompile(`(?i)\b(api[\s_-]?(?:key|token)\s+(?:\\?["\x27])?)([A-Za-z0-9_+/-]{16,}={0,2})((?:\\?["\x27])?\s+(?:is|was)\s+(?:invalid|incorrect)\b)`)

// encodedAuthorization is an authorization or cookie header (proxy-authorization and
// set-cookie end in those names) written into a URL: the name, an optional encoded quote
// (%22, %27) and an encoded colon or equals sign (%3A, %3D), then the value to the end of its
Expand Down Expand Up @@ -172,16 +201,18 @@ func holdsWord(text string, words []string) bool {
return false
}

// redactCredentials is RedactLogText with no check first.
// redactCredentials is RedactLogText with no check first. The shaped rules run first, so a
// rule after them that takes only a part of a shaped token, as vendorKeyMessage takes a JWT
// up to its first dot, does not leave the rest of it in a shape no rule matches.
func redactCredentials(text string) string {
if holdsLegacyWord(text) {
text = redactLegacyCredentials(text)
}
for _, shaped := range shapedCredentials {
if shaped.mayMatch(text) {
text = shaped.rule.ReplaceAllString(text, "${1}[redacted]")
}
}
if holdsLegacyWord(text) {
text = redactLegacyCredentials(text)
}
return text
}

Expand All @@ -191,13 +222,31 @@ func redactLegacyCredentials(text string) string {
text = redactUnlessWord(credentialText, text)
text = urlCredential.ReplaceAllString(text, "${1}[redacted]@")
text = queryCredential.ReplaceAllString(text, "${1}[redacted]")
// The encoded key goes before the vendor phrase: the key class of the phrase stops at the %
// of %3D and would leave the value of an encoded key that follows it.
text = encodedCredential.ReplaceAllString(text, "${1}${2}[redacted]")
text = redactVendorKeyMessage(vendorKeyMessage, text)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] S1.1 This rule runs in redactLegacyCredentials, which runs before the shaped rules (redactCredentials, L204). Its key class stops at the first .. When a JWT follows the vendor phrase, the rule takes only the header, and the JWT shape rule (L82) then has nothing to match. The token's payload and signature stay in the log line and the stored field. Base redacts the same text whole. Fix: in redactCredentials, run the shapedCredentials loop before redactLegacyCredentials. I tried that and the store suite still passes; it guards every legacy rule against cutting a shaped token. Another fix is a . in the key class of vendorKeyMessage (L119). Add rows that put a fake JWT after each phrase form and expect the whole token to be [redacted]. S1.5 is here too: with +, / or = in a key, the tail after that character stays.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4157657: redactCredentials runs the shaped rules first, then the keyword rules. Test: TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut rows "jwt after the phrase" and "jwt after the phrase and a colon". Mutation (old order back): both rows fail.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit, unchanged code] N2.2 — the mutant that runs vendorKeyMessage before encodedCredential survives, and it is not equivalent: the key class (it already held -) can eat the name of an encoded parameter glued to it. In Invalid API key aaaaaaaaaaaaaaaaaaaaaaa-key%3D<secret> head gives Invalid API key [redacted]%3D[redacted], the swapped order leaves the secret. Contrived, but one row pins it: in the redact table, "key run glued to an encoded name", input Invalid API key aaaaaaaaaaaaaaaaaaaaaaa-key%3D + secret, want Invalid API key [redacted]%3D[redacted]. I checked it fails under the swap and passes on head.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4194e46: row key then an encoded key, in this order (Invalid API key <16 chars>-key%3D<secret> -> Invalid API key [redacted]%3D[redacted]). With vendorKeyMessage run before encodedCredential the row fails (the %3D value leaks); a comment in redactLegacyCredentials says why the order holds.

text = redactVendorKeyMessage(vendorKeyBefore, text)
text = encodedAuthorization.ReplaceAllString(text, "[redacted]")
text = encodedBearer.ReplaceAllString(text, "[redacted]")
text = providerCredential.ReplaceAllString(text, "[redacted]")
text = jsonToken.ReplaceAllString(text, `${1}"[redacted]"`)
return text
}

// redactVendorKeyMessage takes the key out of each match of rule (vendorKeyMessage or
// vendorKeyBefore: the phrase before it, the key, the phrase after it), but for a value that
// is a word, as redactUnlessWord does, such as authentication_failed after "invalid_api_key".
func redactVendorKeyMessage(rule *regexp.Regexp, text string) string {
return rule.ReplaceAllStringFunc(text, func(match string) string {
parts := rule.FindStringSubmatch(match)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 Mutant survives and it is a leak: rule.FindStringSubmatch(match) -> rule.FindStringSubmatch(text) passes the whole suite. Under it the first match's parts are used for every match, so Invalid API key authentication_failed_error; Invalid API key <32 hex> keeps the key (and the reverse order redacts the word). No test row has two matches in one text, so nothing pins that each match is judged on its own value.

Add to the main table of TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut (checked: all three fail under the mutant, pass on head):

  • "word then key": "Invalid API key authentication_failed_error; Invalid API key " + secret -> "Invalid API key authentication_failed_error; Invalid API key [redacted]"
  • "key then word": "Invalid API key " + secret + "; Invalid API key authentication_failed_error" -> "Invalid API key [redacted]; Invalid API key authentication_failed_error"
  • "before: word then key": "API key authentication_failed_error is invalid; API key " + secret + " is invalid" -> "API key authentication_failed_error is invalid; API key [redacted] is invalid"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f50dcdc: the reviewer's three rows added ("word then key", "key then word", "before the verdict, word then key"). Mutation FindStringSubmatch(match) -> (text): "word then key" and "key then word" fail.

if word.MatchString(parts[2]) {
return match
}
return parts[1] + "[redacted]" + parts[3]
})
}

func (s shapedCredential) mayMatch(text string) bool {
for _, literal := range s.literals {
if strings.Contains(text, literal) {
Expand Down
119 changes: 119 additions & 0 deletions acceleration/internal/store/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -138,6 +139,122 @@ func TestSafeLogTextKeepsTheRestOfTheURL(t *testing.T) {
}
}

// A key in an encoded query that no ? or & stands before (a text cut at the parameter, a name
// after an encoded quote), and a provider's refusal that names the key with no = or : before it.
// Each row is the whole answer, so what stays around the key is checked too. The rows with no
// credential are the answers base 31fd2dd96 gives, the same as the input.
func TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut(t *testing.T) {
raw := make([]byte, 16)
_, err := rand.Read(raw)
require.NoError(t, err)
secret := hex.EncodeToString(raw)
jwt := "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0." + secret
for name, tc := range map[string]struct{ in, want string }{
"jwt after the phrase": {"Invalid API token " + jwt, "Invalid API token [redacted]"},
"jwt after the phrase and a colon": {"Invalid API key: " + jwt, "Invalid API key: [redacted]"},
"key": {"key%3D" + secret, "key%3D[redacted]"},
"api_key": {"api_key%3D" + secret, "api_key%3D[redacted]"},
"token": {"token%3D" + secret, "token%3D[redacted]"},
"mixed case equals sign": {"key%3d" + secret, "key%3d[redacted]"},
"upper case name": {"API_KEY%3d" + secret, "API_KEY%3d[redacted]"},
"name with a prefix": {"x_api_key%3D" + secret, "x_api_key%3D[redacted]"},
"apikey": {"apikey%3D" + secret, "apikey%3D[redacted]"},
"access_token": {"access_token%3D" + secret, "access_token%3D[redacted]"},
"client_secret": {"client_secret%3D" + secret, "client_secret%3D[redacted]"},
"password": {"password%3D" + secret, "password%3D[redacted]"},
"camel case accessToken": {"accessToken%3D" + secret, "accessToken%3D[redacted]"},
"camel case clientSecret": {"clientSecret%3D" + secret, "clientSecret%3D[redacted]"},
"camel case authToken": {"authToken%3D" + secret, "authToken%3D[redacted]"},
"camel case refreshToken": {"refreshToken%3D" + secret, "refreshToken%3D[redacted]"},
"camel case idToken": {"idToken%3D" + secret, "idToken%3D[redacted]"},
"id_token after a prefix": {"x_id_token%3D" + secret, "x_id_token%3D[redacted]"},
"camel case privateKey": {"privateKey%3D" + secret, "privateKey%3D[redacted]"},
"after a twice-encoded quote": {"q%3D%2522key%253D" + secret, "q%3D%2522key%253D[redacted]"},
"after a twice-encoded space": {"%2520key%253D" + secret, "%2520key%253D[redacted]"},
"camel case after a twice-encoded ?": {"%253FaccessToken%253D" + secret, "%253FaccessToken%253D[redacted]"},
"camel case apiKey": {"apiKey%3D" + secret, "apiKey%3D[redacted]"},
"twice-encoded equals sign": {"key%253D" + secret, "key%253D[redacted]"},
"in the middle of a sentence": {"request failed: key%3D" + secret + " tail", "request failed: key%3D[redacted] tail"},
"after an encoded quote": {"q=%22key%3D" + secret + "%22", "q=%22key%3D[redacted]"},
"in the middle of a query": {"wss://live.example/ws?a=1&key%3D" + secret + "&b=2", "wss://live.example/ws?a=1&key%3D[redacted]&b=2"},
"in an encoded url": {"https%3A%2F%2Flive.example%2Fws%3Fa%3D1%26key%3D" + secret, "https%3A%2F%2Flive.example%2Fws%3Fa%3D1%26key%3D[redacted]"},
"after a json-escaped newline": {`{"m":"x\nkey%3D` + secret + `"}`, `{"m":"x\nkey%3D[redacted]"}`},
"after a json-escaped quote": {`{"m":"\u0022key%3D` + secret + `"}`, `{"m":"\u0022key%3D[redacted]"}`},
"ends at a quote": {`"key%3D` + secret + `" failed`, `"key%3D[redacted]" failed`},
"ends at a single quote": {`'key%3D` + secret + `' failed`, `'key%3D[redacted]' failed`},
"ends at a fragment": {"key%3D" + secret + "#top", "key%3D[redacted]#top"},
"ends at a json escape": {"key%3D" + secret + `\u0026model=m`, "key%3D[redacted]" + `\u0026model=m`},
"invalid api key": {"Invalid API key " + secret, "Invalid API key [redacted]"},
"invalid api key with a colon": {"invalid api key: " + secret, "invalid api key: [redacted]"},
"incorrect api key provided": {"Incorrect API key provided: " + secret, "Incorrect API key provided: [redacted]"},
"incorrect key from a vendor": {"Incorrect API key provided: sk-" + secret, "Incorrect API key provided: [redacted]"},
"invalid_api_key code": {"invalid_api_key " + secret, "invalid_api_key [redacted]"},
"invalid x-api-key": {"Invalid x-api-key " + secret, "Invalid x-api-key [redacted]"},
"invalid api token": {"Invalid API token " + secret, "Invalid API token [redacted]"},
"key of 16 characters": {"Invalid API key " + secret[:16], "Invalid API key [redacted]"},
"after a prefix and a colon": {`provider: 401: {"message":"Invalid API key ` + secret + `"}`, `provider: 401: {"message":"Invalid API key [redacted]"}`},
"text after the key": {"Invalid API key " + secret + " for model m", "Invalid API key [redacted] for model m"},
"word then key": {"Invalid API key authentication_failed_error; Invalid API key " + secret, "Invalid API key authentication_failed_error; Invalid API key [redacted]"},
"key then word": {"Invalid API key " + secret + "; Invalid API key authentication_failed_error", "Invalid API key [redacted]; Invalid API key authentication_failed_error"},
"before the verdict, word then key": {"API key authentication_failed_error is invalid; API key " + secret + " is invalid", "API key authentication_failed_error is invalid; API key [redacted] is invalid"},
"key before the verdict, single quotes": {"The API key '" + secret + "' is invalid", "The API key '[redacted]' is invalid"},
"key before the verdict, double quotes": {`The API key "` + secret + `" is invalid`, `The API key "[redacted]" is invalid`},
"key before the verdict, no quotes": {"The API key " + secret + " is invalid", "The API key [redacted] is invalid"},
"api token before the verdict": {"api token '" + secret + "' was incorrect", "api token '[redacted]' was incorrect"},
"single-quoted key after a colon": {"Invalid API key: '" + secret + "'", "Invalid API key: '[redacted]'"},
"double-quoted key after the phrase": {`Invalid API key "` + secret + `"`, `Invalid API key "[redacted]"`},
"json-escaped quote after the phrase": {`{"message":"Invalid API key: \"` + secret + `\""}`, `{"message":"Invalid API key: \"[redacted]\""}`},
"json-escaped quotes before the verdict": {`{"detail":"The API key \"` + secret + `\" is invalid"}`, `{"detail":"The API key \"[redacted]\" is invalid"}`},
"base64 key": {"Invalid API key Ab" + secret[:10] + "+/" + secret[10:] + "==", "Invalid API key [redacted]"},
"base64 key before the verdict": {"The API key '" + secret[:16] + "+/" + secret[16:] + "=' is invalid", "The API key '[redacted]' is invalid"},
"key of 16 before the verdict": {"API key '" + secret[:16] + "' is invalid for model m", "API key '[redacted]' is invalid for model m"},
"key then an encoded key, in this order": {"Invalid API key " + secret[:16] + "-key%3D" + secret, "Invalid API key [redacted]%3D[redacted]"},
} {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.want, SafeLogText(tc.in))
require.Equal(t, tc.want, SafeLogText(tc.want), "a second pass changes the text")
})
}
for name, text := range map[string]string{
"no key named": "Invalid API key provided",
"no key named, other wording": "Incorrect API key provided",
"request id of 8 hex digits": "Invalid API key " + secret[:8],
"key of 15 characters": "Invalid API key " + secret[:15],
"request id after the sentence": "Invalid API key. Request id " + secret[:8],
"request id in parentheses": "Invalid API key (request " + secret[:8] + ")",
"a word after the phrase": "invalid_api_key authentication_failed_error",
"an id with no phrase": "request id " + secret,
"id of 15 before the verdict": "API key '" + secret[:15] + "' is invalid",
"id of 8 before the verdict": "API key " + secret[:8] + " is invalid",
"a word before the verdict": "API key authentication_failed_error is invalid",
"key before another verdict": "API key " + secret + " is set",
"phrase with no key": "API key not valid. Please pass a valid API key.",
"already redacted vendor text": "Invalid API key [redacted]",
"already redacted query": "key%3D[redacted]",
"name with no value": "key%3D",
"name inside a word": "monkey%3D" + secret,
"key word glued to the phrase": "Invalid API keystore" + secret,
"plural name": "keys%3D" + secret,
"tokens": "max_tokens%3D256 tokens%3D12",
"a name ending in _token": "max_token%3D256",
"a name ending in _key": "sort_key%3Ddate",
"a name ending in id_token": "valid_token%3D" + secret,
"phrase glued to the word before it": "noninvalid api key " + secret,
"phrase glued together": "invalidapi key " + secret,
"name glued to the word before it": "rapi key " + secret + " is invalid",
"name glued to the key": "API key" + secret + " is invalid",
"key glued to the verdict": "API key " + secret + "is invalid",
"name with a plain equals": "the key=value pair",
"a name=value after the phrase": "Invalid API key provided: model=gpt-4o-mini-transcribe",
"a request id after the colon": "Invalid API key: request_id=req_0123456789abcdef",
"a name=value before the verdict": "API key model=gpt-4o-mini-transcribe is invalid",
} {
t.Run("keeps "+name, func(t *testing.T) {
require.Equal(t, text, SafeLogText(text))
})
}
}

// Our own errors name a bearer token, a secret or a password in prose, and a WWW-Authenticate
// challenge starts with Bearer and an auth-param (RFC 6750 section 3): with no credential in
// them, they are kept byte for byte.
Expand Down Expand Up @@ -495,6 +612,8 @@ func TestEveryTextARuleRedactsPassesTheCheck(t *testing.T) {
"client_SECRET=" + secret,
`{"Password":"` + secret + `"}`,
"wss://live.example/ws?KEY=" + secret,
"key%3d" + secret,
"Invalid API key " + secret,
"https://ipinfo.io/json?Token=" + secret,
"https://user:" + secret + "@example.com",
"used sk-" + secret,
Expand Down
Loading