Reject API keys that are not valid header values at construction
Independent review Codex gpt-6-sol high: APPROVED (0 findings)
CI / ci (push) Successful in 1m30s
CI / ci (pull_request) Successful in 1m29s

FromSettings now fails with llm.ErrInvalidKey for a key with a control
character such as CR or LF, for every preset that sends a key, and
openai.New rejects such a key too, so neither defers the failure to the
first request. anthropic.New already rejected it. No error quotes the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-04 09:08:46 -04:00
co-authored by Claude Opus 5.5
parent 31322f239e
commit 08be8891da
5 changed files with 42 additions and 2 deletions
+14
View File
@@ -628,6 +628,20 @@ func TestNewRejectsBadHeaderWithoutEchoingValue(t *testing.T) {
assertNoSecret(t, err)
}
func TestNewRejectsKeyWithControlCharacter(t *testing.T) {
for _, key := range []string{testKey + "\n", testKey + "\r\nX-Injected: 1", "\x00" + testKey, testKey + "\x7f"} {
_, err := New(Config{BaseURL: "https://example.com/v1", APIKey: key, StructuredOutput: JSONSchema})
if err == nil {
t.Errorf("New(%q) = nil error", key)
continue
}
assertNoSecret(t, err)
if strings.Contains(err.Error()+fmt.Sprintf("%#v", err), key) {
t.Errorf("error leaks the key: %v", err)
}
}
}
// TestNewConfigErrorsNeverLeakKey covers every New error that names
// caller-supplied text, each with the API key embedded in that text.
func TestNewConfigErrorsNeverLeakKey(t *testing.T) {