Files
archie/modules/governance/models_api_test.go
T
sam fa96ee852c fix(governance): refuse to delete a model alias a saved workflow names (#2097)
The delete refused only a missing alias, so removing the default model, or an
alias a saved workflow still names, succeeded and those workflows failed at
their agent step.

The runs module now reports the saved workflows that give an agent step a
model, treating a step that names none as the default, and the delete is
refused with a conflict that names them. The dashboard already shows a delete's
failure inline beside the alias, so the operator sees which workflows to move
first.
2026-11-27 19:28:13 +11:00

192 lines
6.1 KiB
Go

package governance
import (
"context"
"errors"
"log/slog"
"net/http"
"strings"
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/runtime"
)
type fakeBearerCredentials struct {
tokens map[uuid.UUID]string
names map[uuid.UUID]string
sawPrincipal bool
sawOrg OrgID
}
func (f *fakeBearerCredentials) record(ctx context.Context) {
_, f.sawPrincipal = PrincipalFromContext(ctx)
f.sawOrg = OrgFromContext(ctx)
}
func (f *fakeBearerCredentials) BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error) {
f.record(ctx)
tok, ok := f.tokens[id]
if !ok {
return "", errors.New("credential doesn't exist")
}
return tok, nil
}
func (f *fakeBearerCredentials) BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error) {
f.record(ctx)
name, ok := f.names[id]
return name, ok, nil
}
func (f *fakeBearerCredentials) BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error) {
f.record(ctx)
return f.names, nil
}
// TestModelPolicyAllowsEveryAliasOnlyWhenUnset guards the model policy
// boundary: no policy lets every alias through, while a policy that names no
// alias allows none.
func TestModelPolicyAllowsEveryAliasOnlyWhenUnset(t *testing.T) {
cases := []struct {
name string
allowed []string
alias string
wantErr error
}{
{"no policy allows the default", nil, "", nil},
{"no policy allows a named alias", nil, "fast", nil},
{"a policy naming nothing allows no alias", []string{}, "", ErrModelNotAllowed},
{"a policy allows what it names", []string{"default", "fast"}, "fast", nil},
{"a policy refuses the alias it leaves out", []string{"fast"}, "", ErrModelNotAllowed},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if err := allowedAlias(c.allowed, c.alias); !errors.Is(err, c.wantErr) {
t.Fatalf("allowedAlias(%v, %q) error = %v, want %v", c.allowed, c.alias, err, c.wantErr)
}
})
}
}
// TestModelProviderCredentialBoundary guards the governance->connectors
// credential boundary: governance strips any caller principal so lookups run in
// organisation scope only, and refuses inaccessible or zero-UUID credentials.
func TestModelProviderCredentialBoundary(t *testing.T) {
runtime.RegisterBuiltinClasses()
validCredID := uuid.New()
missingCredID := uuid.New()
zeroCredID := uuid.Nil
creds := &fakeBearerCredentials{
tokens: map[uuid.UUID]string{validCredID: "plainly-fake-api-key"},
names: map[uuid.UUID]string{validCredID: "openai-key"},
}
m := &Module{orgID: "org-a", log: slog.New(slog.DiscardHandler), credentials: creds}
callerCtx := WithOrg(WithPrincipal(t.Context(), Principal{IdentityID: "alice", Kind: KindUser, Org: "other-org"}), "other-org")
t.Run("endpoint rejects zero credential UUID", func(t *testing.T) {
if _, err := endpoint("openai", "openai", "", &zeroCredID); err == nil {
t.Fatal("endpoint() accepted zero UUID credential id")
}
})
t.Run("checkCredential strips caller principal and enforces org scope", func(t *testing.T) {
name, err := m.checkCredential(callerCtx, uuid.NullUUID{UUID: validCredID, Valid: true})
if err != nil {
t.Fatalf("checkCredential(valid) error = %v", err)
}
if name != "openai-key" {
t.Errorf("checkCredential(valid) name = %q, want %q", name, "openai-key")
}
if creds.sawPrincipal {
t.Fatal("checkCredential leaked caller Principal into connectors")
}
if creds.sawOrg != DefaultOrgID {
t.Errorf("checkCredential org = %q, want %q", creds.sawOrg, DefaultOrgID)
}
_, err = m.checkCredential(callerCtx, uuid.NullUUID{UUID: missingCredID, Valid: true})
var statusErr huma.StatusError
if !errors.As(err, &statusErr) || statusErr.GetStatus() != http.StatusBadRequest {
t.Fatalf("checkCredential(missing) error = %v, want 400 Bad Request", err)
}
})
t.Run("provider strips caller principal when calling BearerTokenByID", func(t *testing.T) {
_, _, err := m.provider(callerCtx, Model{
ProviderID: uuid.New(),
Model: "gpt-4o-mini",
Class: "openai",
APIKeyCredentialID: &validCredID,
})
if err != nil {
t.Fatalf("provider(valid) error = %v", err)
}
if creds.sawPrincipal {
t.Fatal("provider leaked caller Principal into BearerTokenByID")
}
if creds.sawOrg != DefaultOrgID {
t.Errorf("provider org = %q, want %q", creds.sawOrg, DefaultOrgID)
}
if _, _, err := m.provider(callerCtx, Model{
ProviderID: uuid.New(),
Model: "gpt-4o-mini",
Class: "openai",
APIKeyCredentialID: &missingCredID,
}); err == nil {
t.Fatal("provider(missing) succeeded, want error")
}
})
}
// aliasUsers is the runs module as the models routes see it: the saved
// workflows that name an alias.
type aliasUsers struct {
asked string
workflows []string
err error
}
func (a *aliasUsers) WorkflowsUsingModel(_ context.Context, _, alias string) ([]string, error) {
a.asked = alias
return a.workflows, a.err
}
// TestDeletingAnAliasAWorkflowUsesIsRefused guards #2097: the delete refused
// only a missing alias, so removing the default model, or one a saved workflow
// still names, succeeded and those workflows failed at their agent step.
func TestDeletingAnAliasAWorkflowUsesIsRefused(t *testing.T) {
users := &aliasUsers{workflows: []string{"remediate", "triage"}}
m := NewModule(nil, slog.New(slog.DiscardHandler), "org-sys")
m.UseWorkflowAliases(users)
_, err := m.deleteAgentModel(t.Context(), &agentModelAlias{Alias: "fast"})
if got := statusCode(t, err); got != http.StatusConflict {
t.Fatalf("status = %d (%v), want a conflict", got, err)
}
for _, name := range users.workflows {
if !strings.Contains(err.Error(), name) {
t.Fatalf("refusal %q does not name %q", err, name)
}
}
if users.asked != "fast" {
t.Fatalf("asked about alias %q, want fast", users.asked)
}
}
// statusCode reads the HTTP status a handler's error carries.
func statusCode(t *testing.T, err error) int {
t.Helper()
if err == nil {
return http.StatusOK
}
var se huma.StatusError
if !errors.As(err, &se) {
t.Fatalf("error %v carries no status", err)
}
return se.GetStatus()
}