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

+78 -11
View File
@@ -579,6 +579,8 @@ components:
ConnectorsCredentialSaved:
additionalProperties: false
properties:
id:
type: string
kind:
type: string
name:
@@ -596,6 +598,7 @@ components:
- person
type: string
required:
- id
- name
- kind
- scope
@@ -608,6 +611,8 @@ components:
additionalProperties:
type: string
type: object
id:
type: string
kind:
type: string
name:
@@ -619,6 +624,7 @@ components:
- person
type: string
required:
- id
- name
- kind
- scope
@@ -2415,6 +2421,10 @@ components:
api_key_credential:
readOnly: true
type: string
api_key_credential_id:
format: uuid
readOnly: true
type: string
base_url:
readOnly: true
type: string
@@ -2425,10 +2435,14 @@ components:
description: The model's name on the provider
type: string
provider:
readOnly: true
type: string
provider_id:
description: The provider the model is called on
format: uuid
type: string
required:
- provider
- provider_id
- model
type: object
GovernanceModelAnswer:
@@ -2477,12 +2491,39 @@ components:
additionalProperties: false
properties:
api_key_credential:
readOnly: true
type: string
api_key_credential_id:
format: uuid
type: string
base_url:
type: string
class:
description: A provider class from the model classes catalogue
type: string
id:
type: string
name:
description: Lowercase letters, digits, dots, underscores or hyphens
type: string
required:
- id
- name
- class
type: object
GovernanceModelProviderInput:
additionalProperties: false
properties:
api_key_credential_id:
description: The bearer credential whose token authenticates the provider
format: uuid
type: string
base_url:
description: The endpoint; empty uses the class's default
type: string
class:
description: A provider class from the model classes catalogue
type: string
name:
description: Lowercase letters, digits, dots, underscores or hyphens
type: string
@@ -8878,9 +8919,11 @@ paths:
content:
application/json:
schema:
additionalProperties:
items:
$ref: "#/components/schemas/GovernanceModelProvider"
type: object
type:
- array
- "null"
description: OK
default:
content:
@@ -8891,14 +8934,39 @@ paths:
summary: List model providers
tags:
- Governance
/api/settings/model-providers/{name}:
post:
operationId: create-model-provider
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/GovernanceModelProviderInput"
required: true
responses:
"201":
content:
application/json:
schema:
$ref: "#/components/schemas/GovernanceModelProvider"
description: Created
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Create a model provider
tags:
- Governance
/api/settings/model-providers/{id}:
delete:
operationId: delete-model-provider
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"204":
@@ -8915,18 +8983,17 @@ paths:
put:
operationId: put-model-provider
parameters:
- description: Lowercase letters, digits, dots, underscores or hyphens
in: path
name: name
- in: path
name: id
required: true
schema:
description: Lowercase letters, digits, dots, underscores or hyphens
format: uuid
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/GovernanceModelProvider"
$ref: "#/components/schemas/GovernanceModelProviderInput"
required: true
responses:
"200":
@@ -8941,7 +9008,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Save a model provider
summary: Save a model provider, including its name; aliases refer to it by id and are unchanged
tags:
- Governance
/api/sources:
+22 -2
View File
@@ -160,8 +160,9 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
if err != nil {
return nil, err
}
// A model's key is a credential name resolved through the sealed store.
settings.UseCredentials(conns)
// A model's key is a credential id resolved through the sealed store in
// organisation scope with no person attached.
settings.UseCredentials(orgCredentials{conns: conns, orgID: string(governance.DefaultOrgID)})
// An account links a channel account on the connectors that can link.
settings.UseChannels(conns)
@@ -242,6 +243,25 @@ func (b *binary) close() {
_ = b.db.Close()
}
// orgCredentials confines every model-provider credential lookup to orgID with
// no person attached, so a caller's personal credentials are never reachable.
type orgCredentials struct {
conns *connectors.Module
orgID string
}
func (c orgCredentials) BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error) {
return c.conns.BearerTokenByID(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}), id)
}
func (c orgCredentials) BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error) {
return c.conns.BearerCredentialName(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}), id)
}
func (c orgCredentials) BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error) {
return c.conns.BearerCredentialNames(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}))
}
// answers wakes whatever asked for an approval: a chat turn, or else the run
// waiting on it.
type answers struct {
@@ -2,27 +2,34 @@
CREATE SCHEMA governance;
-- A model provider is an API endpoint that serves models: its provider class,
-- its base URL and the credential that holds its API key. A model alias refers
-- to a provider and one of its models, so several aliases can share a provider.
-- its base URL and the credential that holds its API key. It is identified by
-- its id, fixed when created; name is an editable label unique within the
-- organisation. api_key_credential_id references connectors.credentials (id)
-- without a cross-schema foreign key. A model alias refers to a provider by id
-- and one of its models, so several aliases can share a provider.
CREATE TABLE governance.model_providers (
org_id text NOT NULL,
name text NOT NULL CHECK (name ~ '^[a-z0-9][a-z0-9_.-]{0,62}$'),
class text NOT NULL,
base_url text NOT NULL,
api_key_credential text NOT NULL DEFAULT '',
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (org_id, name)
id uuid PRIMARY KEY,
org_id text NOT NULL,
name text NOT NULL CHECK (name ~ '^[a-z0-9][a-z0-9_.-]{0,62}$'),
class text NOT NULL,
base_url text NOT NULL,
api_key_credential_id uuid,
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (org_id, name),
UNIQUE (org_id, id)
);
-- A model role records the model an organisation uses for one job.
-- A model role records the model an organisation uses for one job. The
-- foreign key includes org_id so a role can only use its own organisation's
-- provider.
CREATE TABLE governance.model_roles (
org_id text NOT NULL,
role text NOT NULL CHECK ((role = 'agent') OR ((role <> 'agent:default') AND (role ~ '^agent:[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$'))),
model text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
provider text NOT NULL,
org_id text NOT NULL,
role text NOT NULL CHECK ((role = 'agent') OR ((role <> 'agent:default') AND (role ~ '^agent:[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$'))),
provider_id uuid NOT NULL,
model text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (org_id, role),
FOREIGN KEY (org_id, provider) REFERENCES governance.model_providers (org_id, name)
FOREIGN KEY (org_id, provider_id) REFERENCES governance.model_providers (org_id, id) ON DELETE RESTRICT
);
-- An organisation's settings are one row. When the row is missing, every
@@ -3,8 +3,10 @@ CREATE SCHEMA connectors;
-- A package is an extension the instance has accepted: its name, contract,
-- binary and digest, and the manifest that declares its settings, capabilities
-- and effects. It holds no configuration and no credentials, so it is accepted
-- once for the whole instance and configured by its installations.
-- and effects. 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. It holds no configuration and no credentials, so it is
-- accepted once for the whole instance and configured by its installations.
CREATE TABLE connectors.packages (
id uuid PRIMARY KEY,
name text NOT NULL UNIQUE,
+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")
}
})
}
+20 -6
View File
@@ -326,11 +326,13 @@ export const api = {
instructions: () => request<{ text: string }>("/api/settings/instructions"),
saveInstructions: (text: string) =>
request<{ text: string }>("/api/settings/instructions", { method: "PUT", body: { text } }),
modelProviders: () => request<Record<string, ModelProvider>>("/api/settings/model-providers"),
putModelProvider: (name: string, provider: ModelProvider) =>
request<ModelProvider>(`/api/settings/model-providers/${encodeURIComponent(name)}`, { method: "PUT", body: provider }),
deleteModelProvider: (name: string) =>
request<void>(`/api/settings/model-providers/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
modelProviders: () => request<ModelProvider[]>("/api/settings/model-providers"),
createModelProvider: (provider: ModelProviderInput) =>
request<ModelProvider>("/api/settings/model-providers", { method: "POST", body: provider }),
putModelProvider: (id: string, provider: ModelProviderInput) =>
request<ModelProvider>(`/api/settings/model-providers/${encodeURIComponent(id)}`, { method: "PUT", body: provider }),
deleteModelProvider: (id: string) =>
request<void>(`/api/settings/model-providers/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
modelClasses: () => request<ModelClass[]>("/api/settings/model-classes"),
modelPolicy: () => request<ModelPolicy>("/api/settings/model-policy"),
putModelPolicy: (policy: ModelPolicy) =>
@@ -1443,6 +1445,7 @@ export interface OrgSettings {
}
export interface Credential {
id: string;
name: string;
kind: string;
scope: ExtensionScope;
@@ -1463,22 +1466,33 @@ export interface CredentialField {
}
export interface AgentModel {
provider: string;
provider_id: string;
model: string;
/** Read from the provider, never sent when saving an alias. */
provider?: string;
class?: string;
base_url?: string;
api_key_credential_id?: string;
api_key_credential?: string;
}
/** An endpoint models are called on. */
export interface ModelProvider {
id: string;
name: string;
class: string;
base_url?: string;
api_key_credential_id?: string;
api_key_credential?: string;
}
export interface ModelProviderInput {
name: string;
class: string;
base_url?: string;
api_key_credential_id?: string;
}
export interface ModelClass {
class: string;
default_base_url?: string;
+65 -44
View File
@@ -29,11 +29,13 @@ onMounted(() => {
});
const NONE = "__none__";
const providerMap = computed(() => providers.data.value ?? {});
const providerNames = computed(() => Object.keys(providerMap.value).sort());
const providerList = computed(() => [...(providers.data.value ?? [])].sort((a, b) => a.name.localeCompare(b.name)));
const providerById = computed(() => new Map(providerList.value.map((entry) => [entry.id, entry])));
const classList = computed(() => classes.data.value ?? []);
const classNames = computed(() => classList.value.map((entry) => entry.class));
const credentialNames = computed(() => (credentials.data.value ?? []).map((entry) => entry.name));
const bearerCredentials = computed(() =>
(credentials.data.value ?? []).filter((entry) => entry.kind === "bearer" && entry.scope !== "person"),
);
const modelMap = computed(() => models.data.value ?? {});
const hasModels = computed(() => models.data.value !== undefined);
const hasProviders = computed(() => providers.data.value !== undefined);
@@ -54,12 +56,12 @@ async function run(act: () => Promise<void>): Promise<boolean> {
// Aliases: which provider and model each name resolves to.
interface AliasForm {
provider: string;
provider_id: string;
model: string;
}
const aliasEdits = ref<Record<string, AliasForm>>({});
const addedAliases = ref<string[]>([]);
const formOf = (model?: AgentModel): AliasForm => ({ provider: model?.provider ?? "", model: model?.model ?? "" });
const formOf = (model?: AgentModel): AliasForm => ({ provider_id: model?.provider_id ?? "", model: model?.model ?? "" });
watch(models.data, (rows) => {
const next: Record<string, AliasForm> = {};
for (const [alias, model] of Object.entries(rows ?? {})) next[alias] = aliasEdits.value[alias] ?? formOf(model);
@@ -85,14 +87,14 @@ async function aliasRun(alias: string, act: () => Promise<void>): Promise<void>
const saveAlias = (alias: string) =>
aliasRun(alias, async () => {
const field = aliasField(alias);
await api.putAgentModel(alias === "default" ? "" : alias, { provider: field.provider, model: field.model });
await api.putAgentModel(alias === "default" ? "" : alias, { provider_id: field.provider_id, model: field.model });
addedAliases.value = addedAliases.value.filter((name) => name !== alias);
await models.reload();
});
const testAlias = (alias: string) =>
aliasRun(alias, async () => {
const field = aliasField(alias);
const answer = await api.testAgentModel({ provider: field.provider, model: field.model });
const answer = await api.testAgentModel({ provider_id: field.provider_id, model: field.model });
tested.value = { ...tested.value, [alias]: `${answer.model} answered “${answer.answer.trim()}”` };
});
const removeAlias = (alias: string) =>
@@ -113,44 +115,60 @@ function addAlias(): void {
// Providers: the endpoints aliases call.
interface ProviderForm {
name: string;
class: string;
base_url: string;
key: string;
}
const providerEdits = ref<Record<string, ProviderForm>>({});
const providerForm = (provider?: ModelProvider): ProviderForm => ({
name: provider?.name ?? "",
class: provider?.class ?? classNames.value[0] ?? "",
base_url: provider?.base_url ?? "",
key: provider?.api_key_credential || NONE,
key: provider?.api_key_credential_id || NONE,
});
watch(providers.data, (rows) => {
for (const [name, provider] of Object.entries(rows ?? {})) providerEdits.value[name] ??= providerForm(provider);
for (const provider of rows ?? []) providerEdits.value[provider.id] ??= providerForm(provider);
});
const providerField = (name: string): ProviderForm => (providerEdits.value[name] ??= providerForm());
const providerField = (id: string): ProviderForm => (providerEdits.value[id] ??= providerForm());
function credentialLabel(id: string): string {
const key = providerField(id).key;
if (key === NONE) return "no key";
const found = bearerCredentials.value.find((entry) => entry.id === key);
if (found) return found.name;
const saved = providerById.value.get(id);
if (saved?.api_key_credential_id === key && saved.api_key_credential) return saved.api_key_credential;
return "missing credential";
}
function hasUnknownCredential(id: string): boolean {
const key = providerField(id).key;
return key !== NONE && !bearerCredentials.value.some((entry) => entry.id === key);
}
const providerBusy = ref("");
const saveProvider = async (name: string): Promise<void> => {
providerBusy.value = name;
const saveProvider = async (id: string): Promise<void> => {
providerBusy.value = id;
try {
const field = providerField(name);
const field = providerField(id);
await run(async () => {
await api.putModelProvider(name, {
name,
const saved = await api.putModelProvider(id, {
name: field.name.trim(),
class: field.class,
base_url: field.base_url.trim() || undefined,
api_key_credential: field.key === NONE ? undefined : field.key,
api_key_credential_id: field.key === NONE ? undefined : field.key,
});
await providers.reload();
providerEdits.value[id] = providerForm(saved);
await Promise.all([providers.reload(), models.reload()]);
});
} finally {
providerBusy.value = "";
}
};
const removeProvider = async (name: string): Promise<void> => {
providerBusy.value = name;
const removeProvider = async (id: string): Promise<void> => {
providerBusy.value = id;
try {
await run(async () => {
await api.deleteModelProvider(name);
delete providerEdits.value[name];
await api.deleteModelProvider(id);
delete providerEdits.value[id];
await providers.reload();
});
} finally {
@@ -171,8 +189,8 @@ function addProvider(): void {
const classId = newClass.value || classNames.value[0];
if (!name || !classId) return;
void run(async () => {
await api.putModelProvider(name, { name, class: classId });
providerEdits.value[name] = providerForm();
const created = await api.createModelProvider({ name, class: classId });
providerEdits.value[created.id] = providerForm(created);
newProvider.value = "";
await providers.reload();
});
@@ -218,16 +236,16 @@ async function savePolicy(): Promise<void> {
<div v-for="alias in aliases" :key="alias" class="border-b border-border py-2.5 last-of-type:border-b-0">
<div class="flex flex-wrap items-center gap-3">
<Label :for="`model-${alias}`" class="w-28 text-label font-medium @max-xl:w-full">{{ alias }}</Label>
<Select v-model="aliasField(alias).provider">
<Select v-model="aliasField(alias).provider_id">
<SelectTrigger class="w-44 font-mono" :aria-label="`${alias} provider`"><SelectValue placeholder="provider" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="name in providerNames" :key="name" :value="name">{{ name }}</SelectItem>
<SelectItem v-for="provider in providerList" :key="provider.id" :value="provider.id">{{ provider.name }}</SelectItem>
</SelectContent>
</Select>
<Input :id="`model-${alias}`" v-model="aliasField(alias).model" class="min-w-40 flex-1 basis-40 font-mono" placeholder="model" />
<span class="ml-auto flex items-center gap-1">
<Button variant="outline" size="sm" :disabled="!!aliasBusy || !aliasField(alias).provider || !aliasField(alias).model" @click="testAlias(alias)">Test</Button>
<Button size="sm" :disabled="!!aliasBusy || !aliasField(alias).provider || !aliasField(alias).model" @click="saveAlias(alias)">Save</Button>
<Button variant="outline" size="sm" :disabled="!!aliasBusy || !aliasField(alias).provider_id || !aliasField(alias).model" @click="testAlias(alias)">Test</Button>
<Button size="sm" :disabled="!!aliasBusy || !aliasField(alias).provider_id || !aliasField(alias).model" @click="saveAlias(alias)">Save</Button>
<Button v-if="alias !== 'default' || modelMap[alias]" variant="ghost" size="icon" :aria-label="`Remove alias ${alias}`" :disabled="!!aliasBusy" @click="removeAlias(alias)"><Trash2 /></Button>
</span>
</div>
@@ -242,41 +260,44 @@ async function savePolicy(): Promise<void> {
<Section v-if="hasProviders" title="Providers">
<Accordion type="multiple">
<AccordionItem v-for="name in providerNames" :key="name" :value="name">
<AccordionItem v-for="provider in providerList" :key="provider.id" :value="provider.id">
<AccordionTrigger class="hover:no-underline">
<span class="flex min-w-0 flex-1 flex-wrap items-center gap-x-3">
<span class="w-28 text-left font-mono text-label font-medium">{{ name }}</span>
<span class="font-mono text-caption text-fg-muted">{{ providerField(name).class }}</span>
<span class="min-w-0 truncate font-mono text-caption text-fg-subtle">{{
providerField(name).key === NONE ? "no key" : providerField(name).key
}}</span>
<span class="w-28 text-left font-mono text-label font-medium">{{ provider.name }}</span>
<span class="font-mono text-caption text-fg-muted">{{ providerField(provider.id).class }}</span>
<span class="min-w-0 truncate font-mono text-caption text-fg-subtle">{{ credentialLabel(provider.id) }}</span>
</span>
</AccordionTrigger>
<AccordionContent>
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
<Label :for="`prov-${name}-class`" class="w-28 text-label font-medium @max-xl:w-full">Class</Label>
<Select v-model="providerField(name).class">
<SelectTrigger :id="`prov-${name}-class`" class="w-48 font-mono" :aria-label="`Class for ${name}`"><SelectValue /></SelectTrigger>
<Label :for="`prov-${provider.id}-name`" class="w-28 text-label font-medium @max-xl:w-full">Name</Label>
<Input :id="`prov-${provider.id}-name`" v-model="providerField(provider.id).name" class="max-w-md font-mono" :aria-label="`Name for ${provider.name}`" />
</div>
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
<Label :for="`prov-${provider.id}-class`" class="w-28 text-label font-medium @max-xl:w-full">Class</Label>
<Select v-model="providerField(provider.id).class">
<SelectTrigger :id="`prov-${provider.id}-class`" class="w-48 font-mono" :aria-label="`Class for ${provider.name}`"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem v-for="classId in classNames" :key="classId" :value="classId">{{ classId }}</SelectItem></SelectContent>
</Select>
</div>
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
<Label :for="`prov-${name}-url`" class="w-28 text-label font-medium @max-xl:w-full">Base URL</Label>
<Input :id="`prov-${name}-url`" v-model="providerField(name).base_url" class="max-w-md font-mono" :placeholder="classList.find((entry) => entry.class === providerField(name).class)?.default_base_url || 'class default'" />
<Label :for="`prov-${provider.id}-url`" class="w-28 text-label font-medium @max-xl:w-full">Base URL</Label>
<Input :id="`prov-${provider.id}-url`" v-model="providerField(provider.id).base_url" class="max-w-md font-mono" :placeholder="classList.find((entry) => entry.class === providerField(provider.id).class)?.default_base_url || 'class default'" />
</div>
<div class="flex flex-wrap items-center gap-3 border-t-0 py-2">
<Label :for="`prov-${name}-key`" class="w-28 text-label font-medium @max-xl:w-full">API key</Label>
<Select v-model="providerField(name).key">
<SelectTrigger :id="`prov-${name}-key`" class="w-56" :aria-label="`API key for ${name}`"><SelectValue /></SelectTrigger>
<Label :for="`prov-${provider.id}-key`" class="w-28 text-label font-medium @max-xl:w-full">API key</Label>
<Select v-model="providerField(provider.id).key">
<SelectTrigger :id="`prov-${provider.id}-key`" class="w-56" :aria-label="`API key for ${provider.name}`"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="NONE">No key</SelectItem>
<SelectItem v-for="credential in credentialNames" :key="credential" :value="credential">{{ credential }}</SelectItem>
<SelectItem v-if="hasUnknownCredential(provider.id)" :value="providerField(provider.id).key" disabled>{{ credentialLabel(provider.id) }}</SelectItem>
<SelectItem v-for="credential in bearerCredentials" :key="credential.id" :value="credential.id">{{ credential.name }}</SelectItem>
</SelectContent>
</Select>
</div>
<div class="flex justify-end gap-1 pb-1">
<Button variant="ghost" size="sm" class="text-danger" :disabled="!!providerBusy" @click="removeProvider(name)"><Trash2 data-icon="inline-start" />Remove</Button>
<Button size="sm" :disabled="!!providerBusy || !providerField(name).class" @click="saveProvider(name)">Save</Button>
<Button variant="ghost" size="sm" class="text-danger" :disabled="!!providerBusy" @click="removeProvider(provider.id)"><Trash2 data-icon="inline-start" />Remove</Button>
<Button size="sm" :disabled="!!providerBusy || !providerField(provider.id).name.trim() || !providerField(provider.id).class" @click="saveProvider(provider.id)">Save</Button>
</div>
</AccordionContent>
</AccordionItem>