Reject API keys that are not valid header values at construction
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:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user