diff --git a/web/backend/api/model_catalog.go b/web/backend/api/model_catalog.go index da092e89e..ce50deafe 100644 --- a/web/backend/api/model_catalog.go +++ b/web/backend/api/model_catalog.go @@ -48,7 +48,12 @@ func generateCatalogKey(provider, apiBase, apiKey string) string { return fmt.Sprintf("%s|%s|%x", provider, apiBase, hash[:6]) } -// maskAPIKeyValue masks an API key for display, keeping first 4 and last 4 chars. +// maskAPIKeyValue masks an API key for display. +// Keys longer than 12 chars show prefix + last 4 chars: "sk-****abcd". +// Keys 9-12 chars show prefix + last 2 chars: "sk-****cd". +// Shorter keys are fully masked as "****". +// Empty keys return empty string. +// Ensure at least 40% of the key will not be displayed. func maskAPIKeyValue(key string) string { key = strings.TrimSpace(key) if key == "" { @@ -57,7 +62,10 @@ func maskAPIKeyValue(key string) string { if len(key) <= 8 { return "****" } - return key[:4] + "****" + key[len(key)-4:] + if len(key) <= 12 { + return key[:3] + "****" + key[len(key)-2:] + } + return key[:3] + "****" + key[len(key)-4:] } func loadCatalogs() (*CatalogStore, error) { diff --git a/web/backend/api/model_catalog_test.go b/web/backend/api/model_catalog_test.go new file mode 100644 index 000000000..76138fdcd --- /dev/null +++ b/web/backend/api/model_catalog_test.go @@ -0,0 +1,87 @@ +package api + +import ( + "strings" + "testing" +) + +func TestMaskAPIKeyValue(t *testing.T) { + tests := []struct { + name string + key string + want string + }{ + { + name: "empty key", + key: "", + want: "", + }, + { + name: "whitespace only", + key: " ", + want: "", + }, + { + name: "short key fully masked", + key: "abcd", + want: "****", + }, + { + name: "length 8 boundary fully masked", + key: "12345678", + want: "****", + }, + { + name: "length 9 boundary shows last 2", + key: "123456789", + want: "123****89", + }, + { + name: "length 10 shows last 2", + key: "1234567890", + want: "123****90", + }, + { + name: "length 12 boundary shows last 2", + key: "abcdefghijkl", + want: "abc****kl", + }, + { + name: "length 13 boundary shows last 4", + key: "abcdefghijklm", + want: "abc****jklm", + }, + { + name: "typical api key", + key: "sk-1234567890abcd", + want: "sk-****abcd", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := maskAPIKeyValue(tc.key) + if got != tc.want { + t.Fatalf("maskAPIKeyValue(%q) = %q, want %q", tc.key, got, tc.want) + } + + if tc.key != "" { + displayed := strings.Replace(got, "****", "", 1) + if len(strings.TrimSpace(tc.key)) <= 8 { + if displayed != "" { + t.Fatalf("maskAPIKeyValue(%q) displayed part = %q, want empty", tc.key, displayed) + } + } else { + if len(displayed)*10 > len(strings.TrimSpace(tc.key))*6 { + t.Fatalf( + "maskAPIKeyValue(%q) displayed length = %d, want at most 60%% of %d", + tc.key, + len(displayed), + len(strings.TrimSpace(tc.key)), + ) + } + } + } + }) + } +}