feat(governance,connectors,ui): identify model providers and keys by UUID (#2129)

This commit is contained in:
sam committed 2026-11-24 06:52:58 +11:00
1 parent c5591d95da
commit 26e19f3de4
16 files changed
+896 -213

No files matched your search

+93 -8
View File
@@ -11,6 +11,7 @@ import (
"slices"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"golang.org/x/crypto/ssh"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
@@ -77,14 +78,16 @@ type credentialInput struct {
// credentialSaved names a stored credential and the extensions restarted to
// pick it up.
type credentialSaved struct {
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
Restarted []string `json:"restarted"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
Restarted []string `json:"restarted"`
}
// credentialView shows where each field comes from, never a value.
type credentialView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
@@ -119,7 +122,8 @@ func (m *Module) putCredential(ctx context.Context, in *credentialInput) (*httpa
return nil, huma.NewError(http.StatusInternalServerError, "couldn't seal the credential")
}
c := store.Credential{Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID, Name: name, Kind: req.Kind, Sealed: sealed}
if err := m.store.PutCredential(ctx, c); err != nil {
id, err := m.store.PutCredential(ctx, c)
if err != nil {
m.log.ErrorContext(ctx, "put credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the credential")
}
@@ -127,7 +131,7 @@ func (m *Module) putCredential(ctx context.Context, in *credentialInput) (*httpa
if err != nil {
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
return httpapi.OK(credentialSaved{Name: name, Kind: req.Kind, Scope: owner.Scope, Restarted: restarted}), nil
return httpapi.OK(credentialSaved{ID: id, Name: name, Kind: req.Kind, Scope: owner.Scope, Restarted: restarted}), nil
}
func (m *Module) listCredentials(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]credentialView], error) {
@@ -180,7 +184,7 @@ func (m *Module) credentialViewOf(c store.Credential) (credentialView, error) {
if err != nil {
return credentialView{}, err
}
view := credentialView{Name: c.Name, Kind: c.Kind, Scope: c.Scope, Fields: map[string]string{}}
view := credentialView{ID: c.ID, Name: c.Name, Kind: c.Kind, Scope: c.Scope, Fields: map[string]string{}}
for name, f := range fields {
view.Fields[name] = "stored"
if f.Engine != "" {
@@ -212,6 +216,36 @@ func pickCredential(creds []store.Credential, s Scope, name string) (store.Crede
return store.Credential{}, false, nil
}
// credentialUsable reports whether s may use credential c: the instance's
// credentials reach every scope, an organisation's only that organisation, and
// a person's only that person.
func credentialUsable(s Scope, c store.Credential) bool {
return slices.Contains(s.owners(), c.Owner())
}
func (m *Module) credentialByID(ctx context.Context, s Scope, id uuid.UUID) (store.Credential, bool, error) {
if id == uuid.Nil {
return store.Credential{}, false, nil
}
creds, err := m.store.Credentials(ctx)
if err != nil {
return store.Credential{}, false, err
}
return pickCredentialByID(creds, s, id)
}
func pickCredentialByID(creds []store.Credential, s Scope, id uuid.UUID) (store.Credential, bool, error) {
if id == uuid.Nil {
return store.Credential{}, false, nil
}
for _, c := range creds {
if c.ID == id && credentialUsable(s, c) {
return c, true, nil
}
}
return store.Credential{}, false, nil
}
// BearerToken returns the token a bearer credential holds, resolved through an
// engine when it names one. The credential resolves for the scope ctx acts for.
// It is how a setting references a credential by name without the dashboard
@@ -224,13 +258,64 @@ func (m *Module) BearerToken(ctx context.Context, name string) (string, error) {
if !ok {
return "", fmt.Errorf("credential %q doesn't exist", name)
}
return m.resolveBearerToken(ctx, c)
}
// BearerTokenByID returns the token a bearer credential holds, resolved through
// an engine when it names one, provided the credential is usable by the scope
// ctx acts for.
func (m *Module) BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error) {
c, ok, err := m.credentialByID(ctx, ScopeFromContext(ctx), id)
if err != nil {
return "", err
}
if !ok {
return "", fmt.Errorf("credential %s doesn't exist", id)
}
return m.resolveBearerToken(ctx, c)
}
// BearerCredentialName returns the name of the bearer credential id if it
// exists and is usable by the scope ctx acts for.
func (m *Module) BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error) {
c, ok, err := m.credentialByID(ctx, ScopeFromContext(ctx), id)
if err != nil {
return "", false, err
}
if !ok || c.Kind != "bearer" {
return "", false, nil
}
return c.Name, true, nil
}
// BearerCredentialNames returns a map of id to name for every bearer
// credential usable by the scope ctx acts for.
func (m *Module) BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error) {
creds, err := m.store.Credentials(ctx)
if err != nil {
return nil, err
}
s := ScopeFromContext(ctx)
out := make(map[uuid.UUID]string)
for _, c := range creds {
if c.Kind == "bearer" && credentialUsable(s, c) {
out[c.ID] = c.Name
}
}
return out, nil
}
func (m *Module) resolveBearerToken(ctx context.Context, c store.Credential) (string, error) {
if c.Kind != "bearer" {
return "", fmt.Errorf("credential %q is not a bearer credential", c.Name)
}
fields, err := m.openCredential(c)
if err != nil {
return "", err
}
f, ok := fields["token"]
if !ok {
return "", fmt.Errorf("credential %q has no token field", name)
return "", fmt.Errorf("credential %q has no token field", c.Name)
}
return m.resolveField(ctx, "", c.Owner(), f)
}
+137
View File
@@ -8,6 +8,7 @@ import (
"testing"
"filippo.io/age"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
@@ -69,3 +70,139 @@ func TestCredentialRoutesNeverReturnASecret(t *testing.T) {
})
}
}
// TestBearerTokenByIDRespectsScope guards the credential ID resolution boundary:
// BearerTokenByID and the bearer name lookups enforce the caller's scope, so an
// organisation scope with no person reaches only that organisation's and the
// instance's credentials, never another organisation's or any person's.
func TestBearerTokenByIDRespectsScope(t *testing.T) {
id, err := age.GenerateX25519Identity()
if err != nil {
t.Fatal(err)
}
sealer, err := seal.New(id.String(), nil)
if err != nil {
t.Fatal(err)
}
sealBearer := func(owner store.Owner, name, token string) store.Credential {
plain, err := json.Marshal(map[string]Field{"token": {Value: token}})
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal(credentialLabel(owner, name, "bearer"), plain)
if err != nil {
t.Fatal(err)
}
return store.Credential{
ID: uuid.New(), Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID,
Name: name, Kind: "bearer", Sealed: sealed,
}
}
sealBasic := func(owner store.Owner, name string) store.Credential {
plain, err := json.Marshal(map[string]Field{"username": {Value: "u"}, "password": {Value: "plainly-fake-password-for-test"}}) //nolint:gosec // test fixture for non-bearer refusal
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal(credentialLabel(owner, name, "basic"), plain)
if err != nil {
t.Fatal(err)
}
return store.Credential{
ID: uuid.New(), Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID,
Name: name, Kind: "basic", Sealed: sealed,
}
}
instanceCred := sealBearer(store.Owner{Scope: store.ScopeInstance}, "inst-key", "plainly-fake-inst-token")
ownOrgCred := sealBearer(store.Owner{Scope: store.ScopeOrg, OrgID: "own"}, "own-org-key", "plainly-fake-own-org-token")
otherOrgCred := sealBearer(store.Owner{Scope: store.ScopeOrg, OrgID: "other"}, "other-org-key", "plainly-fake-other-org-token")
ownPersonCred := sealBearer(store.Owner{Scope: store.ScopePerson, PersonID: "me"}, "me-key", "plainly-fake-me-token")
otherPersonCred := sealBearer(store.Owner{Scope: store.ScopePerson, PersonID: "them"}, "them-key", "plainly-fake-them-token")
basicCred := sealBasic(store.Owner{Scope: store.ScopeOrg, OrgID: "own"}, "own-basic")
module := &Module{
log: slog.New(slog.DiscardHandler),
store: &fakeRegistry{creds: []store.Credential{
instanceCred, ownOrgCred, otherOrgCred, ownPersonCred, otherPersonCred, basicCred,
}},
sealer: sealer,
}
orgOwn := func(ctx context.Context) context.Context { return WithScope(ctx, Scope{OrgID: "own"}) }
personMe := func(ctx context.Context) context.Context {
return WithScope(ctx, Scope{OrgID: "own", PersonID: "me"})
}
instanceOnly := func(ctx context.Context) context.Context { return WithScope(ctx, Scope{}) }
principalMe := func(ctx context.Context) context.Context {
return governance.WithOrg(
governance.WithPrincipal(ctx, governance.Principal{IdentityID: "me", Kind: governance.KindUser, Org: "own"}),
"own",
)
}
stripped := func(ctx context.Context) context.Context {
return governance.WithOrg(governance.WithoutPrincipal(principalMe(ctx)), "own")
}
tests := []struct {
name string
scope func(context.Context) context.Context
credID uuid.UUID
wantToken string
wantName string
wantOK bool
}{
{name: "org scope reads instance credential", scope: orgOwn, credID: instanceCred.ID, wantToken: "plainly-fake-inst-token", wantName: "inst-key", wantOK: true},
{name: "org scope reads its own org credential", scope: orgOwn, credID: ownOrgCred.ID, wantToken: "plainly-fake-own-org-token", wantName: "own-org-key", wantOK: true},
{name: "org scope refuses another org credential", scope: orgOwn, credID: otherOrgCred.ID, wantOK: false},
{name: "org scope refuses any person credential", scope: orgOwn, credID: ownPersonCred.ID, wantOK: false},
{name: "org scope refuses non-bearer credential", scope: orgOwn, credID: basicCred.ID, wantOK: false},
{name: "org scope refuses nil UUID", scope: orgOwn, credID: uuid.Nil, wantOK: false},
{name: "org scope refuses unknown UUID", scope: orgOwn, credID: uuid.New(), wantOK: false},
{name: "person scope reads instance credential", scope: personMe, credID: instanceCred.ID, wantToken: "plainly-fake-inst-token", wantName: "inst-key", wantOK: true},
{name: "person scope reads own org credential", scope: personMe, credID: ownOrgCred.ID, wantToken: "plainly-fake-own-org-token", wantName: "own-org-key", wantOK: true},
{name: "person scope reads own person credential", scope: personMe, credID: ownPersonCred.ID, wantToken: "plainly-fake-me-token", wantName: "me-key", wantOK: true},
{name: "person scope refuses another person credential", scope: personMe, credID: otherPersonCred.ID, wantOK: false},
{name: "person scope refuses another org credential", scope: personMe, credID: otherOrgCred.ID, wantOK: false},
{name: "instance-only scope reads instance credential", scope: instanceOnly, credID: instanceCred.ID, wantToken: "plainly-fake-inst-token", wantName: "inst-key", wantOK: true},
{name: "instance-only scope refuses org credential", scope: instanceOnly, credID: ownOrgCred.ID, wantOK: false},
{name: "instance-only scope refuses person credential", scope: instanceOnly, credID: ownPersonCred.ID, wantOK: false},
{name: "principal context reads own person credential", scope: principalMe, credID: ownPersonCred.ID, wantToken: "plainly-fake-me-token", wantName: "me-key", wantOK: true},
{name: "principal context refuses another person credential", scope: principalMe, credID: otherPersonCred.ID, wantOK: false},
{name: "principal stripped context refuses person credential", scope: stripped, credID: ownPersonCred.ID, wantOK: false},
{name: "principal stripped context reads own org credential", scope: stripped, credID: ownOrgCred.ID, wantToken: "plainly-fake-own-org-token", wantName: "own-org-key", wantOK: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := tt.scope(t.Context())
tok, err := module.BearerTokenByID(ctx, tt.credID)
if tt.wantOK {
if err != nil {
t.Fatalf("BearerTokenByID() error = %v, want nil", err)
}
if tok != tt.wantToken {
t.Errorf("BearerTokenByID() = %q, want %q", tok, tt.wantToken)
}
} else if err == nil {
t.Fatalf("BearerTokenByID() succeeded with %q, want error", tok)
}
name, ok, err := module.BearerCredentialName(ctx, tt.credID)
if err != nil {
t.Fatalf("BearerCredentialName() error = %v", err)
}
if ok != tt.wantOK || (ok && name != tt.wantName) {
t.Errorf("BearerCredentialName() = (%q, %v), want (%q, %v)", name, ok, tt.wantName, tt.wantOK)
}
names, err := module.BearerCredentialNames(ctx)
if err != nil {
t.Fatalf("BearerCredentialNames() error = %v", err)
}
gotName, inMap := names[tt.credID]
if inMap != tt.wantOK || (inMap && gotName != tt.wantName) {
t.Errorf("BearerCredentialNames()[%s] = (%q, %v), want (%q, %v)", tt.credID, gotName, inMap, tt.wantName, tt.wantOK)
}
})
}
}
+14 -9
View File
@@ -86,7 +86,8 @@ type Owner struct {
}
// Installed is one installation with the package it configures. Name is the
// installation's own name, which a binding uses; PackageName is the package's.
// installation's own name, which a binding uses; PackageName is the package's
// immutable identifier.
type Installed struct {
ID uuid.UUID `db:"id"`
PackageID uuid.UUID `db:"package_id"`
@@ -196,7 +197,9 @@ type Credential struct {
// Owner returns the scope that owns the credential.
func (c Credential) Owner() Owner { return Owner{Scope: c.Scope, OrgID: c.OrgID, PersonID: c.PersonID} }
// Package is an extension the instance accepted.
// Package is an extension the instance accepted. Name is the immutable
// package identifier from the catalogue or acceptance request: a package is
// never renamed, and a name is never given to a different package.
type Package struct {
ID uuid.UUID `db:"id"`
Name string `db:"name"`
@@ -448,17 +451,19 @@ func (s *Store) Credentials(ctx context.Context) ([]Credential, error) {
}
// PutCredential records a credential, replacing an earlier one of that name at
// the same owner.
func (s *Store) PutCredential(ctx context.Context, c Credential) error {
if _, err := s.db.ExecContext(ctx, `
// the same owner, and returns its id.
func (s *Store) PutCredential(ctx context.Context, c Credential) (uuid.UUID, error) {
var id uuid.UUID
if err := s.db.GetContext(ctx, &id, `
INSERT INTO connectors.credentials (id, scope, org_id, person_id, name, kind, sealed)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (scope, org_id, person_id, name) DO UPDATE
SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now()`,
uuid.New(), c.Scope, c.OrgID, c.PersonID, c.Name, c.Kind, c.Sealed); err != nil {
return fmt.Errorf("put credential %q: %w", c.Name, err)
SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now()
RETURNING id`,
cmp.Or(c.ID, uuid.New()), c.Scope, c.OrgID, c.PersonID, c.Name, c.Kind, c.Sealed); err != nil {
return uuid.Nil, fmt.Errorf("put credential %q: %w", c.Name, err)
}
return nil
return id, nil
}
// Strings is a string list stored as a JSON array. Value has a value receiver
+1 -1
View File
@@ -100,7 +100,7 @@ type packageStore interface {
// credentialStore is where sealed credentials are kept.
type credentialStore interface {
Credentials(ctx context.Context) ([]store.Credential, error)
PutCredential(ctx context.Context, c store.Credential) error
PutCredential(ctx context.Context, c store.Credential) (uuid.UUID, error)
}
// registry is the module's persistence, so removal can be tested with a fake.
+6 -1
View File
@@ -50,7 +50,12 @@ func (f *fakeRegistry) Credentials(context.Context) ([]store.Credential, error)
return f.creds, nil
}
func (f *fakeRegistry) PutCredential(context.Context, store.Credential) error { return nil }
func (f *fakeRegistry) PutCredential(_ context.Context, c store.Credential) (uuid.UUID, error) {
if c.ID != uuid.Nil {
return c.ID, nil
}
return uuid.New(), nil
}
func (f *fakeRegistry) SetCapabilities(context.Context, uuid.UUID, jsontext.Value) error {
return nil
+58 -25
View File
@@ -18,6 +18,7 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/runtime"
@@ -38,8 +39,7 @@ const (
var agentAliasPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$`)
// providerName is the shape of a provider name; it is stored as an identifier
// beside the alias that names it.
// providerName is the shape of a provider name.
var providerName = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]{0,62}$`)
// ValidateAgentModelAlias accepts an empty alias for the default model.
@@ -205,21 +205,33 @@ func stepsOf(req []stepRequest) ([]Step, error) {
// Model is the model chosen for a role.
type Model struct {
// Provider is the endpoint the model is called on, and Model is its name
// ProviderID is the endpoint the model is called on, and Model is its name
// there.
Provider string `json:"provider" doc:"The provider the model is called on"`
Model string `json:"model" doc:"The model's name on the provider"`
// Class, BaseURL and APIKeyCredential are read from the provider. The
// dashboard shows the credential's name, never its token.
Class string `json:"class,omitempty" readOnly:"true"`
BaseURL string `json:"base_url,omitempty" readOnly:"true"`
APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"`
ProviderID uuid.UUID `json:"provider_id" format:"uuid" doc:"The provider the model is called on"`
Model string `json:"model" doc:"The model's name on the provider"`
// Provider, Class, BaseURL, APIKeyCredentialID and APIKeyCredential are
// read from the provider. The dashboard shows the credential's name, never
// its token.
Provider string `json:"provider,omitempty" readOnly:"true"`
Class string `json:"class,omitempty" readOnly:"true"`
BaseURL string `json:"base_url,omitempty" readOnly:"true"`
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid" readOnly:"true"`
APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"`
}
// Credentials resolves a credential's token by name. It is the connectors
// module's sealed store, so governance never holds a secret.
// Credentials resolves a credential's token and display name by id. It is the
// connectors module's sealed store, so governance never holds a secret.
type Credentials interface {
BearerToken(ctx context.Context, credential string) (string, error)
BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error)
BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error)
BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error)
}
// orgScopeCtx confines credential lookups to the organisation itself with no
// person attached, so an organisation's model provider can never reach a
// person-scoped credential or another organisation's credential.
func (m *Module) orgScopeCtx(ctx context.Context) context.Context {
return WithOrg(WithoutPrincipal(ctx), DefaultOrgID)
}
// AgentProvider builds the chat client for model, resolving the credential it
@@ -232,13 +244,13 @@ func (m *Module) AgentProvider(ctx context.Context, model Model) (chat.Provider,
// names one.
func (m *Module) provider(ctx context.Context, model Model) (chat.Provider, chat.ModelInfo, error) {
auth := runtime.AuthConfig{Type: runtime.AuthTypeNone}
if model.APIKeyCredential != "" {
if model.APIKeyCredentialID != nil && *model.APIKeyCredentialID != uuid.Nil {
if m.credentials == nil {
return nil, chat.ModelInfo{}, errors.New("no credential store is configured")
}
key, err := m.credentials.BearerToken(ctx, model.APIKeyCredential)
key, err := m.credentials.BearerTokenByID(m.orgScopeCtx(ctx), *model.APIKeyCredentialID)
if err != nil {
return nil, chat.ModelInfo{}, fmt.Errorf("agent model credential %q: %w", model.APIKeyCredential, err)
return nil, chat.ModelInfo{}, fmt.Errorf("agent model credential %s: %w", *model.APIKeyCredentialID, err)
}
auth = runtime.AuthConfig{Type: runtime.AuthTypeAPIKey, APIKey: key}
}
@@ -313,8 +325,10 @@ func (m *Module) AgentModelForAlias(ctx context.Context, alias string) (Model, e
return Model{}, ErrNoAgentModel
}
return Model{
Provider: role.Provider, Model: role.Model,
Class: role.Class, BaseURL: role.BaseURL, APIKeyCredential: role.APIKeyCredential,
ProviderID: role.ProviderID, Provider: role.Provider, Model: role.Model,
Class: role.Class, BaseURL: role.BaseURL,
APIKeyCredentialID: credentialIDPtr(role.APIKeyCredentialID),
APIKeyCredential: m.credentialName(ctx, role.APIKeyCredentialID),
}, nil
}
@@ -577,11 +591,20 @@ func (m *Module) listAgentModels(ctx context.Context, _ *struct{}) (*httpapi.Rep
m.log.ErrorContext(ctx, "list agent models", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list agent models")
}
var credNames map[uuid.UUID]string
for _, row := range rows {
if row.APIKeyCredentialID.Valid {
credNames = m.credentialNames(ctx)
break
}
}
out := make(map[string]Model, len(rows))
for _, row := range rows {
out[aliasOf(row.Role)] = Model{
Provider: row.Provider, Model: row.Model,
Class: row.Class, BaseURL: row.BaseURL, APIKeyCredential: row.APIKeyCredential,
ProviderID: row.ProviderID, Provider: row.Provider, Model: row.Model,
Class: row.Class, BaseURL: row.BaseURL,
APIKeyCredentialID: credentialIDPtr(row.APIKeyCredentialID),
APIKeyCredential: credNames[row.APIKeyCredentialID.UUID],
}
}
return httpapi.OK(out), nil
@@ -619,11 +642,14 @@ func (m *Module) putAgentModel(ctx context.Context, in *agentModelInput) (*httpa
}
model, err := m.modelOf(ctx, in.Body)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
return nil, err
}
if err := m.store.PutModelRole(ctx, store.ModelRole{
OrgID: m.orgID, Role: agentModelRole(in.Alias), Provider: model.Provider, Model: model.Model,
OrgID: m.orgID, Role: agentModelRole(in.Alias), ProviderID: model.ProviderID, Model: model.Model,
}); err != nil {
if errors.Is(err, store.ErrNoProvider) {
return nil, huma.NewError(http.StatusBadRequest, fmt.Sprintf("no provider with id %s", model.ProviderID))
}
m.log.ErrorContext(ctx, "put agent model", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the agent model")
}
@@ -660,7 +686,7 @@ const testTimeout = 60 * time.Second
func (m *Module) testAgentModel(ctx context.Context, in *struct{ Body Model }) (*httpapi.Reply[modelAnswer], error) {
model, err := m.modelOf(ctx, in.Body)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
return nil, err
}
provider, _, err := m.provider(ctx, model)
if err != nil {
@@ -681,7 +707,7 @@ func (m *Module) testAgentModel(ctx context.Context, in *struct{ Body Model }) (
// endpoint checks a provider's class and endpoint and returns it with the
// class's default base URL filled in.
func endpoint(name, class, baseURL, credential string) (store.Provider, error) {
func endpoint(name, class, baseURL string, credentialID *uuid.UUID) (store.Provider, error) {
if !providerName.MatchString(name) {
return store.Provider{}, errors.New("a provider name is lowercase letters, digits, dots, underscores or hyphens")
}
@@ -699,5 +725,12 @@ func endpoint(name, class, baseURL, credential string) (store.Provider, error) {
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return store.Provider{}, fmt.Errorf("base URL %q must be an http or https URL", baseURL)
}
return store.Provider{Name: name, Class: class, BaseURL: baseURL, APIKeyCredential: credential}, nil
var credID uuid.NullUUID
if credentialID != nil {
if *credentialID == uuid.Nil {
return store.Provider{}, errors.New("a credential id is a non-zero UUID")
}
credID = uuid.NullUUID{UUID: *credentialID, Valid: true}
}
return store.Provider{Name: name, Class: class, BaseURL: baseURL, APIKeyCredentialID: credID}, nil
}
@@ -33,6 +33,11 @@ func isUniqueViolation(err error) bool {
return ok && pgerr.Code == "23505"
}
func isForeignKeyViolation(err error) bool {
pgerr, ok := errors.AsType[*pgconn.PgError](err)
return ok && pgerr.Code == "23503"
}
func (s *Store) withTx(ctx context.Context, fn func(*sqlx.Tx) error) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
+92 -51
View File
@@ -8,39 +8,51 @@ import (
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// ModelRole is the model an organisation chose for one role: a provider and a
// model name on it.
var (
// ErrProviderNameTaken means another model provider in the organisation already has the name.
ErrProviderNameTaken = errors.New("another model provider has that name")
// ErrProviderInUse means at least one model role still references the provider.
ErrProviderInUse = errors.New("the model provider is still in use")
// ErrNoProvider means no model provider has that id in the organisation.
ErrNoProvider = errors.New("no such model provider")
)
// ModelRole is the model an organisation chose for one role: a provider id
// and a model name on it.
type ModelRole struct {
OrgID string `db:"org_id"`
Role string `db:"role"`
Provider string `db:"provider"`
Model string `db:"model"`
OrgID string `db:"org_id"`
Role string `db:"role"`
ProviderID uuid.UUID `db:"provider_id"`
Model string `db:"model"`
}
// ResolvedRole is a role with the endpoint its provider names.
type ResolvedRole struct {
OrgID string `db:"org_id"`
Role string `db:"role"`
Provider string `db:"provider"`
Model string `db:"model"`
Class string `db:"class"`
BaseURL string `db:"base_url"`
// APIKeyCredential names the credential whose token authenticates the
// provider, or empty when it needs no key.
APIKeyCredential string `db:"api_key_credential"`
OrgID string `db:"org_id"`
Role string `db:"role"`
ProviderID uuid.UUID `db:"provider_id"`
Provider string `db:"provider"`
Model string `db:"model"`
Class string `db:"class"`
BaseURL string `db:"base_url"`
// APIKeyCredentialID references the credential whose token authenticates
// the provider, or invalid when it needs no key.
APIKeyCredentialID uuid.NullUUID `db:"api_key_credential_id"`
}
// Provider is an endpoint models are called on: a provider class, base URL and
// the credential whose token authenticates it.
// Provider is an endpoint models are called on: an immutable id, an editable
// name, provider class, base URL and optional credential id.
type Provider struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
Class string `db:"class"`
BaseURL string `db:"base_url"`
APIKeyCredential string `db:"api_key_credential"`
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
Name string `db:"name"`
Class string `db:"class"`
BaseURL string `db:"base_url"`
APIKeyCredentialID uuid.NullUUID `db:"api_key_credential_id"`
}
// Store is the governance module's Postgres store.
@@ -55,60 +67,86 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} }
func (s *Store) Providers(ctx context.Context, orgID string) ([]Provider, error) {
var out []Provider
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, class, base_url, api_key_credential
SELECT id, org_id, name, class, base_url, api_key_credential_id
FROM governance.model_providers WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("list model providers: %w", err)
}
return out, nil
}
// Provider returns the named provider; ok is false when none exists.
func (s *Store) Provider(ctx context.Context, orgID, name string) (Provider, bool, error) {
// ProviderByID returns the provider with id in orgID; ok is false when none exists.
func (s *Store) ProviderByID(ctx context.Context, orgID string, id uuid.UUID) (Provider, bool, error) {
var out Provider
err := s.db.GetContext(ctx, &out, `
SELECT org_id, name, class, base_url, api_key_credential
FROM governance.model_providers WHERE org_id = $1 AND name = $2`, orgID, name)
SELECT id, org_id, name, class, base_url, api_key_credential_id
FROM governance.model_providers WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Provider{}, false, nil
}
if err != nil {
return Provider{}, false, fmt.Errorf("read model provider %q: %w", name, err)
return Provider{}, false, fmt.Errorf("read model provider %s: %w", id, err)
}
return out, true, nil
}
// PutProvider records a provider.
func (s *Store) PutProvider(ctx context.Context, p Provider) error {
// CreateProvider inserts a new provider.
func (s *Store) CreateProvider(ctx context.Context, p Provider) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO governance.model_providers (org_id, name, class, base_url, api_key_credential)
VALUES (:org_id, :name, :class, :base_url, :api_key_credential)
ON CONFLICT (org_id, name) DO UPDATE
SET class = EXCLUDED.class, base_url = EXCLUDED.base_url,
api_key_credential = EXCLUDED.api_key_credential, updated_at = now()`, p); err != nil {
return fmt.Errorf("put model provider %q: %w", p.Name, err)
INSERT INTO governance.model_providers (id, org_id, name, class, base_url, api_key_credential_id)
VALUES (:id, :org_id, :name, :class, :base_url, :api_key_credential_id)`, p); err != nil {
if isUniqueViolation(err) {
return ErrProviderNameTaken
}
return fmt.Errorf("create model provider %q: %w", p.Name, err)
}
return nil
}
// UpdateProvider updates an existing provider's editable fields, including its name.
func (s *Store) UpdateProvider(ctx context.Context, p Provider) error {
res, err := s.db.NamedExecContext(ctx, `
UPDATE governance.model_providers
SET name = :name, class = :class, base_url = :base_url,
api_key_credential_id = :api_key_credential_id, updated_at = now()
WHERE org_id = :org_id AND id = :id`, p)
if err != nil {
if isUniqueViolation(err) {
return ErrProviderNameTaken
}
return fmt.Errorf("update model provider %s: %w", p.ID, err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("update model provider %s: %w", p.ID, err)
}
if n == 0 {
return ErrNoProvider
}
return nil
}
// DeleteProvider removes a provider and reports whether one existed.
func (s *Store) DeleteProvider(ctx context.Context, orgID, name string) (bool, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM governance.model_providers WHERE org_id = $1 AND name = $2`, orgID, name)
func (s *Store) DeleteProvider(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM governance.model_providers WHERE org_id = $1 AND id = $2`, orgID, id)
if err != nil {
return false, fmt.Errorf("delete model provider %q: %w", name, err)
if isForeignKeyViolation(err) {
return false, ErrProviderInUse
}
return false, fmt.Errorf("delete model provider %s: %w", id, err)
}
n, err := res.RowsAffected()
if err != nil {
return false, fmt.Errorf("delete model provider %q: %w", name, err)
return false, fmt.Errorf("delete model provider %s: %w", id, err)
}
return n > 0, nil
}
// AliasesUsingProvider names the roles that call models through provider.
func (s *Store) AliasesUsingProvider(ctx context.Context, orgID, provider string) ([]string, error) {
// AliasesUsingProvider names the roles that call models through providerID.
func (s *Store) AliasesUsingProvider(ctx context.Context, orgID string, providerID uuid.UUID) ([]string, error) {
var roles []string
if err := s.db.SelectContext(ctx, &roles, `
SELECT role FROM governance.model_roles WHERE org_id = $1 AND provider = $2 ORDER BY role`, orgID, provider); err != nil {
return nil, fmt.Errorf("read model roles for provider %q: %w", provider, err)
SELECT role FROM governance.model_roles WHERE org_id = $1 AND provider_id = $2 ORDER BY role`, orgID, providerID); err != nil {
return nil, fmt.Errorf("read model roles for provider %s: %w", providerID, err)
}
return roles, nil
}
@@ -118,9 +156,9 @@ func (s *Store) AliasesUsingProvider(ctx context.Context, orgID, provider string
func (s *Store) ModelRole(ctx context.Context, orgID, role string) (ResolvedRole, bool, error) {
var out ResolvedRole
err := s.db.GetContext(ctx, &out, `
SELECT r.org_id, r.role, r.provider, r.model, p.class, p.base_url, p.api_key_credential
SELECT r.org_id, r.role, r.provider_id, p.name AS provider, r.model, p.class, p.base_url, p.api_key_credential_id
FROM governance.model_roles r
JOIN governance.model_providers p ON p.org_id = r.org_id AND p.name = r.provider
JOIN governance.model_providers p ON p.id = r.provider_id
WHERE r.org_id = $1 AND r.role = $2`, orgID, role)
if errors.Is(err, sql.ErrNoRows) {
return ResolvedRole{}, false, nil
@@ -136,9 +174,9 @@ func (s *Store) ModelRole(ctx context.Context, orgID, role string) (ResolvedRole
func (s *Store) AgentModelRoles(ctx context.Context, orgID string) ([]ResolvedRole, error) {
var out []ResolvedRole
if err := s.db.SelectContext(ctx, &out, `
SELECT r.org_id, r.role, r.provider, r.model, p.class, p.base_url, p.api_key_credential
SELECT r.org_id, r.role, r.provider_id, p.name AS provider, r.model, p.class, p.base_url, p.api_key_credential_id
FROM governance.model_roles r
JOIN governance.model_providers p ON p.org_id = r.org_id AND p.name = r.provider
JOIN governance.model_providers p ON p.id = r.provider_id
WHERE r.org_id = $1 AND (r.role = 'agent' OR r.role LIKE 'agent:%')
ORDER BY r.role`, orgID); err != nil {
return nil, fmt.Errorf("list agent models: %w", err)
@@ -149,10 +187,13 @@ func (s *Store) AgentModelRoles(ctx context.Context, orgID string) ([]ResolvedRo
// PutModelRole records the organisation's model for a role.
func (s *Store) PutModelRole(ctx context.Context, m ModelRole) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO governance.model_roles (org_id, role, provider, model)
VALUES (:org_id, :role, :provider, :model)
INSERT INTO governance.model_roles (org_id, role, provider_id, model)
VALUES (:org_id, :role, :provider_id, :model)
ON CONFLICT (org_id, role) DO UPDATE
SET provider = EXCLUDED.provider, model = EXCLUDED.model, updated_at = now()`, m); err != nil {
SET provider_id = EXCLUDED.provider_id, model = EXCLUDED.model, updated_at = now()`, m); err != nil {
if isForeignKeyViolation(err) {
return ErrNoProvider
}
return fmt.Errorf("put model role %q: %w", m.Role, err)
}
return nil
+166 -37
View File
@@ -10,6 +10,7 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
@@ -22,13 +23,84 @@ var ErrModelNotAllowed = errors.New("the organisation's model policy doesn't all
// ModelProvider is an endpoint models are called on.
type ModelProvider struct {
Name string `json:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Class string `json:"class" doc:"A provider class from the model classes catalogue"`
ID uuid.UUID `json:"id"`
Name string `json:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Class string `json:"class" doc:"A provider class from the model classes catalogue"`
// BaseURL is the endpoint; empty uses the class's default.
BaseURL string `json:"base_url,omitempty"`
// APIKeyCredential names the credential whose token authenticates the
// provider. Only the name is ever returned.
APIKeyCredential string `json:"api_key_credential,omitempty"`
// APIKeyCredentialID references the credential whose token authenticates
// the provider. APIKeyCredential is its display name, read from connectors.
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid"`
APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"`
}
// modelProviderInput is a provider as the API creates or updates it.
type modelProviderInput struct {
Name string `json:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Class string `json:"class" doc:"A provider class from the model classes catalogue"`
BaseURL string `json:"base_url,omitempty" doc:"The endpoint; empty uses the class's default"`
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid" doc:"The bearer credential whose token authenticates the provider"`
}
func credentialIDPtr(id uuid.NullUUID) *uuid.UUID {
if !id.Valid {
return nil
}
v := id.UUID
return &v
}
func (m *Module) credentialName(ctx context.Context, id uuid.NullUUID) string {
if !id.Valid || m.credentials == nil {
return ""
}
name, ok, err := m.credentials.BearerCredentialName(m.orgScopeCtx(ctx), id.UUID)
if err != nil {
m.log.WarnContext(ctx, "read credential name", "credential_id", id.UUID, "error", err)
return ""
}
if !ok {
return ""
}
return name
}
func (m *Module) credentialNames(ctx context.Context) map[uuid.UUID]string {
if m.credentials == nil {
return nil
}
names, err := m.credentials.BearerCredentialNames(m.orgScopeCtx(ctx))
if err != nil {
m.log.WarnContext(ctx, "list credential names", "error", err)
return nil
}
return names
}
func (m *Module) checkCredential(ctx context.Context, id uuid.NullUUID) (string, error) {
if !id.Valid {
return "", nil
}
if m.credentials == nil {
return "", huma.NewError(http.StatusInternalServerError, "no credential store is configured")
}
name, ok, err := m.credentials.BearerCredentialName(m.orgScopeCtx(ctx), id.UUID)
if err != nil {
m.log.ErrorContext(ctx, "check credential", "credential_id", id.UUID, "error", err)
return "", huma.NewError(http.StatusInternalServerError, "couldn't check the credential")
}
if !ok {
return "", huma.NewError(http.StatusBadRequest, "no accessible bearer credential with that id")
}
return name, nil
}
func providerView(p store.Provider, credName string) ModelProvider {
return ModelProvider{
ID: p.ID, Name: p.Name, Class: p.Class, BaseURL: p.BaseURL,
APIKeyCredentialID: credentialIDPtr(p.APIKeyCredentialID),
APIKeyCredential: credName,
}
}
// ModelClass is one provider class the runtime can build.
@@ -47,22 +119,25 @@ type ModelPolicy struct {
// modelOf returns the model a request names with its provider's endpoint.
func (m *Module) modelOf(ctx context.Context, req Model) (Model, error) {
if req.Provider == "" {
return Model{}, errors.New("a provider is required")
if req.ProviderID == uuid.Nil {
return Model{}, huma.NewError(http.StatusBadRequest, "a provider is required")
}
if req.Model == "" {
return Model{}, errors.New("a model is required")
return Model{}, huma.NewError(http.StatusBadRequest, "a model is required")
}
p, ok, err := m.store.Provider(ctx, m.orgID, req.Provider)
p, ok, err := m.store.ProviderByID(ctx, m.orgID, req.ProviderID)
if err != nil {
return Model{}, err
m.log.ErrorContext(ctx, "read model provider", "provider_id", req.ProviderID, "error", err)
return Model{}, huma.NewError(http.StatusInternalServerError, "couldn't read the model provider")
}
if !ok {
return Model{}, fmt.Errorf("no provider named %q", req.Provider)
return Model{}, huma.NewError(http.StatusBadRequest, fmt.Sprintf("no provider with id %s", req.ProviderID))
}
return Model{
Provider: p.Name, Model: req.Model,
Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential,
ProviderID: p.ID, Provider: p.Name, Model: req.Model,
Class: p.Class, BaseURL: p.BaseURL,
APIKeyCredentialID: credentialIDPtr(p.APIKeyCredentialID),
APIKeyCredential: m.credentialName(ctx, p.APIKeyCredentialID),
}, nil
}
@@ -144,46 +219,93 @@ func marshalAliases(aliases []string) ([]byte, error) {
return json.Marshal(aliases)
}
func (m *Module) listModelProviders(ctx context.Context, _ *struct{}) (*httpapi.Reply[map[string]ModelProvider], error) {
func (m *Module) listModelProviders(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ModelProvider], error) {
rows, err := m.store.Providers(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list model providers", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list model providers")
}
out := make(map[string]ModelProvider, len(rows))
var credNames map[uuid.UUID]string
for _, p := range rows {
out[p.Name] = ModelProvider{Name: p.Name, Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential}
if p.APIKeyCredentialID.Valid {
credNames = m.credentialNames(ctx)
break
}
}
out := make([]ModelProvider, 0, len(rows))
for _, p := range rows {
out = append(out, providerView(p, credNames[p.APIKeyCredentialID.UUID]))
}
return httpapi.OK(out), nil
}
func (m *Module) putModelProvider(ctx context.Context, in *struct {
Name string `path:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Body ModelProvider
func (m *Module) createModelProvider(ctx context.Context, in *struct {
Body modelProviderInput
},
) (*httpapi.Reply[ModelProvider], error) {
p, err := endpoint(in.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredential)
p, err := endpoint(in.Body.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredentialID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
credName, err := m.checkCredential(ctx, p.APIKeyCredentialID)
if err != nil {
return nil, err
}
p.ID = uuid.New()
p.OrgID = m.orgID
if err := m.store.PutProvider(ctx, p); err != nil {
m.log.ErrorContext(ctx, "put model provider", "error", err)
if err := m.store.CreateProvider(ctx, p); err != nil {
if errors.Is(err, store.ErrProviderNameTaken) {
return nil, huma.NewError(http.StatusConflict, "another model provider has that name")
}
m.log.ErrorContext(ctx, "create model provider", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model provider")
}
return httpapi.OK(ModelProvider{
Name: p.Name, Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential,
}), nil
return httpapi.OK(providerView(p, credName)), nil
}
func (m *Module) putModelProvider(ctx context.Context, in *struct {
ID string `path:"id" format:"uuid"`
Body modelProviderInput
},
) (*httpapi.Reply[ModelProvider], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "a provider id is a UUID")
}
p, err := endpoint(in.Body.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredentialID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
credName, err := m.checkCredential(ctx, p.APIKeyCredentialID)
if err != nil {
return nil, err
}
p.ID = id
p.OrgID = m.orgID
switch err := m.store.UpdateProvider(ctx, p); {
case errors.Is(err, store.ErrNoProvider):
return nil, huma.NewError(http.StatusNotFound, "no such model provider")
case errors.Is(err, store.ErrProviderNameTaken):
return nil, huma.NewError(http.StatusConflict, "another model provider has that name")
case err != nil:
m.log.ErrorContext(ctx, "update model provider", "provider_id", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model provider")
}
return httpapi.OK(providerView(p, credName)), nil
}
func (m *Module) deleteModelProvider(ctx context.Context, in *struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
},
) (*struct{}, error) {
users, err := m.store.AliasesUsingProvider(ctx, m.orgID, in.Name)
id, err := uuid.Parse(in.ID)
if err != nil {
m.log.ErrorContext(ctx, "read the aliases that use a provider", "provider", in.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't check the aliases that use "+in.Name)
return nil, huma.NewError(http.StatusBadRequest, "a provider id is a UUID")
}
users, err := m.store.AliasesUsingProvider(ctx, m.orgID, id)
if err != nil {
m.log.ErrorContext(ctx, "read the aliases that use a provider", "provider_id", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't check the aliases that use this provider")
}
if len(users) > 0 {
aliases := make([]string, 0, len(users))
@@ -191,15 +313,18 @@ func (m *Module) deleteModelProvider(ctx context.Context, in *struct {
aliases = append(aliases, aliasOf(role))
}
return nil, huma.NewError(http.StatusConflict,
fmt.Sprintf("provider %s is used by aliases: %s", in.Name, strings.Join(aliases, ", ")))
fmt.Sprintf("provider is used by aliases: %s", strings.Join(aliases, ", ")))
}
found, err := m.store.DeleteProvider(ctx, m.orgID, in.Name)
found, err := m.store.DeleteProvider(ctx, m.orgID, id)
if err != nil {
m.log.ErrorContext(ctx, "delete model provider", "provider", in.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't delete "+in.Name)
if errors.Is(err, store.ErrProviderInUse) {
return nil, huma.NewError(http.StatusConflict, "provider is still used by an alias")
}
m.log.ErrorContext(ctx, "delete model provider", "provider_id", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't delete the model provider")
}
if !found {
return nil, huma.NewError(http.StatusNotFound, "no provider named "+in.Name)
return nil, huma.NewError(http.StatusNotFound, "no such model provider")
}
return nil, nil
}
@@ -265,11 +390,15 @@ func (m *Module) registerModels(api huma.API) {
Summary: "List model providers", Tags: tags,
}, m.listModelProviders)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-model-provider", Method: http.MethodPut, Path: "/api/settings/model-providers/{name}",
Summary: "Save a model provider", Tags: tags,
OperationID: "create-model-provider", Method: http.MethodPost, Path: "/api/settings/model-providers",
Summary: "Create a model provider", Tags: tags, DefaultStatus: http.StatusCreated,
}, m.createModelProvider)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-model-provider", Method: http.MethodPut, Path: "/api/settings/model-providers/{id}",
Summary: "Save a model provider, including its name; aliases refer to it by id and are unchanged", Tags: tags,
}, m.putModelProvider)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "delete-model-provider", Method: http.MethodDelete, Path: "/api/settings/model-providers/{name}",
OperationID: "delete-model-provider", Method: http.MethodDelete, Path: "/api/settings/model-providers/{id}",
Summary: "Delete a model provider no alias uses", Tags: tags, DefaultStatus: http.StatusNoContent,
}, m.deleteModelProvider)
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
+112
View File
@@ -1,10 +1,50 @@
package governance
import (
"context"
"errors"
"log/slog"
"net/http"
"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.
@@ -29,3 +69,75 @@ func TestModelPolicyAllowsEveryAliasOnlyWhenUnset(t *testing.T) {
})
}
}
// 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")
}
})
}