Files
ai/controllers/iam_key_resolve_test.go
zeekayandHanzo Dev 9b96b749b8 auth: two key shapes, and the store decides which is which
hk- is gone. IAM resolves sk-, which authenticates, and pk-, which names an
org and authenticates nobody; every other spelling — hk- among them — answers
to no live credential and comes back key_unknown, which keyRefusal turns into
the one sentence a stranded holder can act on: mint a new one. Nothing here
special-cases the retired prefix, because inventing a case for it would put
the third family back.

That leaves the dispatch unable to tell two families apart by prefix: the key
this estate mints and an upstream vendor key wear the same three characters.
So it stops trying. The provider table is asked first — an exact lookup, so it
can never claim a key it does not hold — and anything it misses is put to IAM.
The order matters only for who answers when NEITHER owns the key, and IAM's
refusal names the cure where a provider miss can only say "invalid".

resolveBillingKey skipped every sk- before it reached the cache, back when
sk- meant "vendor key, billed elsewhere". Keeping that would now skip the main
credential and cost IAM keys their router-level gate, so only pk- skips. The
IAM miss is cached alongside the hit, or a vendor key would buy a fresh
round-trip on every request it makes.

TestGetUserByAccessKey_RetiredPrefixGetsTheActionableRefusal pins the outcome:
an hk- key gets "not recognized … Mint a new one", never the bare "the entity
does not exist" relay that sent people looking for a deleted organization, and
the refusal carries the prefix only.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-02 13:40:28 -07:00

134 lines
5.0 KiB
Go

// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
// TestGetUserByAccessKeyUsesClientSecretBasic pins the ONE transport sk- key
// resolution may use.
//
// IAM gates get-user?accessKey= on an authenticated confidential-APP principal
// (authz.CapKeyResolve requires p.App != ""), and it derives p.App ONLY from
// client_secret_basic. Both other spellings have shipped to production and both
// were dead ends:
//
// - clientId/clientSecret as QUERY PARAMS → 401 "authentication required"
// (no principal at all — and a credential in a URL, which lands in logs)
// - a client_credentials BEARER → 200 {"status":"error",
// "msg":"auth:Unauthorized operation"} (a machine token has no user row, so
// the principal is org-scoped with an EMPTY App and holds the capability
// vacuously — which the handler refuses)
//
// So this test asserts the positive (Basic, matching the configured credential)
// AND the negative (no credential anywhere in the URL).
func TestGetUserByAccessKeyUsesClientSecretBasic(t *testing.T) {
const (
clientID = "hanzo-cloud"
clientSecret = "s3cr3t"
accessKey = "sk-testkey"
)
var gotQuery url.Values
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotQuery = r.URL.Query()
id, secret, ok := r.BasicAuth()
if !ok {
t.Errorf("no Basic credential presented; Authorization=%q", r.Header.Get("Authorization"))
w.WriteHeader(http.StatusUnauthorized)
return
}
if id != clientID || secret != clientSecret {
t.Errorf("Basic credential = %q:<secret>, want %q", id, clientID)
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"status":"ok","msg":"","data":{"owner":"hanzo","name":"test-api-user"}}`))
}))
defer srv.Close()
t.Setenv("IAM_URL", srv.URL)
t.Setenv("IAM_CLIENT_ID", clientID)
t.Setenv("IAM_CLIENT_SECRET", clientSecret)
u, err := GetUserByAccessKey(accessKey)
if err != nil {
t.Fatalf("GetUserByAccessKey: %v", err)
}
if u == nil || u.Owner != "hanzo" || u.Name != "test-api-user" {
t.Fatalf("resolved user = %+v, want hanzo/test-api-user", u)
}
if got := gotQuery.Get("accessKey"); got != accessKey {
t.Errorf("accessKey query = %q, want %q", got, accessKey)
}
// No credential may ride in the URL — that is the shape IAM refuses AND a
// secret in an access log.
for _, k := range []string{"clientId", "clientSecret", "client_id", "client_secret"} {
if _, ok := gotQuery[k]; ok {
t.Errorf("credential %q leaked into the request URL", k)
}
}
}
// TestGetUserByAccessKeyRefusalIsAnError asserts a denied resolution surfaces as
// an ERROR, never a nil user with a nil error. IAM answers a refusal inside a 200
// envelope ({"status":"error"}), so a caller that branched on the HTTP code alone
// would read the denial as "no such key" and fail open.
func TestGetUserByAccessKeyRefusalIsAnError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"status":"error","msg":"auth:Unauthorized operation","data":null}`))
}))
defer srv.Close()
t.Setenv("IAM_URL", srv.URL)
t.Setenv("IAM_CLIENT_ID", "hanzo-cloud")
t.Setenv("IAM_CLIENT_SECRET", "s3cr3t")
if _, err := GetUserByAccessKey("sk-testkey"); err == nil {
t.Fatal("a refused resolution must be an error, got nil")
}
}
// TestGetUserByAccessKeyRequiresCredentials asserts the resolver fails CLOSED
// when no confidential-client credential is configured: it must not fall back to
// an unauthenticated call that IAM would 401 anyway.
func TestGetUserByAccessKeyRequiresCredentials(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Error("resolver called IAM with no configured credential")
}))
defer srv.Close()
t.Setenv("IAM_URL", srv.URL)
t.Setenv("IAM_CLIENT_ID", "")
t.Setenv("IAM_CLIENT_SECRET", "")
// iamClientCreds falls back to KMS when the env is empty; an environment that
// HAS a KMS-backed credential is not the case under test.
if id, secret := iamClientCreds(); id != "" || secret != "" {
t.Skip("a client credential is configured out-of-band; nothing to fail closed on")
}
if _, err := GetUserByAccessKey("sk-testkey"); err == nil {
t.Fatal("missing client credentials must be an error, got nil")
}
}