| 1 | package secrets |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "net/url" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "unicode/utf8" |
| 10 | |
| 11 | "reasonix/internal/provider" |
| 12 | ) |
| 13 | |
| 14 | func TestFailureDetailPreservesCauseWithoutCredentialsOrResponseEnvelope(t *testing.T) { |
| 15 | for _, tc := range []struct { |
| 16 | err error |
| 17 | want string |
| 18 | }{ |
| 19 | {errors.New("unknown vision model fixture/vision"), "unknown vision model fixture/vision"}, |
| 20 | {&provider.ImageInputError{Err: errors.New("configured image understanding model does not accept images")}, "does not accept images"}, |
| 21 | {&provider.ImageInputError{Err: &provider.APIError{Status: 400, Body: `{"error":{"message":"bad image API_KEY=sk-private-value-12345"},"request":{"prompt":"private prompt","image":"private pixels"}}`}}, "bad image"}, |
| 22 | {&provider.AuthError{Status: 401, Body: `{"error":{"message":"expired token sk-private-value-12345"}}`}, "expired token"}, |
| 23 | {&provider.APIError{Status: 502, Body: "private prompt private pixels"}, "502"}, |
| 24 | {&provider.RequestFailure{Operation: "send", Err: &url.Error{Op: "Post", URL: "https://user:password@provider.test/v1/chat?prompt=private+prompt#private-fragment", Err: errors.New("connection refused")}}, "connection refused"}, |
| 25 | } { |
| 26 | got := FailureDetail(tc.err) |
| 27 | if !strings.Contains(got, tc.want) { |
| 28 | t.Fatalf("lost cause: %q", got) |
| 29 | } |
| 30 | for _, private := range []string{"sk-private-value-12345", "private prompt", "private pixels", "password", "private-fragment", "prompt="} { |
| 31 | if strings.Contains(got, private) { |
| 32 | t.Fatalf("leaked %q: %q", private, got) |
| 33 | } |
| 34 | } |
| 35 | b, _ := json.Marshal(got) |
| 36 | if !json.Valid(b) { |
| 37 | t.Fatal("invalid persisted text") |
| 38 | } |
| 39 | } |
| 40 | if FailureDetail(nil) != "" { |
| 41 | t.Fatal("nil failure") |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | func TestFailureDetailRedactsBeforeBoundingUnicode(t *testing.T) { |
| 46 | got := FailureDetail(errors.New(strings.Repeat("图", 4090) + " API_KEY=" + strings.Repeat("aB1", 4000))) |
| 47 | if !utf8.ValidString(got) || len([]rune(got)) > 4097 || strings.Contains(got, "aB1") { |
| 48 | t.Fatalf("invalid bound/redaction: %q", got) |
| 49 | } |
| 50 | } |
| 51 |