package runtime import ( "context" "crypto/sha256" "encoding/hex" "strings" "testing" agentllm "agent-native/runtime/llm" core "agent-system-core" ) func TestUnauthorizedNamesKeySourceWithoutRevealingIt(t *testing.T) { const secret = "sk-owner-secret" SecretLookup = func(owner, service string) (string, string, bool) { if owner == "weichen" && service == "models.chat" { return secret, "owner", true } return "", "", false } t.Cleanup(func() { SecretLookup = nil }) route := ResolveChatModel(core.AgentProfile{Owner: "weichen"}, effOf(map[string]any{ "models": map[string]any{"chat": map[string]any{"model": "m", "baseUrl": "https://gw", "apiKey": "sk-settings"}}, })) if route.Key != secret || route.KeySource != "owner" { t.Fatalf("route = %+v", route) } msg := "provider status 401: invalid api key" stream := annotateKeyFailure(func(context.Context, string, []agentllm.Message, []agentllm.ToolDecl, agentllm.StreamOptions) <-chan agentllm.Event { ch := make(chan agentllm.Event, 1) ch <- agentllm.Event{ Kind: agentllm.KindError, HTTPStatus: 401, ErrorMessage: msg, Err: &agentllm.StreamError{Message: msg}, } close(ch) return ch }, route) ev := <-stream(context.Background(), "m", nil, nil, agentllm.StreamOptions{}) got := ev.Err.Error() sum := sha256.Sum256([]byte(secret)) fp := hex.EncodeToString(sum[:4]) if strings.Contains(got, secret) || !strings.Contains(got, "source=owner fp="+fp) || !strings.Contains(ev.ErrorMessage, "source=owner fp="+fp) { t.Fatalf("error = %s", got) } }