merge: connector packages and scoped installations (#2027)

This commit is contained in:
sam committed 2026-11-24 03:08:52 +11:00
commit bed51c4bd1
57 files changed
+3358 -1264

No files matched your search

+356 -8
View File
@@ -559,6 +559,13 @@ components:
type: object
kind:
type: string
scope:
description: "Who owns the credential. Default: instance"
enum:
- instance
- org
- person
type: string
required:
- kind
- fields
@@ -576,9 +583,16 @@ components:
type:
- array
- "null"
scope:
enum:
- instance
- org
- person
type: string
required:
- name
- kind
- scope
- restarted
type: object
ConnectorsCredentialView:
@@ -592,9 +606,16 @@ components:
type: string
name:
type: string
scope:
enum:
- instance
- org
- person
type: string
required:
- name
- kind
- scope
- fields
type: object
ConnectorsEffect:
@@ -618,6 +639,9 @@ components:
ConnectorsExtensionKind:
additionalProperties: false
properties:
contract:
description: The package contract this kind accepts
type: string
group:
enum:
- platform
@@ -633,6 +657,7 @@ components:
type: string
required:
- kind
- contract
- label
- singular
- group
@@ -648,6 +673,15 @@ components:
type:
- array
- "null"
can_override:
items:
enum:
- org
- person
type: string
type:
- array
- "null"
can_rollback:
type: boolean
capabilities:
@@ -666,6 +700,8 @@ components:
type: string
display_name:
type: string
editable:
type: boolean
effects:
$ref: "#/components/schemas/ConnectorsServerEffects"
egress:
@@ -690,14 +726,37 @@ components:
- integration
- agent
type: string
id:
type: string
managed:
type: boolean
name:
type: string
overridden:
type: boolean
overridden_by:
items:
enum:
- org
- person
type: string
type:
- array
- "null"
owner_id:
type: string
package:
type: string
path:
type: string
pending:
$ref: "#/components/schemas/ConnectorsPendingView"
scope:
enum:
- instance
- org
- person
type: string
settings:
additionalProperties:
type: string
@@ -718,7 +777,12 @@ components:
version:
type: string
required:
- id
- name
- package
- scope
- editable
- overridden
- contract
- group
- state
@@ -784,13 +848,83 @@ components:
- "null"
healthy:
type: boolean
id:
type: string
name:
type: string
scope:
enum:
- instance
- org
- person
type: string
required:
- id
- name
- scope
- contract
- healthy
type: object
ConnectorsInstallation:
additionalProperties: false
properties:
id:
type: string
scope:
enum:
- instance
- org
- person
type: string
required:
- id
- scope
type: object
ConnectorsInstallationRequest:
additionalProperties: false
properties:
args:
items:
type: string
type:
- array
- "null"
credentials:
additionalProperties:
type: string
description: Each credential slot and the credential, by name, that fills it
type: object
egress:
description: Every host the extension may reach. An installation below the instance must name them, unless the package runs unconfined
items:
type: string
type:
- array
- "null"
enabled:
type: boolean
env:
description: Host environment variables the extension may see; the instance's installations of the package bound them
items:
type: string
type:
- array
- "null"
settings:
additionalProperties:
type: string
type: object
tools:
items:
$ref: "#/components/schemas/ConnectorsToolDecl"
type:
- array
- "null"
url:
type: string
required:
- enabled
type: object
ConnectorsLifecycle:
additionalProperties: false
properties:
@@ -870,6 +1004,47 @@ components:
- name
- state
type: object
ConnectorsPackageView:
additionalProperties: false
properties:
accepted_at:
format: date-time
type: string
contract:
type: string
description:
type: string
digest:
type: string
display_name:
type: string
group:
enum:
- platform
- integration
- agent
type: string
id:
type: string
installed:
description: Whether the instance accepted the package's grants, so an organisation or a person can install it
type: boolean
managed:
type: boolean
name:
type: string
version:
type: string
required:
- id
- name
- contract
- group
- digest
- managed
- installed
- accepted_at
type: object
ConnectorsPendingView:
additionalProperties: false
properties:
@@ -1003,6 +1178,26 @@ components:
- source
- name
type: object
CreateInstallationInputBody:
additionalProperties: false
properties:
name:
description: "What a binding calls the installation. Default: the package's name"
type: string
package:
description: The accepted package to install
type: string
scope:
description: "Who owns the installation: the instance, the caller's organisation or the caller"
enum:
- instance
- org
- person
type: string
required:
- package
- scope
type: object
CreateTokenInputBody:
additionalProperties: false
properties:
@@ -2569,12 +2764,15 @@ components:
effect:
$ref: "#/components/schemas/ConnectorsEffect"
input: {}
installation:
$ref: "#/components/schemas/ConnectorsInstallation"
name:
type: string
target:
$ref: "#/components/schemas/ConnectorsTarget"
required:
- connector
- installation
- name
- input
- digest
@@ -3152,6 +3350,22 @@ components:
required:
- versions
type: object
OverrideInputBody:
additionalProperties: false
properties:
"off":
description: True switches the inherited installation off; false restores it
type: boolean
scope:
description: Switch it off for the caller's organisation or for the caller
enum:
- org
- person
type: string
required:
- scope
- "off"
type: object
PolicyInputBody:
additionalProperties: false
properties:
@@ -5494,7 +5708,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List accepted connectors
summary: List the connectors the caller can use
tags:
- Connectors
/api/connectors/{name}:
@@ -5620,7 +5834,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List credentials, never their values
summary: List the credentials the caller can see, never their values
tags:
- Credentials
/api/credentials/{name}:
@@ -5645,7 +5859,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Get a credential, never its values
summary: Get the credential a name resolves to for the caller, never its values
tags:
- Credentials
put:
@@ -5677,7 +5891,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Store a credential sealed and restart what uses it
summary: Store a credential sealed at a scope and restart what uses it
tags:
- Credentials
/api/drafts:
@@ -6035,7 +6249,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List every accepted package, whatever its contract
summary: List every installation the caller can see, whatever its contract and scope
tags:
- Extensions
/api/extensions/catalogue:
@@ -6421,7 +6635,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List accepted guards
summary: List the guards the caller can use
tags:
- Guards
/api/guards/{name}:
@@ -6481,6 +6695,117 @@ paths:
summary: Accept a package and start it
tags:
- Guards
/api/installations:
post:
operationId: create-installation
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateInstallationInputBody"
required: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/ConnectorsExtensionView"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Install an accepted package at the instance, the caller's organisation or the caller
tags:
- Installations
/api/installations/{id}:
delete:
operationId: remove-installation
parameters:
- in: path
name: id
required: true
schema:
type: string
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/ConnectorsPackageState"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Remove an installation; its package stays accepted
tags:
- Installations
put:
operationId: update-installation
parameters:
- in: path
name: id
required: true
schema:
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/ConnectorsInstallationRequest"
required: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/ConnectorsExtensionView"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Change an installation's configuration and restart it
tags:
- Installations
/api/installations/{id}/override:
put:
operationId: put-installation-override
parameters:
- in: path
name: id
required: true
schema:
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/OverrideInputBody"
required: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/ConnectorsPackageState"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Switch an inherited installation off or on for the caller's organisation or the caller
tags:
- Installations
/api/mappings:
get:
operationId: list-mappings
@@ -6647,7 +6972,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List accepted MCP servers
summary: List the MCP servers the caller can use
tags:
- MCP servers
/api/mcp-servers/{name}:
@@ -7492,6 +7817,29 @@ paths:
summary: Rename a workspace
tags:
- Organisations
/api/packages:
get:
operationId: list-packages
responses:
"200":
content:
application/json:
schema:
items:
$ref: "#/components/schemas/ConnectorsPackageView"
type:
- array
- "null"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List the packages the instance accepted
tags:
- Installations
/api/policies/change-request:
get:
operationId: get-change-request-rules
@@ -7742,7 +8090,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List accepted secret engines
summary: List the secret engines the caller can use
tags:
- Secret engines
/api/secret-engines/{name}:
+1 -1
View File
@@ -154,7 +154,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
mux := http.NewServeMux()
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256), settings)
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{
conns, err := connectors.NewModule(db, log.With("module", "connectors"), connectors.Sealing{
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
}, filepath.Join(cfg.StateDir, "extensions"))
if err != nil {
@@ -11,6 +11,10 @@ CREATE TABLE judgement.decisions (
run_id uuid NOT NULL,
key text NOT NULL,
connector text NOT NULL,
-- installation_id and installation_scope name the installation the action
-- resolved to, so an audit can say which configuration acted and whose it was.
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
action text NOT NULL,
target_kind text NOT NULL,
environment text NOT NULL,
@@ -20,6 +20,8 @@ CREATE TABLE approvals.requests (
answered_by text,
answered_via text,
connector text NOT NULL,
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
action text NOT NULL,
target_kind text NOT NULL,
target_id text NOT NULL,
@@ -69,6 +69,8 @@ CREATE TABLE chat.actions (
created_at timestamptz NOT NULL DEFAULT now(),
binding jsonb,
binding_digest text NOT NULL DEFAULT '',
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
UNIQUE (turn_id, key)
);
CREATE INDEX actions_open ON chat.actions (state) WHERE (state IN ('waiting', 'approved', 'running'));
+4 -1
View File
@@ -21,6 +21,7 @@ import (
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
@@ -238,6 +239,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
Connector: d.Action.Connector, Action: d.Action.Name,
InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope,
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action),
Summary: Summary(d), State: StatePending, Deadline: now.Add(total),
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true},
@@ -324,7 +326,8 @@ func (m *Module) askProposal(ctx context.Context, r *judgement.AutonomyProposal)
ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(),
DecisionID: r.ID, Kind: KindAutonomy, Level: r.From.String(),
Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment,
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline,
InstallationScope: connectors.ScopeInstance,
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline,
})
if err == nil {
err = m.tell.Ask(ctx, deliveries.ApprovalRequest{
+15 -10
View File
@@ -23,11 +23,16 @@ type Request struct {
Kind string `db:"kind"`
Digest string `db:"digest"`
// Copy the action details so the request can be read without loading the decision.
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
TargetID string `db:"target_id"`
Level string `db:"level"`
Connector string `db:"connector"`
// InstallationID and InstallationScope name the installation the action
// resolved to. An autonomy proposal has none and records the nil ID at the
// instance scope.
InstallationID uuid.UUID `db:"installation_id"`
InstallationScope string `db:"installation_scope"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
TargetID string `db:"target_id"`
Level string `db:"level"`
// Irreversible is whether approving needs a fresh passkey assertion.
Irreversible bool `db:"irreversible"`
Summary string `db:"summary"`
@@ -57,7 +62,7 @@ type Store struct {
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, action, target_kind,
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, installation_id, installation_scope, action, target_kind,
target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via,
step, step_deadline, change_request, counted, discarded_because`
@@ -66,12 +71,12 @@ const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, conn
func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, action,
target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, installation_id,
installation_scope, action, target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
ON CONFLICT (org_id, run_id, key) DO NOTHING
RETURNING `+requestColumns,
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.Action, r.TargetKind,
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind,
r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest)
if errors.Is(err, sql.ErrNoRows) {
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
+7 -6
View File
@@ -218,8 +218,8 @@ func (c *countingTool) Lookup(context.Context, string, jsontext.Value) (string,
// offered.
type staleBox struct{ tool *countingTool }
func (b staleBox) Declarations() []connectors.Declaration { return nil }
func (b staleBox) Tool(string) (connectors.Tool, bool) { return b.tool, true }
func (b staleBox) Declarations(context.Context) []connectors.Declaration { return nil }
func (b staleBox) Tool(context.Context, string) (connectors.Tool, bool) { return b.tool, true }
// TestOmittedToolCannotRun guards invocation: a tool the registry no longer
// declares is refused before anything runs, and names nothing new.
@@ -307,14 +307,15 @@ func TestToolNameCollisionsAreWithheld(t *testing.T) {
type collisionBox struct{}
func (collisionBox) Declarations() []connectors.Declaration {
func (collisionBox) Declarations(context.Context) []connectors.Declaration {
return []connectors.Declaration{
{Connector: "a_b", Privileged: noPrivilegedEffects, Kind: connectors.KindLookup, Name: "c"},
{Connector: "a", Privileged: noPrivilegedEffects, Kind: connectors.KindLookup, Name: "b_c"},
{Connector: "run", Privileged: noPrivilegedEffects, Kind: connectors.KindLookup, Name: "list"},
}
}
func (collisionBox) Tool(string) (connectors.Tool, bool) { return fakeTool{}, true }
func (collisionBox) Tool(context.Context, string) (connectors.Tool, bool) { return fakeTool{}, true }
// freshTurn is a turn in a conversation of its own. The taint flag is kept per
// conversation, so a turn sharing the zero session with another case would
@@ -404,14 +405,14 @@ func (f fakePeople) PrincipalFor(_ context.Context, id governance.IdentityID) (g
type fakeToolbox struct{ Toolbox }
func (fakeToolbox) Declarations() []connectors.Declaration {
func (fakeToolbox) Declarations(context.Context) []connectors.Declaration {
return []connectors.Declaration{
{Connector: "pager", Privileged: noPrivilegedEffects, Kind: connectors.KindAction, Name: "page", Description: "Page the on-call person", Schema: jsontext.Value(`{"type":"object"}`)},
{Connector: "pager", Privileged: noPrivilegedEffects, Kind: connectors.KindLookup, Name: "who", Description: "Who is on call", Schema: jsontext.Value(`{"type":"object"}`)},
}
}
func (fakeToolbox) Tool(string) (connectors.Tool, bool) { return fakeTool{}, true }
func (fakeToolbox) Tool(context.Context, string) (connectors.Tool, bool) { return fakeTool{}, true }
type fakeTool struct{ connectors.Tool }
+2 -2
View File
@@ -39,8 +39,8 @@ type Settings interface {
// Toolbox is where the agent finds the connector lookups and actions and the
// MCP server tools it may call.
type Toolbox interface {
Declarations() []connectors.Declaration
Tool(name string) (connectors.Tool, bool)
Declarations(ctx context.Context) []connectors.Declaration
Tool(ctx context.Context, name string) (connectors.Tool, bool)
}
// Judge decides whether an action runs, and runs only what it decided.
+10 -3
View File
@@ -73,6 +73,10 @@ type Action struct {
// digest. An action stored without them can't be run.
Binding jsontext.Value `db:"binding"`
BindingDigest string `db:"binding_digest"`
// InstallationID and InstallationScope name the installation the held
// action resolved to.
InstallationID uuid.UUID `db:"installation_id"`
InstallationScope string `db:"installation_scope"`
}
// Store is the chat module's Postgres store.
@@ -358,16 +362,19 @@ func (s *Store) EventsOf(ctx context.Context, sessionID uuid.UUID, kinds []strin
// one under its key, and returns the stored one either way.
func (s *Store) PutAction(ctx context.Context, orgID string, a Action) (Action, error) {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO chat.actions (id, org_id, turn_id, key, decision, request_id, path, step_due, state, binding, binding_digest)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'waiting', $9, $10)
INSERT INTO chat.actions (id, org_id, turn_id, key, decision, request_id, path, step_due, state, binding, binding_digest,
installation_id, installation_scope)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'waiting', $9, $10, $11, $12)
ON CONFLICT (turn_id, key) DO NOTHING`,
a.ID, orgID, a.TurnID, a.Key, a.Decision, a.RequestID, a.Path, a.StepDue, a.Binding, a.BindingDigest); err != nil {
a.ID, orgID, a.TurnID, a.Key, a.Decision, a.RequestID, a.Path, a.StepDue, a.Binding, a.BindingDigest,
a.InstallationID, a.InstallationScope); err != nil {
return Action{}, fmt.Errorf("record held action: %w", err)
}
return s.actionBy(ctx, `turn_id = $1 AND key = $2`, a.TurnID, a.Key)
}
const actionColumns = `id, turn_id, key, decision, request_id, path, step, step_due, state, answer, result, binding, binding_digest,
installation_id, installation_scope,
(SELECT s.owner_id FROM chat.turns t JOIN chat.sessions s ON s.id = t.session_id WHERE t.id = chat.actions.turn_id) AS owner_id`
func (s *Store) actionBy(ctx context.Context, where string, args ...any) (Action, error) {
+3 -2
View File
@@ -1,6 +1,7 @@
package chat
import (
"context"
"encoding/json/jsontext"
"errors"
"log/slog"
@@ -19,8 +20,8 @@ type effectsBox struct {
tool *countingTool
}
func (b effectsBox) Declarations() []connectors.Declaration { return b.decls }
func (b effectsBox) Tool(string) (connectors.Tool, bool) { return b.tool, true }
func (b effectsBox) Declarations(context.Context) []connectors.Declaration { return b.decls }
func (b effectsBox) Tool(context.Context, string) (connectors.Tool, bool) { return b.tool, true }
// TestChatOffersAndRunsOnlyDeclaredHarmlessTools guards the chat prohibition:
// even for the organisation owner, a tool that changes privileges, accesses
+2 -2
View File
@@ -23,8 +23,8 @@ import (
// trustBox declares tools with explicit trust levels.
type trustBox struct{ decls []connectors.Declaration }
func (b trustBox) Declarations() []connectors.Declaration { return b.decls }
func (trustBox) Tool(string) (connectors.Tool, bool) { return fakeTool{}, true }
func (b trustBox) Declarations(context.Context) []connectors.Declaration { return b.decls }
func (trustBox) Tool(context.Context, string) (connectors.Tool, bool) { return fakeTool{}, true }
// taintJudge decides at a fixed level and mirrors the real Execute's hold and
// refusal switches, recording the level it was last executed with.
+7 -6
View File
@@ -87,7 +87,7 @@ func (m *Module) tools(ctx context.Context, d Deps, t store.Turn) core.ToolSet {
// tool name. Offering one of them would make the model's call ambiguous, so
// the name is withheld from both.
ambiguous := map[string]bool{}
for _, decl := range d.Toolbox.Declarations() {
for _, decl := range d.Toolbox.Declarations(ctx) {
if decl.Privileged.ProhibitedInChat() {
continue
}
@@ -155,9 +155,9 @@ var errToolProhibited = errors.New("chat can't run that tool: it changes privile
// call was offered for. A connector that stopped, or was replaced by one
// declaring fewer tools, leaves the old call refused. The effects are read
// from the running declaration, not the one the call was offered with.
func declared(d Deps, decl connectors.Declaration) (connectors.Declaration, bool) {
for _, current := range d.Toolbox.Declarations() {
if current.Connector == decl.Connector && current.Name == decl.Name && current.Kind == decl.Kind {
func declared(ctx context.Context, d Deps, decl connectors.Declaration) (connectors.Declaration, bool) {
for _, current := range d.Toolbox.Declarations(ctx) {
if current.Connector == decl.Connector && current.Installation == decl.Installation && current.Name == decl.Name && current.Kind == decl.Kind {
return current, true
}
}
@@ -175,14 +175,14 @@ func (m *Module) call(ctx context.Context, d Deps, t store.Turn, decl connectors
if err := m.allowed(ctx, d, need, governance.KindConnector, decl.Connector); err != nil {
return "", err
}
current, ok := declared(d, decl)
current, ok := declared(ctx, d, decl)
if !ok {
return "", errToolUnavailable
}
if current.Privileged.ProhibitedInChat() {
return "", errToolProhibited
}
tool, ok := d.Toolbox.Tool(decl.Connector)
tool, ok := d.Toolbox.Tool(ctx, decl.Ref())
if !ok {
return "", errToolUnavailable
}
@@ -320,6 +320,7 @@ func (m *Module) hold(ctx context.Context, d Deps, t store.Turn, decision judgem
if _, err := m.store.PutAction(ctx, m.orgID, store.Action{
ID: actionID, TurnID: t.ID, Key: key, Decision: rawDecision, RequestID: request.ID,
Path: rawPath, StepDue: request.StepDeadline, Binding: rawBinding, BindingDigest: digest,
InstallationID: decision.Action.Installation.ID, InstallationScope: decision.Action.Installation.Scope,
}); err != nil {
return "", err
}
+195
View File
@@ -0,0 +1,195 @@
package connectors
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"net/http"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// extensionKinds lists the API path and names for each kind of accepted
// package. The group comes from the contract's entry in store.Contracts.
func extensionKinds() []extensionKind {
return []extensionKind{
{store.ContractConnector, "/api/connectors", "connector", "connector", "connectors", "Connectors"},
{store.ContractSecretEngine, "/api/secret-engines", "secret-engine", "secret engine", "secret engines", "Secret engines"},
{store.ContractGuard, "/api/guards", "guard", "guard", "guards", "Guards"},
{store.ContractMCP, "/api/mcp-servers", "mcp-server", "MCP server", "MCP servers", "MCP servers"},
}
}
type extensionKind struct {
contract, path, noun, singular, plural, tag string
}
// ExtensionKind is one kind of accepted package and the group it belongs to.
type ExtensionKind struct {
Kind string `json:"kind" doc:"The API path segment that lists this kind"`
Contract string `json:"contract" doc:"The package contract this kind accepts"`
Label string `json:"label"`
Singular string `json:"singular"`
Group string `json:"group" enum:"platform,integration,agent"`
}
func listExtensionKinds(context.Context, *struct{}) (*httpapi.Reply[[]ExtensionKind], error) {
kinds := extensionKinds()
out := make([]ExtensionKind, 0, len(kinds))
for _, k := range kinds {
out = append(out, ExtensionKind{
Kind: strings.TrimPrefix(k.path, "/api/"), Contract: k.contract, Label: k.tag, Singular: k.singular,
Group: string(store.GroupOf(k.contract)),
})
}
return httpapi.OK(out), nil
}
// Register adds the API for packages, installations and credentials. Accepting
// or removing a package is for an instance administrator; installations and
// credentials are checked against the scope that owns them in each handler.
func (m *Module) Register(api huma.API) {
read := httpapi.Authorized(governance.ActionRead, governance.KindConnector)
httpapi.Register(api, read, huma.Operation{
OperationID: "list-extension-kinds", Method: http.MethodGet, Path: "/api/extension-kinds",
Summary: "List the kinds of extension and the group each belongs to", Tags: []string{"Connectors"},
}, listExtensionKinds)
for _, k := range extensionKinds() {
tags := []string{k.tag}
httpapi.Register(api, read, huma.Operation{
OperationID: "list-" + k.noun + "s", Method: http.MethodGet, Path: k.path,
Summary: "List the " + k.plural + " the caller can use", Tags: tags,
}, m.list(k.contract))
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{
OperationID: "remove-" + k.noun, Method: http.MethodDelete, Path: k.path + "/{name}",
Summary: "Remove an accepted package", Tags: tags,
}, m.remove(k.contract))
if k.contract == store.ContractMCP {
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindMCPServer), huma.Operation{
OperationID: "accept-mcp-server", Method: http.MethodPut, Path: k.path + "/{name}",
Summary: "Accept an MCP server and the tools it may offer", Tags: tags,
}, m.acceptServer)
continue
}
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindConnector), huma.Operation{
OperationID: "accept-" + k.noun, Method: http.MethodPut, Path: k.path + "/{name}",
Summary: "Accept a package and start it", Tags: tags,
}, m.accept(k.contract))
}
m.registerInstallations(api)
tags := []string{"Credentials"}
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindSecret), huma.Operation{
OperationID: "list-credentials", Method: http.MethodGet, Path: "/api/credentials",
Summary: "List the credentials the caller can see, never their values", Tags: tags,
}, m.listCredentials)
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindSecret), huma.Operation{
OperationID: "get-credential", Method: http.MethodGet, Path: "/api/credentials/{name}",
Summary: "Get the credential a name resolves to for the caller, never its values", Tags: tags,
}, m.getCredential)
httpapi.Register(api, httpapi.Authorized(governance.ActionUpdate, governance.KindSecret), huma.Operation{
OperationID: "put-credential", Method: http.MethodPut, Path: "/api/credentials/{name}",
Summary: "Store a credential sealed at a scope and restart what uses it", Tags: tags,
}, m.putCredential)
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindSecret), huma.Operation{
OperationID: "list-credential-kinds", Method: http.MethodGet, Path: "/api/credential-kinds",
Summary: "List credential kinds and the fields each takes", Tags: tags,
}, listCredentialKinds)
m.registerCatalogue(api)
m.registerExtensions(api)
}
type acceptRequest struct {
Path string `json:"path" doc:"The extension binary on the host"`
SHA256 string `json:"sha256" doc:"The binary's digest; it runs only while the digest matches"`
Egress []string `json:"egress,omitzero" doc:"Every host the extension may reach"`
Env []string `json:"env,omitzero" doc:"Host environment variables the extension may see"`
Settings map[string]string `json:"settings,omitzero"`
// Credentials maps each credential slot the package declares to a
// credential by name.
Credentials map[string]string `json:"credentials,omitzero"`
}
func (m *Module) accept(contract string) func(context.Context, *packageInput) (*httpapi.Reply[packageState], error) {
return func(ctx context.Context, in *packageInput) (*httpapi.Reply[packageState], error) {
return m.acceptAs(ctx, in, contract)
}
}
type packageInput struct {
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
Body acceptRequest
}
type nameInput struct {
Name string `path:"name"`
}
// packageState is an accepted package's name and state after a change.
type packageState struct {
Name string `json:"name"`
State string `json:"state" enum:"running,removed"`
}
// acceptAs accepts a package by path for the instance and creates the
// instance installation of the same name, so the extension runs for every
// organisation.
func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string) (*httpapi.Reply[packageState], error) {
name, req := in.Name, in.Body
if !validName.MatchString(name) || req.Path == "" || req.SHA256 == "" {
return nil, huma.NewError(http.StatusBadRequest, "a connector needs a lowercase name, a path and a sha256")
}
settings, err := json.Marshal(req.Settings)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
slots, err := json.Marshal(req.Credentials, json.FormatNilMapAsNull(false))
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
a := store.Installed{
ID: uuid.New(), Scope: store.ScopeInstance, Name: name, PackageName: name, Contract: contract,
Path: req.Path, SHA256: req.SHA256,
Egress: req.Egress, Env: req.Env, Settings: settings, Credentials: slots,
// Only an MCP server declares its tools at acceptance; the column
// holds a list either way.
Tools: jsontext.Value(`[]`), Enabled: true,
}
previous, found, err := m.instanceRow(ctx, name)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
if found {
if len(previous.Manifest) > 0 {
return nil, huma.NewError(http.StatusConflict, name+" is installed from the catalogue; change it through its extension page")
}
a.ID, a.PackageID = previous.ID, previous.PackageID
}
if err := m.commit(context.WithoutCancel(ctx), a, found, previous, m.persistInstance(ctx)); err != nil {
return nil, acceptError(err)
}
if found && (previous.Path != a.Path || previous.SHA256 != a.SHA256) {
m.relaunchPackage(context.WithoutCancel(ctx), a)
}
return httpapi.OK(packageState{Name: name, State: "running"}), nil
}
// acceptError maps an error returned by commit to an HTTP error.
func acceptError(err error) error {
if errors.As(err, new(persistError)) {
return huma.NewError(http.StatusInternalServerError, err.Error())
}
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
// errNoPackage is the refusal to install a package the instance hasn't accepted.
func errNoPackage(name string) error {
return huma.NewError(http.StatusNotFound, fmt.Sprintf("the instance hasn't accepted a package named %s", name))
}
+10 -5
View File
@@ -138,14 +138,19 @@ func capabilitiesOf(desc *pb.DescribeResponse) Capabilities {
return caps
}
// Capabilities returns what the named connector declared when it last loaded.
// ok is false when the connector isn't accepted or has never loaded.
// Capabilities returns what the named connector declared when it last loaded,
// for the installation the name resolves to for the scope ctx acts for, running
// or not. ok is false when no such installation exists or it has never loaded.
func (m *Module) Capabilities(ctx context.Context, connector string) (caps Capabilities, ok bool, err error) {
raw, ok, err := m.store.Capabilities(ctx, m.orgID, connector)
if err != nil || !ok {
installed, err := m.store.List(ctx)
if err != nil {
return Capabilities{}, false, err
}
if err := json.Unmarshal(raw, &caps); err != nil {
a, ok := pickInstalled(installed, ScopeFromContext(ctx), connector)
if !ok || len(a.Capabilities) == 0 {
return Capabilities{}, false, nil
}
if err := json.Unmarshal(a.Capabilities, &caps); err != nil {
return Capabilities{}, false, fmt.Errorf("connector %q: stored capabilities: %w", connector, err)
}
return caps, true, nil
+10 -10
View File
@@ -21,9 +21,9 @@ var errNoSource = errors.New("no catalogue source is set")
// sourceStore is where the catalogue source and its freshness mark are kept.
type sourceStore interface {
CatalogueSource(ctx context.Context, orgID string) (store.Source, bool, error)
CatalogueSource(ctx context.Context) (store.Source, bool, error)
PutCatalogueSource(ctx context.Context, src store.Source) error
AdvanceCatalogue(ctx context.Context, orgID string, issuedAt time.Time) (bool, error)
AdvanceCatalogue(ctx context.Context, issuedAt time.Time) (bool, error)
}
// catalogueContracts are the contracts a catalogue entry may serve. An MCP
@@ -45,7 +45,7 @@ type SourceView struct {
}
func (m *Module) getCatalogueSource(ctx context.Context, _ *struct{}) (*httpapi.Reply[SourceView], error) {
src, ok, err := m.sources.CatalogueSource(ctx, m.orgID)
src, ok, err := m.sources.CatalogueSource(ctx)
if err != nil {
m.log.ErrorContext(ctx, "read the catalogue source", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the catalogue source")
@@ -68,7 +68,7 @@ func (m *Module) putCatalogueSource(ctx context.Context, in *struct{ Body Catalo
if _, err := catalogue.ParseKey(req.PublicKey); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if err := m.sources.PutCatalogueSource(ctx, store.Source{OrgID: m.orgID, Location: req.Location, PublicKey: req.PublicKey}); err != nil {
if err := m.sources.PutCatalogueSource(ctx, store.Source{Location: req.Location, PublicKey: req.PublicKey}); err != nil {
m.log.ErrorContext(ctx, "save the catalogue source", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the catalogue source")
}
@@ -80,7 +80,7 @@ func (m *Module) putCatalogueSource(ctx context.Context, in *struct{ Body Catalo
// signature, then freshness, so an older catalogue is refused only once it is
// known to be genuine.
func (m *Module) readCatalogue(ctx context.Context) (catalogue.Document, string, error) {
src, ok, err := m.sources.CatalogueSource(ctx, m.orgID)
src, ok, err := m.sources.CatalogueSource(ctx)
if err != nil {
return catalogue.Document{}, "", err
}
@@ -99,7 +99,7 @@ func (m *Module) readCatalogue(ctx context.Context) (catalogue.Document, string,
if err != nil {
return catalogue.Document{}, "", err
}
if fresh, err := m.sources.AdvanceCatalogue(ctx, m.orgID, doc.IssuedAt); err != nil {
if fresh, err := m.sources.AdvanceCatalogue(ctx, doc.IssuedAt); err != nil {
return catalogue.Document{}, "", err
} else if !fresh {
return catalogue.Document{}, "", catalogue.ErrStale
@@ -130,10 +130,10 @@ func (m *Module) listCatalogue(ctx context.Context, _ *struct{}) (*httpapi.Reply
if err != nil {
return nil, catalogueError(err)
}
accepted, err := m.store.List(ctx, m.orgID)
accepted, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list accepted packages", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
m.log.ErrorContext(ctx, "list installations", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
out := make([]CatalogueEntry, 0, len(doc.Extensions))
for _, e := range doc.Extensions {
@@ -141,7 +141,7 @@ func (m *Module) listCatalogue(ctx context.Context, _ *struct{}) (*httpapi.Reply
Name: e.Name, DisplayName: e.DisplayName, Description: e.Description, Contract: e.Contract,
Group: string(store.GroupOf(e.Contract)), Version: e.Version, Digest: e.Digest, Grants: e.Grants,
}
if i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == e.Name }); i >= 0 {
if i := slices.IndexFunc(accepted, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == e.Name }); i >= 0 {
entry.Installed = true
if rec, ok, err := packageOf(accepted[i]); err == nil && ok {
entry.InstalledVersion = rec.State.Current.Version
+35 -14
View File
@@ -13,6 +13,7 @@ import (
"time"
"github.com/google/jsonschema-go/jsonschema"
"github.com/google/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -124,12 +125,16 @@ type lookup struct {
// Declaration is one lookup or action a connector declared, as an agent is
// offered it.
type Declaration struct {
Connector string `json:"connector"`
Kind string `json:"kind"`
Name string `json:"name"`
Description string `json:"description"`
Schema jsontext.Value `json:"schema"`
ReadOnly bool `json:"read_only"`
Connector string `json:"connector"`
// Installation is the installation that declared it. Calling the tool by
// Ref reaches that installation, whatever the caller's scope resolves the
// connector's name to later.
Installation uuid.UUID `json:"installation,omitzero"`
Kind string `json:"kind"`
Name string `json:"name"`
Description string `json:"description"`
Schema jsontext.Value `json:"schema"`
ReadOnly bool `json:"read_only"`
// Privileged states whether the tool changes privileges or accesses
// secrets. Chat is offered only a tool that declared it does neither.
Privileged PrivilegedEffects `json:"privileged"`
@@ -138,6 +143,15 @@ type Declaration struct {
TrustLevel string `json:"trust_level,omitempty"`
}
// Ref is what names the installation that declared the tool: its ID, or the
// connector's name when the declaration carries none.
func (d Declaration) Ref() string {
if d.Installation != uuid.Nil {
return d.Installation.String()
}
return d.Connector
}
// Trust levels a declaration can carry.
const (
TrustTrusted = "trusted"
@@ -162,16 +176,20 @@ type Tool interface {
// Resolve works out one concrete action's target and effect, for
// judgement before it runs.
Resolve(ctx context.Context, name string, input jsontext.Value) (Resolution, error)
// Installation is the installation the tool runs as, which a decision
// records.
Installation() Installation
}
// Connector is a running connector and what it declared.
type Connector struct {
name string
version string
client pb.ConnectorServiceClient
eventTypes map[string]*jsonschema.Resolved
actions map[string]action
lookups map[string]lookup
name string
installation Installation
version string
client pb.ConnectorServiceClient
eventTypes map[string]*jsonschema.Resolved
actions map[string]action
lookups map[string]lookup
// deliveries are the messages and records it sends, never offered to an
// agent.
deliveries map[string]*jsonschema.Resolved
@@ -377,14 +395,14 @@ func (c *Connector) Declarations() []Declaration {
for _, name := range slices.Sorted(maps.Keys(c.lookups)) {
l := c.lookups[name]
out = append(out, Declaration{
Connector: c.name, Kind: KindLookup, Name: name, Description: l.description, Schema: l.schema, ReadOnly: true,
Connector: c.name, Installation: c.installation.ID, Kind: KindLookup, Name: name, Description: l.description, Schema: l.schema, ReadOnly: true,
Privileged: l.privileged,
})
}
for _, name := range slices.Sorted(maps.Keys(c.actions)) {
a := c.actions[name]
out = append(out, Declaration{
Connector: c.name, Kind: KindAction, Name: name, Description: a.description, Schema: a.schema, ReadOnly: a.effect.ReadOnly,
Connector: c.name, Installation: c.installation.ID, Kind: KindAction, Name: name, Description: a.description, Schema: a.schema, ReadOnly: a.effect.ReadOnly,
Privileged: a.effect.Privileged,
})
}
@@ -397,6 +415,9 @@ func (c *Connector) Capabilities() Capabilities { return c.caps }
// Name is the connector's accepted name.
func (c *Connector) Name() string { return c.name }
// Installation is the installation the connector runs as.
func (c *Connector) Installation() Installation { return c.installation }
// Version is the connector's own release, as it described itself.
func (c *Connector) Version() string { return c.version }
+9 -3
View File
@@ -6,6 +6,7 @@
package connectors
import (
"cmp"
"context"
"fmt"
"log/slog"
@@ -26,6 +27,9 @@ const contractVersion = "v1"
// Spec is one accepted connector to run.
type Spec struct {
Name string
// Key identifies the running process; it is the installation ID. It
// defaults to Name.
Key string
// Path is the connector binary; SHA256 is the digest it must match.
Path string
SHA256 string
@@ -53,24 +57,26 @@ func NewHost(log *slog.Logger) *Host {
// already running under the same name is replaced.
func (h *Host) Start(ctx context.Context, spec Spec) (*Connector, error) {
raw, err := h.procs.Start(ctx, host.Spec{
Name: spec.Name, Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
Name: spec.Name, Key: spec.key(), Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
}, surface, &plugin{})
if err != nil {
return nil, err
}
client, ok := raw.(pb.ConnectorServiceClient)
if !ok {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("connector %q: plugin is not a connector", spec.Name)
}
c, err := open(ctx, spec.Name, client, spec.Settings, spec.Secrets)
if err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, err
}
return c, nil
}
func (s Spec) key() string { return cmp.Or(s.Key, s.Name) }
// Stop ends the named connector.
func (h *Host) Stop(name string) { h.procs.Stop(name) }
+85 -30
View File
@@ -1,6 +1,7 @@
package connectors
import (
"cmp"
"context"
json "encoding/json/v2"
"errors"
@@ -63,6 +64,9 @@ func listCredentialKinds(context.Context, *struct{}) (*httpapi.Reply[[]credentia
type credentialRequest struct {
Kind string `json:"kind"`
Fields map[string]Field `json:"fields"`
// Scope is who owns the credential. A credential resolves like an
// installation: the person's, then the organisation's, then the instance's.
Scope string `json:"scope,omitzero" enum:"instance,org,person" doc:"Who owns the credential. Default: instance"`
}
type credentialInput struct {
@@ -75,6 +79,7 @@ type credentialInput struct {
type credentialSaved struct {
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
Restarted []string `json:"restarted"`
}
@@ -82,6 +87,7 @@ type credentialSaved struct {
type credentialView struct {
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
Fields map[string]string `json:"fields"`
}
@@ -95,34 +101,50 @@ func (m *Module) putCredential(ctx context.Context, in *credentialInput) (*httpa
if err := checkCredential(req); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
owner, err := auth.ownerAt(cmp.Or(req.Scope, store.ScopeInstance))
if err != nil {
return nil, err
}
plain, err := json.Marshal(req.Fields)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
sealed, err := m.sealer.Seal(m.credentialLabel(name, req.Kind), plain)
sealed, err := m.sealer.Seal(credentialLabel(owner, name, req.Kind), plain)
if err != nil {
m.log.ErrorContext(ctx, "seal credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't seal the credential")
}
if err := m.store.PutCredential(ctx, store.Credential{OrgID: m.orgID, Name: name, Kind: req.Kind, Sealed: sealed}); err != nil {
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 {
m.log.ErrorContext(ctx, "put credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the credential")
}
restarted, err := m.relaunchUsers(context.WithoutCancel(ctx), name)
restarted, err := m.relaunchUsers(context.WithoutCancel(ctx), owner, name)
if err != nil {
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
return httpapi.OK(credentialSaved{Name: name, Kind: req.Kind, Restarted: restarted}), nil
return httpapi.OK(credentialSaved{Name: name, Kind: req.Kind, Scope: owner.Scope, Restarted: restarted}), nil
}
func (m *Module) listCredentials(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]credentialView], error) {
creds, err := m.store.Credentials(ctx, m.orgID)
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
creds, err := m.store.Credentials(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list credentials", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list credentials")
}
views := make([]credentialView, 0, len(creds))
for _, c := range creds {
if !auth.sees(c.Owner()) {
continue
}
view, err := m.credentialViewOf(c)
if err != nil {
m.log.ErrorContext(ctx, "open credential", "credential", c.Name, "error", err)
@@ -135,7 +157,7 @@ func (m *Module) listCredentials(ctx context.Context, _ *struct{}) (*httpapi.Rep
func (m *Module) getCredential(ctx context.Context, in *nameInput) (*httpapi.Reply[credentialView], error) {
name := in.Name
c, ok, err := m.store.Credential(ctx, m.orgID, name)
c, ok, err := m.credentialFor(ctx, ScopeFromContext(ctx), name)
if err != nil {
m.log.ErrorContext(ctx, "read credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the credential")
@@ -158,7 +180,7 @@ func (m *Module) credentialViewOf(c store.Credential) (credentialView, error) {
if err != nil {
return credentialView{}, err
}
view := credentialView{Name: c.Name, Kind: c.Kind, Fields: map[string]string{}}
view := credentialView{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 != "" {
@@ -168,11 +190,34 @@ func (m *Module) credentialViewOf(c store.Credential) (credentialView, error) {
return view, nil
}
// credentialFor finds the credential name resolves to for s: the person's, then
// the organisation's, then the instance's. A credential owned by another
// person or organisation is never returned.
func (m *Module) credentialFor(ctx context.Context, s Scope, name string) (store.Credential, bool, error) {
creds, err := m.store.Credentials(ctx)
if err != nil {
return store.Credential{}, false, err
}
return pickCredential(creds, s, name)
}
func pickCredential(creds []store.Credential, s Scope, name string) (store.Credential, bool, error) {
for _, o := range s.owners() {
for _, c := range creds {
if c.Name == name && c.Owner() == o {
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. It is how a setting references a credential by
// name without the dashboard ever reading the value.
// 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
// ever reading the value.
func (m *Module) BearerToken(ctx context.Context, name string) (string, error) {
c, ok, err := m.store.Credential(ctx, m.orgID, name)
c, ok, err := m.credentialFor(ctx, ScopeFromContext(ctx), name)
if err != nil {
return "", err
}
@@ -187,7 +232,7 @@ func (m *Module) BearerToken(ctx context.Context, name string) (string, error) {
if !ok {
return "", fmt.Errorf("credential %q has no token field", name)
}
return m.resolveField(ctx, store.Accepted{}, f)
return m.resolveField(ctx, "", c.Owner(), f)
}
func checkCredential(req credentialRequest) error {
@@ -234,12 +279,14 @@ func checkPrivateKey(key, passphrase Field) error {
return nil
}
func (m *Module) credentialLabel(name, kind string) string {
return m.orgID + "/" + name + "/" + kind
// credentialLabel binds a sealed credential to its owner, so a row moved to
// another scope no longer opens.
func credentialLabel(o store.Owner, name, kind string) string {
return o.Scope + ":" + o.OrgID + o.PersonID + "/" + name + "/" + kind
}
func (m *Module) openCredential(c store.Credential) (map[string]Field, error) {
plain, err := m.sealer.Open(m.credentialLabel(c.Name, c.Kind), c.Sealed)
plain, err := m.sealer.Open(credentialLabel(c.Owner(), c.Name, c.Kind), c.Sealed)
if err != nil {
return nil, err
}
@@ -250,17 +297,20 @@ func (m *Module) openCredential(c store.Credential) (map[string]Field, error) {
return fields, nil
}
// secrets resolves an extension's credential slots into the secrets it is
// configured with, keyed "slot.field". A secret engine's own credentials must
// hold their values: an engine never waits on another engine.
func (m *Module) secrets(ctx context.Context, a store.Accepted) (map[string]string, error) {
// secrets resolves an installation's credential slots into the secrets it is
// configured with, keyed "slot.field". Each credential resolves for the
// installation's owner: a person's installation reaches the person's
// credentials and the instance's, an organisation's reaches its own and the
// instance's. A secret engine's own credentials must hold their values: an
// engine never waits on another engine.
func (m *Module) secrets(ctx context.Context, a store.Installed) (map[string]string, error) {
slots, err := decodeSlots(a.Credentials)
if err != nil {
return nil, err
}
out := map[string]string{}
for slot, credName := range slots {
c, ok, err := m.store.Credential(ctx, m.orgID, credName)
c, ok, err := m.credentialFor(ctx, scopeOf(a.Owner()), credName)
if err != nil {
return nil, err
}
@@ -272,7 +322,7 @@ func (m *Module) secrets(ctx context.Context, a store.Accepted) (map[string]stri
return nil, err
}
for field, f := range fields {
v, err := m.resolveField(ctx, a, f)
v, err := m.resolveField(ctx, a.Contract, a.Owner(), f)
if err != nil {
return nil, fmt.Errorf("credential %q field %s: %w", credName, field, err)
}
@@ -282,16 +332,14 @@ func (m *Module) secrets(ctx context.Context, a store.Accepted) (map[string]stri
return out, nil
}
func (m *Module) resolveField(ctx context.Context, a store.Accepted, f Field) (string, error) {
func (m *Module) resolveField(ctx context.Context, contract string, owner store.Owner, f Field) (string, error) {
if f.Engine == "" {
return f.Value, nil
}
if a.Contract == store.ContractSecretEngine {
if contract == store.ContractSecretEngine {
return "", errors.New("a secret engine's own credentials must hold their values")
}
m.mu.RLock()
engine, ok := m.engines[f.Engine]
m.mu.RUnlock()
engine, ok := m.engineAt(owner, f.Engine)
if !ok {
return "", fmt.Errorf("secret engine %q isn't running", f.Engine)
}
@@ -309,10 +357,17 @@ func decodeSlots(raw []byte) (map[string]string, error) {
return slots, nil
}
// relaunchUsers restarts every accepted extension with a slot naming the
// credential, and returns their names.
func (m *Module) relaunchUsers(ctx context.Context, credential string) ([]string, error) {
accepted, err := m.store.List(ctx, m.orgID)
// uses reports whether an installation owned by installOwner may resolve a
// credential owned by credOwner: the instance's credentials reach every
// installation, an organisation's or a person's only their own.
func uses(installOwner, credOwner store.Owner) bool {
return credOwner.Scope == store.ScopeInstance || installOwner == credOwner
}
// relaunchUsers restarts every enabled installation that may resolve the
// credential and has a slot naming it, and returns their names.
func (m *Module) relaunchUsers(ctx context.Context, owner store.Owner, credential string) ([]string, error) {
accepted, err := m.store.List(ctx)
if err != nil {
return nil, err
}
@@ -320,7 +375,7 @@ func (m *Module) relaunchUsers(ctx context.Context, credential string) ([]string
var errs []error
for _, a := range ordered(accepted) {
slots, err := decodeSlots(a.Credentials)
if err != nil || !slices.Contains(slices.Collect(maps.Values(slots)), credential) {
if err != nil || !uses(a.Owner(), owner) || !slices.Contains(slices.Collect(maps.Values(slots)), credential) {
continue
}
if err := m.launch(ctx, a); err != nil {
+6 -5
View File
@@ -11,6 +11,7 @@ import (
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// TestCredentialRoutesNeverReturnASecret guards the credential boundary: a
@@ -29,15 +30,14 @@ func TestCredentialRoutesNeverReturnASecret(t *testing.T) {
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal("default/ops/bearer", plain)
sealed, err := sealer.Seal("instance:/ops/bearer", plain)
if err != nil {
t.Fatal(err)
}
module := &Module{
orgID: "default",
log: slog.New(slog.DiscardHandler),
log: slog.New(slog.DiscardHandler),
store: &fakeRegistry{creds: []store.Credential{
{OrgID: "default", Name: "ops", Kind: "bearer", Sealed: sealed},
{Scope: store.ScopeInstance, Name: "ops", Kind: "bearer", Sealed: sealed},
}},
sealer: sealer,
}
@@ -50,7 +50,8 @@ func TestCredentialRoutesNeverReturnASecret(t *testing.T) {
{name: "read", call: func(ctx context.Context) (any, error) { return module.getCredential(ctx, &nameInput{Name: "ops"}) }},
} {
t.Run(tt.name, func(t *testing.T) {
reply, err := tt.call(t.Context())
ctx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: "admin", Kind: governance.KindUser, Org: governance.DefaultOrgID})
reply, err := tt.call(ctx)
if err != nil {
t.Fatalf("read: %v", err)
}
+5 -5
View File
@@ -58,18 +58,18 @@ func (e *Engine) Resolve(ctx context.Context, key string) (string, error) {
// and its own secrets.
func (h *Host) StartEngine(ctx context.Context, spec Spec) (*Engine, error) {
raw, err := h.procs.Start(ctx, host.Spec{
Name: spec.Name, Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
Name: spec.Name, Key: spec.key(), Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
}, engineSurface, &enginePlugin{})
if err != nil {
return nil, err
}
client, ok := raw.(sepb.SecretEngineServiceClient)
if !ok {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("secret engine %q: plugin is not a secret engine", spec.Name)
}
if _, err := client.Configure(ctx, &sepb.ConfigureRequest{Settings: spec.Settings, Secrets: spec.Secrets}); err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("secret engine %q: configure: %w", spec.Name, err)
}
e := &Engine{name: spec.Name, client: client}
@@ -79,12 +79,12 @@ func (h *Host) StartEngine(ctx context.Context, spec Spec) (*Engine, error) {
return e, nil
}
if err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("secret engine %q: describe: %w", spec.Name, err)
}
e.version, e.settings = desc.GetVersion(), engineSettings(desc.GetSettings())
if err := validateSettingsSchema(e.settings); err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("secret engine %q: %w", spec.Name, err)
}
return e, nil
+14 -27
View File
@@ -13,44 +13,31 @@ import (
"github.com/samcharles93/archie-core/modules/governance"
)
// listExtensions returns every accepted package, whatever its contract: the
// extensions page shows one list rather than one per kind.
// listExtensions returns every installation the caller can see, whatever its
// contract and scope: the extensions page shows one list rather than one per
// kind.
func (m *Module) listExtensions(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ExtensionView], error) {
accepted, err := m.store.List(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list accepted packages", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
}
views := make([]ExtensionView, 0, len(accepted))
for _, a := range accepted {
view, err := m.viewOf(a)
if err != nil {
m.log.ErrorContext(ctx, "read accepted package", "package", a.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read "+a.Name)
}
views = append(views, view)
}
return httpapi.OK(views), nil
return m.listViews(ctx, func(store.Installed) bool { return true })
}
// removeExtension removes an accepted package without naming its contract
// first. The contract is read from the row and handed to the same removal the
// per-kind routes use.
// first. The contract is read from the package's instance installation and
// handed to the same removal the per-kind routes use.
func (m *Module) removeExtension(ctx context.Context, in *nameInput) (*httpapi.Reply[packageState], error) {
accepted, err := m.store.List(ctx, m.orgID)
installed, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list accepted packages", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
m.log.ErrorContext(ctx, "list installations", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == in.Name })
i := slices.IndexFunc(installed, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == in.Name })
if i < 0 {
return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("no accepted package named %s", in.Name))
}
_, managed, err := packageOf(accepted[i])
_, managed, err := packageOf(installed[i])
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
reply, err := m.removeAs(ctx, in, accepted[i].Contract)
reply, err := m.removeAs(ctx, in, installed[i].Contract)
if err != nil {
return nil, err
}
@@ -64,9 +51,9 @@ func (m *Module) removeExtension(ctx context.Context, in *nameInput) (*httpapi.R
func (m *Module) registerExtensions(api huma.API) {
tags := []string{"Extensions"}
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindConnector), huma.Operation{
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindConnector), huma.Operation{
OperationID: "list-extensions", Method: http.MethodGet, Path: "/api/extensions",
Summary: "List every accepted package, whatever its contract", Tags: tags,
Summary: "List every installation the caller can see, whatever its contract and scope", Tags: tags,
}, m.listExtensions)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{
OperationID: "remove-extension", Method: http.MethodDelete, Path: "/api/extensions/{name}",
+5 -5
View File
@@ -191,28 +191,28 @@ func strengthName(s gpb.Strength) string {
// describe itself.
func (h *Host) StartGuard(ctx context.Context, spec Spec) (*Guard, error) {
raw, err := h.procs.Start(ctx, host.Spec{
Name: spec.Name, Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
Name: spec.Name, Key: spec.key(), Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
}, guardSurface, &guardPlugin{})
if err != nil {
return nil, err
}
client, ok := raw.(gpb.GuardServiceClient)
if !ok {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("guard %q: plugin is not a guard", spec.Name)
}
if _, err := client.Configure(ctx, &gpb.ConfigureRequest{Settings: spec.Settings, Secrets: spec.Secrets}); err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("guard %q: configure: %w", spec.Name, err)
}
desc, err := client.Describe(ctx, &gpb.DescribeRequest{})
if err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("guard %q: describe: %w", spec.Name, err)
}
settings := guardSettings(desc.GetSettings())
if err := validateSettingsSchema(settings); err != nil {
h.procs.Stop(spec.Name)
h.procs.Stop(spec.key())
return nil, fmt.Errorf("guard %q: %w", spec.Name, err)
}
return NewGuard(spec.Name, desc.GetVersion(), spec.SHA256, desc.GetAdvisory(), spec.Settings, settings, client), nil
+38 -32
View File
@@ -1,70 +1,76 @@
package connectors
import (
"cmp"
"maps"
"slices"
"time"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
)
// Health is what the module knows about one accepted package right now. It is
// Health is what the module knows about one installation right now. It is
// read from memory, so a database outage does not hide it.
type Health struct {
ID string `json:"id"`
Name string `json:"name"`
Scope string `json:"scope" enum:"instance,org,person"`
Contract string `json:"contract" doc:"connector, secretengine, guard or mcp"`
Healthy bool `json:"healthy"`
// Error is why the package is not running.
// Error is why the installation is not running.
Error string `json:"error,omitzero"`
// FailedAt is when the package last failed to start. A process that exited
// after it started has no time.
// FailedAt is when the installation last failed to start. A process that
// exited after it started has no time.
FailedAt *time.Time `json:"failed_at,omitzero"`
}
// Health lists every package the module launched, in name order: those running,
// those that failed to start, and those whose process has since exited or whose
// MCP server stopped answering.
// Health lists every installation the module launched, in name order: those
// running, those that failed to start, and those whose process has since
// exited or whose MCP server stopped answering.
func (m *Module) Health() []Health {
m.mu.RLock()
failed := maps.Clone(m.failed)
failedAt := maps.Clone(m.failedAt)
contracts := maps.Clone(m.contracts)
launched := maps.Clone(m.launched)
servers := maps.Clone(m.servers)
names := map[string]string{}
for name := range m.running {
names[name] = store.ContractConnector
started := map[string]bool{}
for id := range m.running {
started[id] = true
}
for name := range m.engines {
names[name] = store.ContractSecretEngine
for id := range m.engines {
started[id] = true
}
for name := range m.guards {
names[name] = store.ContractGuard
for id := range m.guards {
started[id] = true
}
for name := range servers {
names[name] = store.ContractMCP
}
for name := range failed {
if _, ok := names[name]; !ok {
names[name] = contracts[name]
}
for id := range servers {
started[id] = true
}
m.mu.RUnlock()
out := make([]Health, 0, len(names))
for _, name := range slices.Sorted(maps.Keys(names)) {
h := Health{Name: name, Contract: names[name], Healthy: true}
server, isServer := servers[name]
ids := make([]string, 0, len(launched))
for id := range launched {
if started[id] || failed[id] != "" {
ids = append(ids, id)
}
}
slices.SortFunc(ids, func(a, b string) int {
return cmp.Or(cmp.Compare(launched[a].name, launched[b].name), cmp.Compare(a, b))
})
out := make([]Health, 0, len(ids))
for _, id := range ids {
info := launched[id]
h := Health{ID: id, Name: info.name, Scope: info.scope, Contract: info.contract, Healthy: true}
server, isServer := servers[id]
switch {
case failed[name] != "":
h.Healthy, h.Error = false, failed[name]
if at, ok := failedAt[name]; ok {
case failed[id] != "":
h.Healthy, h.Error = false, failed[id]
if at, ok := failedAt[id]; ok {
h.FailedAt = &at
}
case isServer:
if err := server.Ready(); err != nil {
h.Healthy, h.Error = false, err.Error()
}
case !m.host.Alive(name):
case !m.host.Alive(id):
h.Healthy, h.Error = false, "process exited"
}
out = append(out, h)
+314
View File
@@ -0,0 +1,314 @@
package connectors
import (
"cmp"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"fmt"
"net/http"
"slices"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
func (m *Module) registerInstallations(api huma.API) {
tags := []string{"Installations"}
read := httpapi.Authorized(governance.ActionRead, governance.KindConnector)
write := httpapi.Authorized(governance.ActionUpdate, governance.KindConnector)
httpapi.Register(api, read, huma.Operation{
OperationID: "list-packages", Method: http.MethodGet, Path: "/api/packages",
Summary: "List the packages the instance accepted", Tags: tags,
}, m.listPackages)
httpapi.Register(api, write, huma.Operation{
OperationID: "create-installation", Method: http.MethodPost, Path: "/api/installations",
Summary: "Install an accepted package at the instance, the caller's organisation or the caller", Tags: tags,
}, m.createInstallation)
httpapi.Register(api, write, huma.Operation{
OperationID: "update-installation", Method: http.MethodPut, Path: "/api/installations/{id}",
Summary: "Change an installation's configuration and restart it", Tags: tags,
}, m.updateInstallation)
httpapi.Register(api, httpapi.Authorized(governance.ActionDelete, governance.KindConnector), huma.Operation{
OperationID: "remove-installation", Method: http.MethodDelete, Path: "/api/installations/{id}",
Summary: "Remove an installation; its package stays accepted", Tags: tags,
}, m.removeInstallation)
httpapi.Register(api, write, huma.Operation{
OperationID: "put-installation-override", Method: http.MethodPut, Path: "/api/installations/{id}/override",
Summary: "Switch an inherited installation off or on for the caller's organisation or the caller", Tags: tags,
}, m.putOverride)
}
// PackageView is one package the instance accepted.
type PackageView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Contract string `json:"contract"`
Group string `json:"group" enum:"platform,integration,agent"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
Version string `json:"version,omitempty"`
Digest string `json:"digest"`
// Managed says the package was installed from the catalogue. A managed
// package can be installed below the instance only once its grants are
// accepted.
Managed bool `json:"managed"`
Installed bool `json:"installed" doc:"Whether the instance accepted the package's grants, so an organisation or a person can install it"`
AcceptedAt time.Time `json:"accepted_at"`
}
func (m *Module) listPackages(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]PackageView], error) {
pkgs, err := m.store.Packages(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list packages", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the packages")
}
out := make([]PackageView, 0, len(pkgs))
for _, p := range pkgs {
view := PackageView{
ID: p.ID, Name: p.Name, Contract: p.Contract, Group: string(store.GroupOf(p.Contract)),
Digest: p.SHA256, Installed: true, AcceptedAt: p.AcceptedAt,
}
if rec, ok, err := packageOf(store.Installed{Manifest: p.Manifest, Name: p.Name}); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
} else if ok {
view.Managed = true
view.DisplayName, view.Description, view.Version = rec.DisplayName, rec.Description, rec.State.Current.Version
view.Installed = rec.State.Accepted != nil
}
out = append(out, view)
}
return httpapi.OK(out), nil
}
// installationRequest is the configuration of one installation.
type installationRequest struct {
Settings map[string]string `json:"settings,omitzero"`
Egress []string `json:"egress,omitzero" doc:"Every host the extension may reach. An installation below the instance must name them, unless the package runs unconfined"`
Env []string `json:"env,omitzero" doc:"Host environment variables the extension may see; the instance's installations of the package bound them"`
Credentials map[string]string `json:"credentials,omitzero" doc:"Each credential slot and the credential, by name, that fills it"`
// Args, URL and Tools configure an MCP server.
Args []string `json:"args,omitzero"`
URL string `json:"url,omitzero"`
Tools []ToolDecl `json:"tools,omitzero"`
Enabled bool `json:"enabled"`
}
type createInstallationInput struct {
Body struct {
Package string `json:"package" doc:"The accepted package to install"`
Name string `json:"name,omitzero" doc:"What a binding calls the installation. Default: the package's name"`
Scope string `json:"scope" enum:"instance,org,person" doc:"Who owns the installation: the instance, the caller's organisation or the caller"`
installationRequest
}
}
type updateInstallationInput struct {
ID uuid.UUID `path:"id"`
Body installationRequest
}
func (m *Module) createInstallation(ctx context.Context, in *createInstallationInput) (*httpapi.Reply[ExtensionView], error) {
req := in.Body
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
owner, err := auth.ownerAt(req.Scope)
if err != nil {
return nil, err
}
pkgs, installed, err := m.packagesAndInstallations(ctx)
if err != nil {
return nil, err
}
i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == req.Package })
if i < 0 {
return nil, errNoPackage(req.Package)
}
pkg := pkgs[i]
name := cmp.Or(req.Name, pkg.Name)
if !validName.MatchString(name) {
return nil, huma.NewError(http.StatusBadRequest, "an installation needs a lowercase name")
}
if slices.ContainsFunc(installed, func(a store.Installed) bool { return a.Owner() == owner && a.Name == name }) {
return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("%s already has an installation named %s", owner.Scope, name))
}
a := store.Installed{
ID: uuid.New(), PackageID: pkg.ID, Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID, Name: name,
PackageName: pkg.Name, Contract: pkg.Contract, Path: pkg.Path, SHA256: pkg.SHA256,
Manifest: pkg.Manifest, Effects: pkg.Effects, Capabilities: pkg.Capabilities,
}
return m.saveInstallation(ctx, auth, a, req.installationRequest, installed, false, store.Installed{})
}
func (m *Module) updateInstallation(ctx context.Context, in *updateInstallationInput) (*httpapi.Reply[ExtensionView], error) {
previous, auth, err := m.installationFor(ctx, in.ID, true)
if err != nil {
return nil, err
}
if previous.Scope == store.ScopeInstance && len(previous.Manifest) > 0 {
return nil, huma.NewError(http.StatusConflict, previous.Name+" is installed from the catalogue; change it through its extension page")
}
installed, err := m.store.List(ctx)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
return m.saveInstallation(ctx, auth, previous, in.Body, installed, true, previous)
}
// saveInstallation applies req to a, checks it, starts it and stores it.
func (m *Module) saveInstallation(ctx context.Context, auth authority, a store.Installed, req installationRequest, installed []store.Installed, hadPrevious bool, previous store.Installed) (*httpapi.Reply[ExtensionView], error) {
if rec, managed, err := packageOf(a); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
} else if managed && rec.State.Accepted == nil {
return nil, huma.NewError(http.StatusConflict, "the instance hasn't accepted the grants of "+a.PackageName)
}
settings, err := json.Marshal(req.Settings, json.FormatNilMapAsNull(false))
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
slots, err := json.Marshal(req.Credentials, json.FormatNilMapAsNull(false))
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
tools := jsontext.Value(`[]`)
if a.Contract == store.ContractMCP {
check := mcpRequest{URL: req.URL, Path: a.Path, SHA256: a.SHA256, Args: req.Args, Settings: req.Settings, Tools: req.Tools}
if err := check.check(); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if tools, err = json.Marshal(req.Tools); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
} else if req.URL != "" || len(req.Args) > 0 || len(req.Tools) > 0 {
return nil, huma.NewError(http.StatusBadRequest, "only an MCP server takes a url, arguments or tools")
}
if err := checkGrants(a, req, installed); err != nil {
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
a.Settings, a.Credentials, a.Tools = settings, slots, tools
a.Egress, a.Env, a.Args, a.URL, a.Enabled = req.Egress, req.Env, req.Args, req.URL, req.Enabled
persist := func(ctx context.Context, in store.Installed, caps jsontext.Value) (store.Installed, error) {
return m.store.SaveInstallation(ctx, in, caps)
}
if err := m.commit(context.WithoutCancel(ctx), a, hadPrevious, previous, persist); err != nil {
return nil, acceptError(err)
}
m.log.InfoContext(ctx, "installation saved", "audit", true, "action", "installation.save",
"installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName)
view, err := m.viewOf(a, auth.manages(a.Owner()))
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
return httpapi.OK(view), nil
}
func (m *Module) packagesAndInstallations(ctx context.Context) ([]store.Package, []store.Installed, error) {
pkgs, err := m.store.Packages(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list packages", "error", err)
return nil, nil, huma.NewError(http.StatusInternalServerError, "couldn't read the packages")
}
installed, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list installations", "error", err)
return nil, nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
return pkgs, installed, nil
}
// checkGrants bounds what an organisation or a person may grant an extension.
// The instance's installations of a package are what an administrator
// accepted, so an installation below them may see only the environment
// variables those pass on, and must name the hosts it reaches unless an
// administrator ran the package unconfined. A host is the installer's own to
// name, since each installation reaches a different system.
func checkGrants(a store.Installed, req installationRequest, installed []store.Installed) error {
if a.Scope == store.ScopeInstance {
return nil
}
var passed map[string]bool
unconfined := false
for _, other := range installed {
if other.PackageID != a.PackageID || other.Scope != store.ScopeInstance {
continue
}
if passed == nil {
passed = map[string]bool{}
}
for _, name := range other.Env {
passed[name] = true
}
unconfined = unconfined || len(other.Egress) == 0
}
for _, name := range req.Env {
if !passed[name] {
return fmt.Errorf("environment variable %s isn't passed on by an instance installation of %s", name, a.PackageName)
}
}
if len(req.Egress) == 0 && !unconfined && a.Contract != store.ContractMCP {
return fmt.Errorf("name the hosts %s reaches", a.PackageName)
}
return nil
}
type overrideInput struct {
ID uuid.UUID `path:"id"`
Body struct {
Scope string `json:"scope" enum:"org,person" doc:"Switch it off for the caller's organisation or for the caller"`
Off bool `json:"off" doc:"True switches the inherited installation off; false restores it"`
}
}
// putOverride switches an installation the caller inherits off or on. It never
// changes the installation: it is the caller's organisation or the caller that
// stops using it.
func (m *Module) putOverride(ctx context.Context, in *overrideInput) (*httpapi.Reply[packageState], error) {
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
a, _, err := m.installationFor(ctx, in.ID, false)
if err != nil {
return nil, err
}
owner, err := auth.ownerAt(in.Body.Scope)
if err != nil {
return nil, err
}
if owner.Scope == store.ScopeInstance || !inherits(owner, a.Owner()) {
return nil, huma.NewError(http.StatusUnprocessableEntity, "only an installation owned by a broader scope can be switched off")
}
o := store.Override{InstallationID: a.ID, Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID}
if err := m.store.SetOverride(ctx, o, in.Body.Off, governance.CallerID(ctx)); err != nil {
m.log.ErrorContext(ctx, "set installation override", "installation", a.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't change the installation")
}
if _, err := m.refresh(ctx); err != nil {
m.log.ErrorContext(ctx, "read installations", "error", err)
}
state := "running"
if in.Body.Off {
state = "removed"
}
return httpapi.OK(packageState{Name: a.Name, State: state}), nil
}
// inherits reports whether a scope owning by inheritor reaches installations
// that owner owns from a broader scope: an organisation reaches the instance's,
// and a person the instance's and their organisation's.
func inherits(inheritor, owner store.Owner) bool {
switch inheritor.Scope {
case store.ScopeOrg:
return owner.Scope == store.ScopeInstance
case store.ScopePerson:
return owner.Scope == store.ScopeInstance || owner.Scope == store.ScopeOrg
}
return false
}
+9 -3
View File
@@ -4,6 +4,7 @@ package host
import (
"bytes"
"cmp"
"context"
"crypto/sha256"
"encoding/hex"
@@ -31,6 +32,10 @@ var Handshake = goplugin.HandshakeConfig{
// Spec is one extension to run.
type Spec struct {
Name string
// Key identifies the running process: Start, Stop and Alive use it. It is
// the installation ID, so two installations of one package run apart. It
// defaults to Name.
Key string
// Path is the extension binary.
Path string
// SHA256 is the hex digest the binary must match before it is launched.
@@ -44,7 +49,7 @@ type Spec struct {
Egress []string
}
// Host owns the running extension processes, keyed by Spec.Name.
// Host owns the running extension processes, keyed by Spec.Key.
type Host struct {
// log is the service's logger; plugin lifecycle goes through hclog.
log *slog.Logger
@@ -130,9 +135,10 @@ func (h *Host) Start(ctx context.Context, spec Spec, surface string, impl goplug
p.kill()
return nil, fmt.Errorf("extension %q: dispense %s: %w", spec.Name, surface, err)
}
key := cmp.Or(spec.Key, spec.Name)
h.mu.Lock()
old := h.procs[spec.Name]
h.procs[spec.Name] = p
old := h.procs[key]
h.procs[key] = p
h.mu.Unlock()
if old != nil {
old.kill()
+286 -130
View File
@@ -1,8 +1,10 @@
// Package store holds the connectors module's SQL: the accepted extensions the
// host starts at boot and the sealed credentials they are configured with.
// Package store holds the connectors module's SQL: the packages the instance
// accepted, the installations that configure them at a scope, and the sealed
// credentials those installations use.
package store
import (
"cmp"
"context"
"database/sql"
"database/sql/driver"
@@ -12,24 +14,22 @@ import (
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Source is where an organisation's catalogue is read from.
// Source is where the instance's catalogue is read from.
type Source struct {
OrgID string `db:"org_id"`
Location string `db:"location"`
PublicKey string `db:"public_key"`
// Newest is the issue time of the newest catalogue accepted from it.
Newest sql.NullTime `db:"newest_issued_at"`
}
// CatalogueSource returns the organisation's catalogue source; ok is false when
// none is set.
func (s *Store) CatalogueSource(ctx context.Context, orgID string) (Source, bool, error) {
// CatalogueSource returns the catalogue source; ok is false when none is set.
func (s *Store) CatalogueSource(ctx context.Context) (Source, bool, error) {
var out Source
err := s.db.GetContext(ctx, &out, `
SELECT org_id, location, public_key, newest_issued_at FROM connectors.catalogue_source WHERE org_id = $1`, orgID)
err := s.db.GetContext(ctx, &out, `SELECT location, public_key, newest_issued_at FROM connectors.catalogue_source`)
if errors.Is(err, sql.ErrNoRows) {
return Source{}, false, nil
}
@@ -44,13 +44,13 @@ func (s *Store) CatalogueSource(ctx context.Context, orgID string) (Source, bool
// changes.
func (s *Store) PutCatalogueSource(ctx context.Context, src Source) error {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO connectors.catalogue_source (org_id, location, public_key) VALUES ($1, $2, $3)
ON CONFLICT (org_id) DO UPDATE
INSERT INTO connectors.catalogue_source (location, public_key) VALUES ($1, $2)
ON CONFLICT (singleton) DO UPDATE
SET newest_issued_at = CASE WHEN connectors.catalogue_source.location = EXCLUDED.location
AND connectors.catalogue_source.public_key = EXCLUDED.public_key
THEN connectors.catalogue_source.newest_issued_at END,
location = EXCLUDED.location, public_key = EXCLUDED.public_key, updated_at = now()`,
src.OrgID, src.Location, src.PublicKey); err != nil {
src.Location, src.PublicKey); err != nil {
return fmt.Errorf("put catalogue source: %w", err)
}
return nil
@@ -58,10 +58,10 @@ func (s *Store) PutCatalogueSource(ctx context.Context, src Source) error {
// AdvanceCatalogue records a catalogue issued at issuedAt as accepted and
// reports false when a newer one was accepted already. It never lowers the mark.
func (s *Store) AdvanceCatalogue(ctx context.Context, orgID string, issuedAt time.Time) (bool, error) {
func (s *Store) AdvanceCatalogue(ctx context.Context, issuedAt time.Time) (bool, error) {
res, err := s.db.ExecContext(ctx, `
UPDATE connectors.catalogue_source SET newest_issued_at = $2
WHERE org_id = $1 AND (newest_issued_at IS NULL OR newest_issued_at <= $2)`, orgID, issuedAt)
UPDATE connectors.catalogue_source SET newest_issued_at = $1
WHERE newest_issued_at IS NULL OR newest_issued_at <= $1`, issuedAt)
if err != nil {
return false, fmt.Errorf("record catalogue freshness: %w", err)
}
@@ -69,47 +69,74 @@ func (s *Store) AdvanceCatalogue(ctx context.Context, orgID string, issuedAt tim
return n > 0, err
}
// Accepted is one package an operator accepted, with the authority it
// declared.
type Accepted struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
// Scopes an installation or a credential can be owned by.
const (
ScopeInstance = "instance"
ScopeOrg = "org"
ScopePerson = "person"
)
// Owner is the scope that owns an installation or a credential. OrgID is set
// for an organisation and PersonID for a person; both are empty for the
// instance.
type Owner struct {
Scope string
OrgID string
PersonID string
}
// 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.
type Installed struct {
ID uuid.UUID `db:"id"`
PackageID uuid.UUID `db:"package_id"`
Scope string `db:"scope"`
OrgID string `db:"org_id"`
PersonID string `db:"person_id"`
Name string `db:"name"`
PackageName string `db:"package_name"`
// Contract is ContractConnector, ContractSecretEngine, ContractMCP or
// ContractGuard.
Contract string `db:"contract"`
Path string `db:"path"`
SHA256 string `db:"sha256"`
Egress Strings `db:"egress"`
Env Strings `db:"env"`
Settings jsontext.Value `db:"settings"`
// Contract is ContractConnector, ContractSecretEngine, ContractMCP or
// ContractGuard.
Contract string `db:"contract"`
// Credentials maps a slot to a credential name, as a JSON object.
Credentials jsontext.Value `db:"credentials"`
// Args are a stdio MCP server's arguments; URL is an HTTP server's
// endpoint. Which one the acceptance set is what picks the transport.
// endpoint. Which one is set picks the transport.
Args Strings `db:"args"`
URL string `db:"url"`
// Tools are the lookups and actions an MCP server's acceptance declares,
// as a JSON array.
// Tools are the lookups and actions an MCP server declares, as a JSON
// array.
Tools jsontext.Value `db:"tools"`
// Effects is an MCP server's declared privileged effects, as a JSON
// object. It is nil until the operator declares them. A []byte for the
// same reason as Capabilities.
// object. It is nil until declared. A []byte because database/sql scans
// NULL into []byte but not into a named byte slice such as jsontext.Value.
Effects []byte `db:"effects"`
// Capabilities is what a connector declared when it last loaded, as a JSON
// object. It is nil until then, and acceptance never changes it. It is a
// []byte because database/sql scans NULL into []byte but not into a named
// byte slice such as jsontext.Value.
// object. It is nil until then.
Capabilities []byte `db:"capabilities"`
// Enabled says whether the package runs. A package that is not enabled is
// accepted and kept but never launched.
// Enabled says whether the installation runs. One that is not enabled is
// kept but never launched.
Enabled bool `db:"enabled"`
// Package is the lifecycle of a package installed from the catalogue, as a
// JSON object. It is nil for a package accepted by path. A []byte for the
// same reason as Capabilities.
Package []byte `db:"package"`
// Manifest is the lifecycle of a package installed from the catalogue, as
// a JSON object. It is nil for a package accepted by path.
Manifest []byte `db:"manifest"`
}
// Contracts an accepted package can serve.
// Owner returns the scope that owns the installation.
func (i Installed) Owner() Owner { return Owner{Scope: i.Scope, OrgID: i.OrgID, PersonID: i.PersonID} }
const installedColumns = `i.id, i.package_id, i.scope, i.org_id, i.person_id, i.name, p.name AS package_name,
p.contract, p.path, p.sha256, i.egress, i.env, i.settings, i.credentials, i.args, i.url, i.tools,
p.effects, p.capabilities, i.enabled, p.manifest`
const installedFrom = ` FROM connectors.installations i JOIN connectors.packages p ON p.id = i.package_id`
// Contracts a package can serve.
const (
ContractConnector = "connector"
ContractSecretEngine = "secretengine"
@@ -128,7 +155,7 @@ const (
GroupAgent Group = "agent"
)
// Contracts lists every known contract with its group. Upsert refuses any
// Contracts lists every known contract with its group. Saving refuses any
// contract not in this table, so every stored package has a group.
func Contracts() []ContractGroup {
return []ContractGroup{
@@ -155,12 +182,41 @@ func GroupOf(contract string) Group {
return ""
}
// Credential is a credential's sealed fields.
// Credential is a credential's sealed fields and the scope that owns it.
type Credential struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
Kind string `db:"kind"`
Sealed []byte `db:"sealed"`
ID uuid.UUID `db:"id"`
Scope string `db:"scope"`
OrgID string `db:"org_id"`
PersonID string `db:"person_id"`
Name string `db:"name"`
Kind string `db:"kind"`
Sealed []byte `db:"sealed"`
}
// 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.
type Package struct {
ID uuid.UUID `db:"id"`
Name string `db:"name"`
Contract string `db:"contract"`
Path string `db:"path"`
SHA256 string `db:"sha256"`
Manifest []byte `db:"manifest"`
Capabilities []byte `db:"capabilities"`
Effects []byte `db:"effects"`
AcceptedByID string `db:"accepted_by_id"`
AcceptedAt time.Time `db:"accepted_at"`
}
// Override records that an organisation or a person switched off an
// installation it would otherwise inherit.
type Override struct {
InstallationID uuid.UUID `db:"installation_id"`
Scope string `db:"scope"`
OrgID string `db:"org_id"`
PersonID string `db:"person_id"`
}
// Store is the connectors module's Postgres store.
@@ -171,135 +227,235 @@ type Store struct {
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
// List returns an organisation's accepted connectors.
func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) {
var out []Accepted
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools, effects, capabilities, enabled, package
FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("list connectors: %w", err)
// List returns every installation with its package, whatever its scope.
func (s *Store) List(ctx context.Context) ([]Installed, error) {
var out []Installed
if err := s.db.SelectContext(ctx, &out, `SELECT `+installedColumns+installedFrom+` ORDER BY i.name, i.scope, i.org_id, i.person_id`); err != nil {
return nil, fmt.Errorf("list installations: %w", err)
}
return out, nil
}
// Upsert records an accepted connector, replacing an earlier acceptance.
func (s *Store) Upsert(ctx context.Context, a Accepted) error {
return upsert(ctx, s.db, a)
// Packages returns every accepted package in name order.
func (s *Store) Packages(ctx context.Context) ([]Package, error) {
var out []Package
if err := s.db.SelectContext(ctx, &out, `
SELECT id, name, contract, path, sha256, manifest, capabilities, effects, accepted_by_id, accepted_at
FROM connectors.packages ORDER BY name`); err != nil {
return nil, fmt.Errorf("list packages: %w", err)
}
return out, nil
}
// SetCapabilities records what an accepted connector declared when it loaded.
func (s *Store) SetCapabilities(ctx context.Context, orgID, name string, capabilities jsontext.Value) error {
return setCapabilities(ctx, s.db, orgID, name, capabilities)
// Overrides returns every switched-off inherited installation.
func (s *Store) Overrides(ctx context.Context) ([]Override, error) {
var out []Override
if err := s.db.SelectContext(ctx, &out, `SELECT installation_id, scope, org_id, person_id FROM connectors.installation_overrides`); err != nil {
return nil, fmt.Errorf("list installation overrides: %w", err)
}
return out, nil
}
// Save records an acceptance together with what the connector declared, in one
// transaction, so a failure leaves the acceptance and its declarations as they
// were. Nil capabilities leave the stored declarations unchanged.
func (s *Store) Save(ctx context.Context, a Accepted, capabilities jsontext.Value) error {
// SetOverride switches an inherited installation off for an organisation or a
// person, or back on when off is false.
func (s *Store) SetOverride(ctx context.Context, o Override, off bool, by string) error {
var err error
if off {
_, err = s.db.ExecContext(ctx, `
INSERT INTO connectors.installation_overrides (installation_id, scope, org_id, person_id, disabled_by_id)
VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING`, o.InstallationID, o.Scope, o.OrgID, o.PersonID, by)
} else {
_, err = s.db.ExecContext(ctx, `
DELETE FROM connectors.installation_overrides
WHERE installation_id = $1 AND scope = $2 AND org_id = $3 AND person_id = $4`,
o.InstallationID, o.Scope, o.OrgID, o.PersonID)
}
if err != nil {
return fmt.Errorf("set installation override: %w", err)
}
return nil
}
// SaveInstalled records a package and one installation of it in one
// transaction, replacing the earlier package of that name and the earlier
// installation of that name at the same owner. Nil capabilities leave the
// stored declarations unchanged. It returns the stored row, with its IDs.
func (s *Store) SaveInstalled(ctx context.Context, in Installed, by string, capabilities jsontext.Value) (Installed, error) {
if GroupOf(in.Contract) == "" {
return Installed{}, fmt.Errorf("accept %q: unknown contract %q", in.Name, in.Contract)
}
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("save %q: %w", a.Name, err)
return Installed{}, fmt.Errorf("save %q: %w", in.Name, err)
}
defer func() { _ = tx.Rollback() }()
if err := upsert(ctx, tx, a); err != nil {
return err
if err := tx.GetContext(ctx, &in.PackageID, `
INSERT INTO connectors.packages (id, name, contract, path, sha256, manifest, effects, accepted_by_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (name) DO UPDATE
SET contract = EXCLUDED.contract, path = EXCLUDED.path, sha256 = EXCLUDED.sha256,
manifest = EXCLUDED.manifest, effects = EXCLUDED.effects, updated_at = now()
RETURNING id`,
cmp.Or(in.PackageID, uuid.New()), in.PackageName, in.Contract, in.Path, in.SHA256, nilIfEmpty(in.Manifest), nilIfEmpty(in.Effects), by); err != nil {
return Installed{}, fmt.Errorf("accept package %q: %w", in.PackageName, err)
}
if in.ID, err = upsertInstallation(ctx, tx, in); err != nil {
return Installed{}, err
}
if capabilities != nil {
if err := setCapabilities(ctx, tx, a.OrgID, a.Name, capabilities); err != nil {
return err
if err := setCapabilities(ctx, tx, in.PackageID, capabilities); err != nil {
return Installed{}, err
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("save %q: %w", a.Name, err)
return Installed{}, fmt.Errorf("save %q: %w", in.Name, err)
}
return nil
return in, nil
}
func upsert(ctx context.Context, db sqlx.ExtContext, a Accepted) error {
if GroupOf(a.Contract) == "" {
return fmt.Errorf("accept %q: unknown contract %q", a.Name, a.Contract)
}
if _, err := sqlx.NamedExecContext(ctx, db, `
INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools, effects, enabled, package)
VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings, :contract, :credentials, :args, :url, :tools, :effects, :enabled, :package)
ON CONFLICT (org_id, name) DO UPDATE
SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress,
env = EXCLUDED.env, settings = EXCLUDED.settings, contract = EXCLUDED.contract,
credentials = EXCLUDED.credentials, args = EXCLUDED.args, url = EXCLUDED.url,
tools = EXCLUDED.tools, effects = EXCLUDED.effects, enabled = EXCLUDED.enabled,
package = EXCLUDED.package, updated_at = now()`, a); err != nil {
return fmt.Errorf("accept connector: %w", err)
}
return nil
}
func setCapabilities(ctx context.Context, db sqlx.ExtContext, orgID, name string, capabilities jsontext.Value) error {
if _, err := db.ExecContext(ctx, `
UPDATE connectors.accepted SET capabilities = $3 WHERE org_id = $1 AND name = $2`, orgID, name, []byte(capabilities)); err != nil {
return fmt.Errorf("store capabilities of %q: %w", name, err)
}
return nil
}
// Capabilities returns what the named connector declared when it last loaded.
// ok is false when it isn't accepted or has never loaded.
func (s *Store) Capabilities(ctx context.Context, orgID, name string) (raw jsontext.Value, ok bool, err error) {
err = s.db.GetContext(ctx, &raw, `
SELECT capabilities FROM connectors.accepted WHERE org_id = $1 AND name = $2 AND capabilities IS NOT NULL`, orgID, name)
if errors.Is(err, sql.ErrNoRows) {
return nil, false, nil
}
// SaveInstallation records an installation of an accepted package, replacing
// the earlier installation of that name at the same owner. Nil capabilities
// leave the package's stored declarations unchanged. It returns the stored
// row, with its ID.
func (s *Store) SaveInstallation(ctx context.Context, in Installed, capabilities jsontext.Value) (Installed, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return nil, false, fmt.Errorf("read capabilities of %q: %w", name, err)
return Installed{}, fmt.Errorf("save %q: %w", in.Name, err)
}
return raw, true, nil
defer func() { _ = tx.Rollback() }()
if in.ID, err = upsertInstallation(ctx, tx, in); err != nil {
return Installed{}, err
}
if capabilities != nil {
if err := setCapabilities(ctx, tx, in.PackageID, capabilities); err != nil {
return Installed{}, err
}
}
if err := tx.Commit(); err != nil {
return Installed{}, fmt.Errorf("save %q: %w", in.Name, err)
}
return in, nil
}
// Delete removes an accepted package and reports whether there was one. Its
// credential slots live on the row, so they go with it.
func (s *Store) Delete(ctx context.Context, orgID, name string) (bool, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM connectors.accepted WHERE org_id = $1 AND name = $2`, orgID, name)
func upsertInstallation(ctx context.Context, tx *sqlx.Tx, in Installed) (uuid.UUID, error) {
var id uuid.UUID
err := tx.GetContext(ctx, &id, `
INSERT INTO connectors.installations
(id, package_id, scope, org_id, person_id, name, settings, egress, env, credentials, args, url, tools, enabled)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (scope, org_id, person_id, name) DO UPDATE
SET package_id = EXCLUDED.package_id, settings = EXCLUDED.settings, egress = EXCLUDED.egress,
env = EXCLUDED.env, credentials = EXCLUDED.credentials, args = EXCLUDED.args, url = EXCLUDED.url,
tools = EXCLUDED.tools, enabled = EXCLUDED.enabled, updated_at = now()
RETURNING id`,
cmp.Or(in.ID, uuid.New()), in.PackageID, in.Scope, in.OrgID, in.PersonID, in.Name, orDefault(in.Settings, "{}"), in.Egress, in.Env,
orDefault(in.Credentials, "{}"), in.Args, in.URL, orDefault(in.Tools, "[]"), in.Enabled)
if err != nil {
return false, fmt.Errorf("remove connector %q: %w", name, err)
return uuid.Nil, fmt.Errorf("save installation %q: %w", in.Name, err)
}
return id, nil
}
func setCapabilities(ctx context.Context, tx *sqlx.Tx, packageID uuid.UUID, capabilities jsontext.Value) error {
if _, err := tx.ExecContext(ctx, `UPDATE connectors.packages SET capabilities = $2 WHERE id = $1`, packageID, []byte(capabilities)); err != nil {
return fmt.Errorf("store capabilities: %w", err)
}
return nil
}
func orDefault(v jsontext.Value, empty string) []byte {
if len(v) == 0 {
return []byte(empty)
}
return v
}
func nilIfEmpty(b []byte) []byte {
if len(b) == 0 {
return nil
}
return b
}
// SetCapabilities records what a connector declared when it loaded.
func (s *Store) SetCapabilities(ctx context.Context, packageID uuid.UUID, capabilities jsontext.Value) error {
if _, err := s.db.ExecContext(ctx, `UPDATE connectors.packages SET capabilities = $2 WHERE id = $1`, packageID, []byte(capabilities)); err != nil {
return fmt.Errorf("store capabilities: %w", err)
}
return nil
}
// DeleteInstallation removes one installation and reports whether there was
// one. Its overrides go with it.
func (s *Store) DeleteInstallation(ctx context.Context, id uuid.UUID) (bool, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM connectors.installations WHERE id = $1`, id)
if err != nil {
return false, fmt.Errorf("remove installation: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return false, fmt.Errorf("remove connector %q: %w", name, err)
}
return n > 0, nil
return n > 0, err
}
// Credential returns the named credential; ok is false when there is none.
func (s *Store) Credential(ctx context.Context, orgID, name string) (Credential, bool, error) {
var c Credential
err := s.db.GetContext(ctx, &c, `
SELECT org_id, name, kind, sealed FROM connectors.credentials WHERE org_id = $1 AND name = $2`, orgID, name)
// ErrInstalled means an organisation or a person still has an installation of
// the package.
var ErrInstalled = errors.New("the package is still installed by an organisation or a person")
// DeletePackage removes a package and its instance installations, and reports
// whether there was one. It fails while an organisation or a person still has
// an installation of it.
func (s *Store) DeletePackage(ctx context.Context, name string) (bool, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return false, fmt.Errorf("remove package %q: %w", name, err)
}
defer func() { _ = tx.Rollback() }()
var id uuid.UUID
err = tx.GetContext(ctx, &id, `SELECT id FROM connectors.packages WHERE name = $1`, name)
if errors.Is(err, sql.ErrNoRows) {
return Credential{}, false, nil
return false, nil
}
if err != nil {
return Credential{}, false, fmt.Errorf("read credential %q: %w", name, err)
return false, fmt.Errorf("remove package %q: %w", name, err)
}
return c, true, nil
var others int
if err := tx.GetContext(ctx, &others, `SELECT count(*) FROM connectors.installations WHERE package_id = $1 AND scope <> 'instance'`, id); err != nil {
return false, fmt.Errorf("remove package %q: %w", name, err)
}
if others > 0 {
return false, ErrInstalled
}
if _, err := tx.ExecContext(ctx, `DELETE FROM connectors.installations WHERE package_id = $1`, id); err != nil {
return false, fmt.Errorf("remove package %q: %w", name, err)
}
if _, err := tx.ExecContext(ctx, `DELETE FROM connectors.packages WHERE id = $1`, id); err != nil {
return false, fmt.Errorf("remove package %q: %w", name, err)
}
if err := tx.Commit(); err != nil {
return false, fmt.Errorf("remove package %q: %w", name, err)
}
return true, nil
}
// Credentials returns an organisation's credentials in name order.
func (s *Store) Credentials(ctx context.Context, orgID string) ([]Credential, error) {
// Credentials returns every credential, whatever its scope, in name order.
func (s *Store) Credentials(ctx context.Context) ([]Credential, error) {
var out []Credential
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, kind, sealed FROM connectors.credentials WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
SELECT id, scope, org_id, person_id, name, kind, sealed FROM connectors.credentials
ORDER BY name, scope, org_id, person_id`); err != nil {
return nil, fmt.Errorf("list credentials: %w", err)
}
return out, nil
}
// PutCredential records a credential, replacing an earlier one of that name.
// 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.NamedExecContext(ctx, `
INSERT INTO connectors.credentials (org_id, name, kind, sealed)
VALUES (:org_id, :name, :kind, :sealed)
ON CONFLICT (org_id, name) DO UPDATE
SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now()`, c); err != nil {
if _, err := s.db.ExecContext(ctx, `
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)
}
return nil
+94 -45
View File
@@ -1,6 +1,7 @@
package connectors
import (
"cmp"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
@@ -8,6 +9,7 @@ import (
"net/http"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/connectors/internal/catalogue"
@@ -19,7 +21,25 @@ import (
// It never carries a secret: a credential is named, and a secret setting is
// the reference the extension resolves.
type ExtensionView struct {
Name string `json:"name"`
// ID is the installation's ID, which a decision records.
ID uuid.UUID `json:"id"`
// Name is the installation's name, which a binding uses; Package is the
// package it installs.
Name string `json:"name"`
Package string `json:"package"`
// Scope is who owns the installation. OwnerID is the organisation or the
// person, and is empty for the instance.
Scope string `json:"scope" enum:"instance,org,person"`
OwnerID string `json:"owner_id,omitempty"`
// Editable says whether the caller may change the installation. Overridden
// says the caller's organisation or person switched an inherited
// installation off, and OverriddenBy names the scopes that did. CanOverride
// lists the scopes the caller may switch it off at, and is empty when the
// caller owns it or inherits nothing.
Editable bool `json:"editable"`
Overridden bool `json:"overridden"`
OverriddenBy []string `json:"overridden_by,omitempty" enum:"org,person"`
CanOverride []string `json:"can_override,omitempty" enum:"org,person"`
Contract string `json:"contract"`
Group string `json:"group" enum:"platform,integration,agent"`
State string `json:"state"`
@@ -58,42 +78,67 @@ type ExtensionView struct {
UpdatePolicy string `json:"update_policy,omitempty"`
}
// list returns the accepted packages of one contract, in name order.
// list returns the installations of one contract the caller can see, in name
// order.
func (m *Module) list(contract string) func(context.Context, *struct{}) (*httpapi.Reply[[]ExtensionView], error) {
return func(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ExtensionView], error) {
accepted, err := m.store.List(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list accepted packages", "contract", contract, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
}
views := make([]ExtensionView, 0, len(accepted))
for _, a := range accepted {
if a.Contract != contract {
continue
}
view, err := m.viewOf(a)
if err != nil {
m.log.ErrorContext(ctx, "read accepted package", "package", a.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read "+a.Name)
}
views = append(views, view)
}
return httpapi.OK(views), nil
return m.listViews(ctx, func(a store.Installed) bool { return a.Contract == contract })
}
}
func (m *Module) viewOf(a store.Accepted) (ExtensionView, error) {
// listViews returns the installations the caller can see that keep accepts.
func (m *Module) listViews(ctx context.Context, keep func(store.Installed) bool) (*httpapi.Reply[[]ExtensionView], error) {
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
installed, err := m.refresh(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list installations", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
scope := ScopeFromContext(ctx)
views := make([]ExtensionView, 0, len(installed))
for _, a := range installed {
if !keep(a) || !auth.sees(a.Owner()) {
continue
}
view, err := m.viewOf(a, auth.manages(a.Owner()))
if err != nil {
m.log.ErrorContext(ctx, "read installation", "installation", a.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read "+a.Name)
}
m.mu.RLock()
mem := m.idx.members[a.ID.String()]
view.Overridden = m.idx.hidden(scope, mem)
view.OverriddenBy = m.idx.overriddenBy(scope, mem)
m.mu.RUnlock()
if !view.Editable {
view.CanOverride = overrideScopes(auth, a.Owner())
}
views = append(views, view)
}
return httpapi.OK(views), nil
}
// viewOf shows an installation. A caller who may not change it sees what it is
// and whether it runs, and none of its configuration.
func (m *Module) viewOf(a store.Installed, editable bool) (ExtensionView, error) {
view := ExtensionView{
Name: a.Name, Contract: a.Contract, Group: string(store.GroupOf(a.Contract)), Digest: a.SHA256, Path: a.Path, URL: a.URL,
Args: a.Args, Egress: a.Egress, Env: a.Env, Tools: a.Tools,
ID: a.ID, Name: a.Name, Package: a.PackageName, Scope: a.Scope, OwnerID: cmp.Or(a.OrgID, a.PersonID), Editable: editable,
Contract: a.Contract, Group: string(store.GroupOf(a.Contract)), Digest: a.SHA256, Tools: a.Tools,
Egress: []string{}, Env: []string{},
Settings: map[string]string{}, Credentials: map[string]string{}, SettingsSchema: []Setting{},
}
if len(a.Settings) > 0 {
if editable {
view.Path, view.URL, view.Args, view.Egress, view.Env = a.Path, a.URL, a.Args, a.Egress, a.Env
}
if len(a.Settings) > 0 && editable {
if err := json.Unmarshal(a.Settings, &view.Settings); err != nil {
return ExtensionView{}, fmt.Errorf("settings: %w", err)
}
}
if len(a.Credentials) > 0 {
if len(a.Credentials) > 0 && editable {
if err := json.Unmarshal(a.Credentials, &view.Credentials); err != nil {
return ExtensionView{}, fmt.Errorf("credentials: %w", err)
}
@@ -111,6 +156,9 @@ func (m *Module) viewOf(a store.Accepted) (ExtensionView, error) {
}
}
state, reason, version, schema := m.stateOf(a)
if !editable {
schema = []Setting{}
}
view.State, view.Error, view.Version, view.SettingsSchema = state, reason, version, schema
view.Enabled = a.Enabled
if rec, ok, err := packageOf(a); err != nil {
@@ -127,13 +175,14 @@ func (m *Module) viewOf(a store.Accepted) (ExtensionView, error) {
}
// stateOf reports whether a package is running, and what it declared.
func (m *Module) stateOf(a store.Accepted) (state, reason, version string, schema []Setting) {
func (m *Module) stateOf(a store.Installed) (state, reason, version string, schema []Setting) {
id := a.ID.String()
m.mu.RLock()
reason = m.failed[a.Name]
connector, running := m.running[a.Name]
engine, isEngine := m.engines[a.Name]
guard, isGuard := m.guards[a.Name]
server, isServer := m.servers[a.Name]
reason = m.failed[id]
connector, running := m.running[id]
engine, isEngine := m.engines[id]
guard, isGuard := m.guards[id]
server, isServer := m.servers[id]
m.mu.RUnlock()
switch {
@@ -154,27 +203,27 @@ func (m *Module) stateOf(a store.Accepted) (state, reason, version string, schem
return "stopped", "", "", nil
}
// schemaOf returns the settings schema of a package that is running now.
func (m *Module) schemaOf(name string) ([]Setting, bool) {
// schemaOf returns the settings schema of an installation that is running now.
func (m *Module) schemaOf(id string) ([]Setting, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
switch {
case m.running[name] != nil:
return m.running[name].SettingsSchema(), true
case m.engines[name] != nil:
return m.engines[name].SettingsSchema(), true
case m.guards[name] != nil:
return m.guards[name].SettingsSchema(), true
case m.servers[name] != nil:
return m.servers[name].SettingsSchema(), true
case m.running[id] != nil:
return m.running[id].SettingsSchema(), true
case m.engines[id] != nil:
return m.engines[id].SettingsSchema(), true
case m.guards[id] != nil:
return m.guards[id].SettingsSchema(), true
case m.servers[id] != nil:
return m.servers[id].SettingsSchema(), true
}
return nil, false
}
// checkAccepted checks an acceptance's settings against the schema the package
// declared, once it is known.
func (m *Module) checkAccepted(a store.Accepted) error {
schema, ok := m.schemaOf(a.Name)
// checkInstalled checks an installation's settings against the schema the
// package declared, once it is known.
func (m *Module) checkInstalled(a store.Installed) error {
schema, ok := m.schemaOf(a.ID.String())
if !ok || len(schema) == 0 {
return nil
}
+9 -5
View File
@@ -103,10 +103,11 @@ type mcpTool struct {
// Server is one accepted MCP server: the process or endpoint its acceptance
// names, and the declared subset of the tools that server offers.
type Server struct {
name string
spec ServerSpec
log *slog.Logger
procs *host.Host
name string
installation Installation
spec ServerSpec
log *slog.Logger
procs *host.Host
// dial connects, initialises a session and returns the release that ends
// it. It is a field so a test can speak to an in-memory server.
dial func(context.Context) (*sdk.ClientSession, func(), error)
@@ -129,6 +130,9 @@ func (h *Host) NewServer(spec ServerSpec) *Server {
return s
}
// Installation is the installation the server runs as.
func (s *Server) Installation() Installation { return s.installation }
// SettingsSchema names the environment settings the acceptance gave a stdio
// server. MCP has no configuration channel, so the keys are the declaration.
func (s *Server) SettingsSchema() []Setting {
@@ -148,7 +152,7 @@ func (s *Server) Declarations() []Declaration {
for _, name := range slices.Sorted(maps.Keys(s.tools)) {
t := s.tools[name]
out = append(out, Declaration{
Connector: s.name, Kind: t.kind, Name: name,
Connector: s.name, Installation: s.installation.ID, Kind: t.kind, Name: name,
Description: t.description, Schema: t.schema, ReadOnly: t.effect.ReadOnly, Privileged: t.effect.Privileged,
})
}
+31 -21
View File
@@ -13,6 +13,7 @@ import (
"slices"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
@@ -164,49 +165,56 @@ func (m *Module) acceptServer(ctx context.Context, in *mcpInput) (*httpapi.Reply
if err := req.check(); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
a, err := req.accepted(m.orgID, name)
a, err := req.accepted(name)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if err := m.store.Save(ctx, a, nil); err != nil {
if previous, found, err := m.instanceRow(ctx, name); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
} else if found {
a.ID, a.PackageID = previous.ID, previous.PackageID
}
if a, err = m.persistInstance(ctx)(ctx, a, nil); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
if _, err := m.refresh(ctx); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
if err := m.launch(context.WithoutCancel(ctx), a); err != nil {
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
if err := m.checkAccepted(a); err != nil {
_, _ = m.store.Delete(context.WithoutCancel(ctx), m.orgID, name)
m.release(name)
m.mu.Lock()
delete(m.failed, name)
m.mu.Unlock()
if err := m.checkInstalled(a); err != nil {
_, _ = m.store.DeleteInstallation(context.WithoutCancel(ctx), a.ID)
m.forget(a.ID.String())
_, _ = m.refresh(context.WithoutCancel(ctx))
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
return httpapi.OK(packageState{Name: name, State: "running"}), nil
}
// accepted is the row an acceptance stores.
func (r mcpRequest) accepted(orgID, name string) (store.Accepted, error) {
// accepted is the instance installation, and the package it installs, that an
// acceptance stores.
func (r mcpRequest) accepted(name string) (store.Installed, error) {
settings, err := json.Marshal(r.Settings, json.FormatNilMapAsNull(false))
if err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
slots, err := json.Marshal(r.Credentials, json.FormatNilMapAsNull(false))
if err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
tools, err := json.Marshal(r.Tools)
if err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
var effects jsontext.Value
if r.Effects != nil {
if effects, err = json.Marshal(r.Effects); err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
}
return store.Accepted{
OrgID: orgID, Name: name, Contract: store.ContractMCP,
return store.Installed{
ID: uuid.New(), Scope: store.ScopeInstance, Name: name, PackageName: name, Contract: store.ContractMCP,
Path: r.Path, SHA256: r.SHA256, URL: r.URL, Args: r.Args,
Env: r.Env, Egress: r.Egress, Settings: settings, Credentials: slots, Tools: tools, Effects: effects,
Enabled: true,
@@ -216,16 +224,18 @@ func (r mcpRequest) accepted(orgID, name string) (store.Accepted, error) {
// startServer runs one accepted MCP server. Its supervisor keeps it answering,
// reconnecting with backoff, until the module closes or the server is accepted
// again.
func (m *Module) startServer(ctx context.Context, a store.Accepted) error {
func (m *Module) startServer(ctx context.Context, a store.Installed) error {
id := a.ID.String()
spec, err := m.serverSpec(ctx, a)
if err != nil {
return m.fail(ctx, a.Name, err)
return m.fail(ctx, id, a.Name, err)
}
base, stop := context.WithCancel(context.WithoutCancel(ctx))
s := m.host.NewServer(spec)
s.installation = Installation{ID: a.ID, Scope: a.Scope}
m.mu.Lock()
m.servers[a.Name], m.stops[a.Name] = s, stop
delete(m.failed, a.Name)
m.servers[id], m.stops[id] = s, stop
delete(m.failed, id)
m.mu.Unlock()
go s.Supervise(base)
if err := s.Connect(ctx); err != nil {
@@ -237,7 +247,7 @@ func (m *Module) startServer(ctx context.Context, a store.Accepted) error {
}
// serverSpec is what a stored acceptance says a running server must be.
func (m *Module) serverSpec(ctx context.Context, a store.Accepted) (ServerSpec, error) {
func (m *Module) serverSpec(ctx context.Context, a store.Installed) (ServerSpec, error) {
spec := ServerSpec{
Name: a.Name, Path: a.Path, SHA256: a.SHA256, URL: a.URL,
Args: a.Args, Egress: a.Egress,
+3 -3
View File
@@ -71,7 +71,7 @@ func envName(slot, field string) string {
// a stdio server is launched with, or the headers an HTTP one is called with.
// Only the slots this acceptance names are read, so one server's credentials
// never reach another.
func (m *Module) mcpCredentials(ctx context.Context, a store.Accepted, httpTransport bool) ([]string, map[string]string, error) {
func (m *Module) mcpCredentials(ctx context.Context, a store.Installed, httpTransport bool) ([]string, map[string]string, error) {
slots, err := decodeSlots(a.Credentials)
if err != nil {
return nil, nil, err
@@ -80,7 +80,7 @@ func (m *Module) mcpCredentials(ctx context.Context, a store.Accepted, httpTrans
headers := map[string]string{}
for _, slot := range slices.Sorted(maps.Keys(slots)) {
name := slots[slot]
c, ok, err := m.store.Credential(ctx, m.orgID, name)
c, ok, err := m.credentialFor(ctx, scopeOf(a.Owner()), name)
if err != nil {
return nil, nil, err
}
@@ -93,7 +93,7 @@ func (m *Module) mcpCredentials(ctx context.Context, a store.Accepted, httpTrans
}
values := make(map[string]string, len(fields))
for field, f := range fields {
value, err := m.resolveField(ctx, a, f)
value, err := m.resolveField(ctx, a.Contract, a.Owner(), f)
if err != nil {
return nil, nil, fmt.Errorf("credential %q field %s: %w", name, field, err)
}
+329 -347
View File
@@ -9,7 +9,6 @@ import (
"fmt"
"log/slog"
"maps"
"net/http"
"regexp"
"slices"
"sort"
@@ -17,24 +16,22 @@ import (
"sync"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/connectors/internal/catalogue"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// validName is the shape of a connector name: it appears in logs and URLs.
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
// Module runs an organisation's accepted connectors, secret engines and guards,
// keeps the credentials they are configured with, and serves their
// administration.
// Module runs the installations of the accepted connectors, secret engines,
// guards and MCP servers, keeps the credentials they are configured with, and
// serves their administration. Every running extension is one installation,
// keyed by its ID; a name resolves to an installation for the scope that asks.
type Module struct {
orgID string
host *Host
store registry
sealer *seal.Sealer
@@ -45,25 +42,32 @@ type Module struct {
fetcher *catalogue.Fetcher
pkgMu sync.Mutex
mu sync.RWMutex
mu sync.RWMutex
idx index
// running, engines, guards and servers hold what each installation
// launched, keyed by installation ID. stops ends each MCP server's
// supervisor.
running map[string]*Connector
engines map[string]*Engine
guards map[string]*Guard
// servers are the accepted MCP servers, and stops ends each one's
// supervisor.
servers map[string]*Server
stops map[string]context.CancelFunc
failed map[string]string
// failedAt is when a name last failed to start, and contracts is what each
// launched name is. Both are read only for health, so an entry that outlives
// its failure does no harm.
failedAt map[string]time.Time
contracts map[string]string
// failedAt is when an installation last failed to start, and launched is
// what each launched installation is. Both are read only for health, so an
// entry that outlives its failure does no harm.
failedAt map[string]time.Time
launched map[string]launchedInfo
// recheck, when set, re-checks saved configuration against a connector's
// new declarations; an error refuses them.
recheck Recheck
}
// launchedInfo is what health says about an installation that was launched.
type launchedInfo struct {
name, contract, scope string
}
// Recheck re-checks saved configuration against the capabilities a connector
// now declares. An error refuses the new declarations.
type Recheck func(ctx context.Context, connector string, caps Capabilities) error
@@ -75,16 +79,35 @@ func (m *Module) Use(recheck Recheck) {
m.recheck = recheck
}
// installationStore is where installations, their overrides and the
// capabilities of the package they configure are kept.
type installationStore interface {
List(ctx context.Context) ([]store.Installed, error)
Overrides(ctx context.Context) ([]store.Override, error)
SaveInstallation(ctx context.Context, in store.Installed, capabilities jsontext.Value) (store.Installed, error)
SetCapabilities(ctx context.Context, packageID uuid.UUID, capabilities jsontext.Value) error
SetOverride(ctx context.Context, o store.Override, off bool, by string) error
DeleteInstallation(ctx context.Context, id uuid.UUID) (bool, error)
}
// packageStore is where the packages the instance accepted are kept.
type packageStore interface {
Packages(ctx context.Context) ([]store.Package, error)
SaveInstalled(ctx context.Context, in store.Installed, by string, capabilities jsontext.Value) (store.Installed, error)
DeletePackage(ctx context.Context, name string) (bool, error)
}
// 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
}
// registry is the module's persistence, so removal can be tested with a fake.
type registry interface {
List(ctx context.Context, orgID string) ([]store.Accepted, error)
Save(ctx context.Context, a store.Accepted, capabilities jsontext.Value) error
Delete(ctx context.Context, orgID, name string) (bool, error)
Credential(ctx context.Context, orgID, name string) (store.Credential, bool, error)
Credentials(ctx context.Context, orgID string) ([]store.Credential, error)
PutCredential(ctx context.Context, c store.Credential) error
SetCapabilities(ctx context.Context, orgID, name string, capabilities jsontext.Value) error
Capabilities(ctx context.Context, orgID, name string) (jsontext.Value, bool, error)
installationStore
packageStore
credentialStore
}
// Sealing is the age identity credentials are sealed with, and the backup
@@ -94,36 +117,54 @@ type Sealing struct {
Backups []string
}
// NewModule returns the connectors module for orgID.
// NewModule returns the connectors module.
//
// Artifacts fetched from the catalogue are kept under artifactDir.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealing Sealing, artifactDir string) (*Module, error) {
func NewModule(db *sqlx.DB, log *slog.Logger, sealing Sealing, artifactDir string) (*Module, error) {
sealer, err := seal.New(sealing.Identity, sealing.Backups)
if err != nil {
return nil, err
}
st := store.New(db)
return &Module{
orgID: orgID, host: NewHost(log), store: st, sealer: sealer, log: log,
host: NewHost(log), store: st, sealer: sealer, log: log,
sources: st, fetcher: catalogue.NewFetcher(artifactDir),
running: map[string]*Connector{}, engines: map[string]*Engine{}, guards: map[string]*Guard{}, failed: map[string]string{},
servers: map[string]*Server{}, stops: map[string]context.CancelFunc{},
}, nil
}
// Start launches every accepted secret engine, then every accepted connector,
// refresh reads every installation and override, rebuilds the index that
// resolves names, and returns the installations.
func (m *Module) refresh(ctx context.Context) ([]store.Installed, error) {
installed, err := m.store.List(ctx)
if err != nil {
return nil, err
}
overrides, err := m.store.Overrides(ctx)
if err != nil {
return nil, err
}
ix := newIndex(installed, overrides)
m.mu.Lock()
m.idx = ix
m.mu.Unlock()
return installed, nil
}
// Start launches every enabled secret engine, then every enabled connector,
// since a connector's credentials may be resolved through an engine. One that
// fails to start is reported by Ready and logged; the others still run.
//
// Its only error is the read of the accepted connectors, which happens before
// Its only error is the read of the installations, which happens before
// anything launches, so a caller may call Start again after a failure without
// launching anything twice.
func (m *Module) Start(ctx context.Context) error {
accepted, err := m.store.List(ctx, m.orgID)
installed, err := m.refresh(ctx)
if err != nil {
return err
}
for _, a := range ordered(accepted) {
for _, a := range ordered(installed) {
// A failure is recorded for Ready and logged; the rest still start.
_ = m.launch(ctx, a)
}
@@ -132,15 +173,15 @@ func (m *Module) Start(ctx context.Context) error {
// ordered starts secret engines first, then connectors, then MCP servers: a
// credential may be resolved through an engine.
func ordered(accepted []store.Accepted) []store.Accepted {
out := slices.Clone(accepted)
slices.SortStableFunc(out, func(a, b store.Accepted) int {
func ordered(installed []store.Installed) []store.Installed {
out := slices.Clone(installed)
slices.SortStableFunc(out, func(a, b store.Installed) int {
return cmp.Compare(rank(a), rank(b))
})
return out
}
func rank(a store.Accepted) int {
func rank(a store.Installed) int {
switch a.Contract {
case store.ContractSecretEngine:
return 0
@@ -150,38 +191,70 @@ func rank(a store.Accepted) int {
return 1
}
// Get returns the running connector named name. An MCP server is reached
// through Tool, since it answers lookups and actions rather than events.
func (m *Module) Get(name string) (*Connector, bool) {
// resolve finds the running installation ref names for the scope ctx acts for.
func (m *Module) resolve(ctx context.Context, ref string) (member, bool) {
s := ScopeFromContext(ctx)
m.mu.RLock()
defer m.mu.RUnlock()
c, ok := m.running[name]
return m.idx.resolve(s, ref)
}
// visible lists the installations each name resolves to for the scope ctx acts
// for.
func (m *Module) visible(ctx context.Context) []member {
s := ScopeFromContext(ctx)
m.mu.RLock()
defer m.mu.RUnlock()
return m.idx.visible(s)
}
// Get returns the running connector ref names for the caller: an installation
// ID, or a name that resolves to the person's installation, then the
// organisation's, then the instance's. An MCP server is reached through Tool,
// since it answers lookups and actions rather than events.
func (m *Module) Get(ctx context.Context, ref string) (*Connector, bool) {
mem, ok := m.resolve(ctx, ref)
if !ok {
return nil, false
}
m.mu.RLock()
defer m.mu.RUnlock()
c, ok := m.running[mem.id]
return c, ok
}
// Tool returns the connector or MCP server that declared name.
func (m *Module) Tool(name string) (Tool, bool) {
// Tool returns the connector or MCP server ref names for the caller.
func (m *Module) Tool(ctx context.Context, ref string) (Tool, bool) {
mem, ok := m.resolve(ctx, ref)
if !ok {
return nil, false
}
return m.Installed(mem.id)
}
// Installed returns the connector or MCP server running as installation id,
// whoever asks. A decision records the installation it resolved, and executing
// that decision runs there, whatever scope the approver acts for.
func (m *Module) Installed(id string) (Tool, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
if c, ok := m.running[name]; ok {
if c, ok := m.running[id]; ok {
return c, true
}
s, ok := m.servers[name]
s, ok := m.servers[id]
return s, ok
}
// TargetFacts asks every running connector that serves target facts what it
// knows about t, now, and keeps nothing. Connectors are asked in name order and
// the first to supply a fact wins it.
// TargetFacts asks every connector the caller can use that serves target facts
// what it knows about t, now, and keeps nothing. Connectors are asked in name
// order and the first to supply a fact wins it.
func (m *Module) TargetFacts(ctx context.Context, t Target) (TargetFacts, error) {
m.mu.RLock()
asked := make([]*Connector, 0, len(m.running))
for _, name := range slices.Sorted(maps.Keys(m.running)) {
if c := m.running[name]; c.facts {
var asked []*Connector
for _, c := range m.connectorsFor(ctx) {
if c.facts {
asked = append(asked, c)
}
}
m.mu.RUnlock()
var out TargetFacts
for _, c := range asked {
got, err := c.TargetFacts(ctx, t)
@@ -195,40 +268,53 @@ func (m *Module) TargetFacts(ctx context.Context, t Target) (TargetFacts, error)
return out, nil
}
// Guards lists the running guard extensions in name order.
func (m *Module) Guards() []*Guard {
m.mu.RLock()
defer m.mu.RUnlock()
var out []*Guard
for _, name := range slices.Sorted(maps.Keys(m.guards)) {
out = append(out, m.guards[name])
}
return out
}
// Delivering lists the running connectors that send the named delivery, in
// name order: the channels a message goes out on.
func (m *Module) Delivering(delivery string) []*Connector {
// connectorsFor lists the running connectors the caller can use, in name order.
func (m *Module) connectorsFor(ctx context.Context) []*Connector {
visible := m.visible(ctx)
m.mu.RLock()
defer m.mu.RUnlock()
var out []*Connector
for _, name := range slices.Sorted(maps.Keys(m.running)) {
if c := m.running[name]; c.Delivers(delivery) {
for _, mem := range visible {
if c, ok := m.running[mem.id]; ok {
out = append(out, c)
}
}
return out
}
// LinkableChannels lists the running connectors that can link a person's
// channel identity to their account, in name order.
func (m *Module) LinkableChannels(context.Context) ([]string, error) {
// Guards lists the running guard extensions the caller can use, in name order.
func (m *Module) Guards(ctx context.Context) []*Guard {
visible := m.visible(ctx)
m.mu.RLock()
defer m.mu.RUnlock()
var out []*Guard
for _, mem := range visible {
if g, ok := m.guards[mem.id]; ok {
out = append(out, g)
}
}
return out
}
// Delivering lists the running connectors the caller can use that send the
// named delivery, in name order: the channels a message goes out on.
func (m *Module) Delivering(ctx context.Context, delivery string) []*Connector {
var out []*Connector
for _, c := range m.connectorsFor(ctx) {
if c.Delivers(delivery) {
out = append(out, c)
}
}
return out
}
// LinkableChannels lists the running connectors the caller can use that can
// link a person's channel identity to their account, in name order.
func (m *Module) LinkableChannels(ctx context.Context) ([]string, error) {
var out []string
for _, name := range slices.Sorted(maps.Keys(m.running)) {
if m.running[name].LinksAccounts() {
out = append(out, name)
for _, c := range m.connectorsFor(ctx) {
if c.LinksAccounts() {
out = append(out, c.Name())
}
}
return out, nil
@@ -236,56 +322,66 @@ func (m *Module) LinkableChannels(context.Context) ([]string, error) {
// LinkURL asks the running connector for the URL that delivers a link code.
func (m *Module) LinkURL(ctx context.Context, connector, code string) (string, error) {
c, ok := m.Get(connector)
c, ok := m.Get(ctx, connector)
if !ok {
return "", fmt.Errorf("connector %q isn't running", connector)
}
return c.LinkURL(ctx, code)
}
// Declarations lists every running connector's lookups and actions and every
// MCP server's declared tools, ordered by name and then by tool name.
func (m *Module) Declarations() []Declaration {
// Declarations lists every lookup and action of the connectors the caller can
// use and every tool of the MCP servers it can use, ordered by name and then by
// tool name.
func (m *Module) Declarations(ctx context.Context) []Declaration {
visible := m.visible(ctx)
m.mu.RLock()
defer m.mu.RUnlock()
var out []Declaration
for _, name := range slices.Sorted(maps.Keys(m.running)) {
out = append(out, m.running[name].Declarations()...)
}
for _, name := range slices.Sorted(maps.Keys(m.servers)) {
out = append(out, m.servers[name].Declarations()...)
for _, mem := range visible {
if c, ok := m.running[mem.id]; ok {
out = append(out, c.Declarations()...)
}
if s, ok := m.servers[mem.id]; ok {
out = append(out, s.Declarations()...)
}
}
return out
}
// label names an installation in a problem report.
func (m *Module) label(id string) string {
info, ok := m.launched[id]
switch {
case !ok:
return id
case info.scope == store.ScopeInstance:
return info.name
}
return info.name + " (" + info.scope + ")"
}
// Ready reports an extension that failed to start or whose process has exited,
// and an MCP server that doesn't answer.
func (m *Module) Ready(context.Context) error {
m.mu.RLock()
var problems []string
for name, reason := range m.failed {
problems = append(problems, name+": "+reason)
for id, reason := range m.failed {
problems = append(problems, m.label(id)+": "+reason)
}
for name := range m.running {
if !m.host.Alive(name) {
problems = append(problems, name+": process exited")
}
}
for name := range m.engines {
if !m.host.Alive(name) {
problems = append(problems, name+": process exited")
}
}
for name := range m.guards {
if !m.host.Alive(name) {
problems = append(problems, name+": process exited")
for _, id := range slices.Concat(slices.Collect(maps.Keys(m.running)), slices.Collect(maps.Keys(m.engines)), slices.Collect(maps.Keys(m.guards))) {
if !m.host.Alive(id) {
problems = append(problems, m.label(id)+": process exited")
}
}
servers := maps.Clone(m.servers)
labels := make(map[string]string, len(servers))
for id := range servers {
labels[id] = m.label(id)
}
m.mu.RUnlock()
for _, name := range slices.Sorted(maps.Keys(servers)) {
if err := servers[name].Ready(); err != nil {
problems = append(problems, name+": "+err.Error())
for _, id := range slices.Sorted(maps.Keys(servers)) {
if err := servers[id].Ready(); err != nil {
problems = append(problems, labels[id]+": "+err.Error())
}
}
if len(problems) == 0 {
@@ -310,154 +406,9 @@ func (m *Module) Close() {
m.host.Close()
}
// extensionKinds lists the API path and names for each kind of accepted
// package. The group comes from the contract's entry in store.Contracts.
func extensionKinds() []extensionKind {
return []extensionKind{
{store.ContractConnector, "/api/connectors", "connector", "connector", "connectors", "Connectors"},
{store.ContractSecretEngine, "/api/secret-engines", "secret-engine", "secret engine", "secret engines", "Secret engines"},
{store.ContractGuard, "/api/guards", "guard", "guard", "guards", "Guards"},
{store.ContractMCP, "/api/mcp-servers", "mcp-server", "MCP server", "MCP servers", "MCP servers"},
}
}
type extensionKind struct {
contract, path, noun, singular, plural, tag string
}
// ExtensionKind is one kind of accepted package and the group it belongs to.
type ExtensionKind struct {
Kind string `json:"kind" doc:"The API path segment that lists this kind"`
Label string `json:"label"`
Singular string `json:"singular"`
Group string `json:"group" enum:"platform,integration,agent"`
}
func listExtensionKinds(context.Context, *struct{}) (*httpapi.Reply[[]ExtensionKind], error) {
kinds := extensionKinds()
out := make([]ExtensionKind, 0, len(kinds))
for _, k := range kinds {
out = append(out, ExtensionKind{
Kind: strings.TrimPrefix(k.path, "/api/"), Label: k.tag, Singular: k.singular,
Group: string(store.GroupOf(k.contract)),
})
}
return httpapi.OK(out), nil
}
// Register adds the API for accepted packages and credentials.
func (m *Module) Register(api huma.API) {
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindConnector), huma.Operation{
OperationID: "list-extension-kinds", Method: http.MethodGet, Path: "/api/extension-kinds",
Summary: "List the kinds of extension and the group each belongs to", Tags: []string{"Connectors"},
}, listExtensionKinds)
for _, k := range extensionKinds() {
tags := []string{k.tag}
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindConnector), huma.Operation{
OperationID: "list-" + k.noun + "s", Method: http.MethodGet, Path: k.path,
Summary: "List accepted " + k.plural, Tags: tags,
}, m.list(k.contract))
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{
OperationID: "remove-" + k.noun, Method: http.MethodDelete, Path: k.path + "/{name}",
Summary: "Remove an accepted package", Tags: tags,
}, m.remove(k.contract))
if k.contract == store.ContractMCP {
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindMCPServer), huma.Operation{
OperationID: "accept-mcp-server", Method: http.MethodPut, Path: k.path + "/{name}",
Summary: "Accept an MCP server and the tools it may offer", Tags: tags,
}, m.acceptServer)
continue
}
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindConnector), huma.Operation{
OperationID: "accept-" + k.noun, Method: http.MethodPut, Path: k.path + "/{name}",
Summary: "Accept a package and start it", Tags: tags,
}, m.accept(k.contract))
}
tags := []string{"Credentials"}
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindSecret), huma.Operation{
OperationID: "list-credentials", Method: http.MethodGet, Path: "/api/credentials",
Summary: "List credentials, never their values", Tags: tags,
}, m.listCredentials)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindSecret), huma.Operation{
OperationID: "get-credential", Method: http.MethodGet, Path: "/api/credentials/{name}",
Summary: "Get a credential, never its values", Tags: tags,
}, m.getCredential)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSecret), huma.Operation{
OperationID: "put-credential", Method: http.MethodPut, Path: "/api/credentials/{name}",
Summary: "Store a credential sealed and restart what uses it", Tags: tags,
}, m.putCredential)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindSecret), huma.Operation{
OperationID: "list-credential-kinds", Method: http.MethodGet, Path: "/api/credential-kinds",
Summary: "List credential kinds and the fields each takes", Tags: tags,
}, listCredentialKinds)
m.registerCatalogue(api)
m.registerExtensions(api)
}
type acceptRequest struct {
Path string `json:"path" doc:"The extension binary on the host"`
SHA256 string `json:"sha256" doc:"The binary's digest; it runs only while the digest matches"`
Egress []string `json:"egress,omitzero" doc:"Every host the extension may reach"`
Env []string `json:"env,omitzero" doc:"Host environment variables the extension may see"`
Settings map[string]string `json:"settings,omitzero"`
// Credentials maps each credential slot the package declares to a
// credential by name.
Credentials map[string]string `json:"credentials,omitzero"`
}
func (m *Module) accept(contract string) func(context.Context, *packageInput) (*httpapi.Reply[packageState], error) {
return func(ctx context.Context, in *packageInput) (*httpapi.Reply[packageState], error) {
return m.acceptAs(ctx, in, contract)
}
}
type packageInput struct {
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
Body acceptRequest
}
type nameInput struct {
Name string `path:"name"`
}
// packageState is an accepted package's name and state after a change.
type packageState struct {
Name string `json:"name"`
State string `json:"state" enum:"running,removed"`
}
func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string) (*httpapi.Reply[packageState], error) {
name, req := in.Name, in.Body
if !validName.MatchString(name) || req.Path == "" || req.SHA256 == "" {
return nil, huma.NewError(http.StatusBadRequest, "a connector needs a lowercase name, a path and a sha256")
}
settings, err := json.Marshal(req.Settings)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
slots, err := json.Marshal(req.Credentials, json.FormatNilMapAsNull(false))
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
a := store.Accepted{
OrgID: m.orgID, Name: name, Path: req.Path, SHA256: req.SHA256,
Egress: req.Egress, Env: req.Env, Settings: settings, Contract: contract, Credentials: slots,
// Only an MCP server declares its tools at acceptance; the column
// holds a list either way.
Tools: jsontext.Value(`[]`), Enabled: true,
}
previous, found, err := m.acceptedRow(ctx, name)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
}
if found && len(previous.Package) > 0 {
return nil, huma.NewError(http.StatusConflict, name+" is installed from the catalogue; change it through its extension page")
}
if err := m.commit(context.WithoutCancel(ctx), a, found, previous); err != nil {
return nil, acceptError(err)
}
return httpapi.OK(packageState{Name: name, State: "running"}), nil
}
// persistFunc stores a launched installation and the declarations its package
// made.
type persistFunc func(ctx context.Context, in store.Installed, capabilities jsontext.Value) (store.Installed, error)
// persistError marks a failure to store an acceptance, as distinct from a
// refusal.
@@ -466,23 +417,15 @@ type persistError struct{ err error }
func (e persistError) Error() string { return e.err.Error() }
func (e persistError) Unwrap() error { return e.err }
// acceptError maps an error returned by commit to an HTTP error.
func acceptError(err error) error {
if errors.As(err, new(persistError)) {
return huma.NewError(http.StatusInternalServerError, err.Error())
}
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
// commit starts next and stores it only once it has started and its
// declarations and settings are accepted. The acceptance and the connector's
// declarations and settings are accepted. The installation and the connector's
// declarations are written in one transaction, after every check, so a
// refusal changes nothing that is stored. The extension that previously ran
// under the name is restarted from its stored row.
func (m *Module) commit(ctx context.Context, next store.Accepted, hadPrevious bool, previous store.Accepted) error {
// as the installation is restarted from its stored row.
func (m *Module) commit(ctx context.Context, next store.Installed, hadPrevious bool, previous store.Installed, persist persistFunc) error {
saved := false
save := func(ctx context.Context, caps jsontext.Value) error {
if err := m.store.Save(ctx, next, caps); err != nil {
if _, err := persist(ctx, next, caps); err != nil {
return persistError{err}
}
saved = true
@@ -492,17 +435,20 @@ func (m *Module) commit(ctx context.Context, next store.Accepted, hadPrevious bo
// A connector validates its settings against its declared schema before
// saving. Other contracts are checked after they start.
if err == nil && !saved && next.Enabled && next.Contract != store.ContractConnector {
err = m.checkAccepted(next)
err = m.checkInstalled(next)
}
if err == nil && !saved {
err = save(ctx, nil)
}
if err == nil {
if _, rerr := m.refresh(ctx); rerr != nil {
return persistError{rerr}
}
return nil
}
m.release(next.Name)
m.release(next.ID.String())
m.mu.Lock()
delete(m.failed, next.Name)
delete(m.failed, next.ID.String())
m.mu.Unlock()
if hadPrevious {
_ = m.launch(ctx, previous)
@@ -510,56 +456,43 @@ func (m *Module) commit(ctx context.Context, next store.Accepted, hadPrevious bo
return err
}
// launch starts or restarts one accepted package and records the outcome. A
// name runs one package: whatever ran under it before is stopped first, so a
// connector, a secret engine and an MCP server never share a name.
func (m *Module) launch(ctx context.Context, a store.Accepted) error {
// launch starts or restarts one installation and records the outcome. An
// installation runs as one extension: whatever ran as it before is stopped
// first.
func (m *Module) launch(ctx context.Context, a store.Installed) error {
return m.launchWith(ctx, a, nil)
}
// launchWith launches an acceptance that is not stored yet. When save is
// launchWith launches an installation that is not stored yet. When save is
// set, a connector calls it with its declarations once they and its settings
// are accepted, and is registered only if it succeeds; the other contracts
// leave saving to the caller. Without save, the row is already stored and only
// the declarations are recorded.
func (m *Module) launchWith(ctx context.Context, a store.Accepted, save func(context.Context, jsontext.Value) error) error {
m.releaseAs(a.Name, a.Contract)
func (m *Module) launchWith(ctx context.Context, a store.Installed, save func(context.Context, jsontext.Value) error) error {
id := a.ID.String()
m.releaseAs(a)
if !a.Enabled {
m.markStopped(a.Name)
m.markStopped(id)
return nil
}
if a.Contract == store.ContractMCP {
return m.startServer(ctx, a)
}
var settings map[string]string
if len(a.Settings) > 0 {
if err := json.Unmarshal(a.Settings, &settings); err != nil {
return m.fail(ctx, a.Name, fmt.Errorf("settings: %w", err))
}
}
settings, secretSettings, err := m.splitSecretSettings(ctx, a, settings)
spec, err := m.processSpec(ctx, a)
if err != nil {
return m.fail(ctx, a.Name, err)
}
secrets, err := m.secrets(ctx, a)
if err != nil {
return m.fail(ctx, a.Name, err)
}
maps.Copy(secrets, secretSettings)
spec := Spec{
Name: a.Name, Path: a.Path, SHA256: a.SHA256,
Env: a.Env, Egress: a.Egress, Settings: settings, Secrets: secrets,
return m.fail(ctx, id, a.Name, err)
}
inst := Installation{ID: a.ID, Scope: a.Scope}
if a.Contract == store.ContractSecretEngine {
e, err := m.host.StartEngine(ctx, spec)
if err != nil {
return m.fail(ctx, a.Name, err)
return m.fail(ctx, id, a.Name, err)
}
m.mu.Lock()
m.engines[a.Name] = e
delete(m.failed, a.Name)
m.engines[id] = e
delete(m.failed, id)
m.mu.Unlock()
m.log.InfoContext(ctx, "secret engine started", "engine", a.Name)
m.log.InfoContext(ctx, "secret engine started", "engine", a.Name, "installation", id, "scope", a.Scope)
return nil
}
if a.Contract == store.ContractGuard {
@@ -567,41 +500,68 @@ func (m *Module) launchWith(ctx context.Context, a store.Accepted, save func(con
}
c, err := m.host.Start(ctx, spec)
if err != nil {
return m.fail(ctx, a.Name, err)
return m.fail(ctx, id, a.Name, err)
}
c.installation = inst
if err := m.checkDeclarations(ctx, a.Name, c.Capabilities()); err != nil {
m.host.Stop(a.Name)
return m.fail(ctx, a.Name, err)
m.host.Stop(id)
return m.fail(ctx, id, a.Name, err)
}
if save != nil {
if err := checkSettingValues(c.SettingsSchema(), a.Settings); err != nil {
m.host.Stop(a.Name)
return m.fail(ctx, a.Name, err)
m.host.Stop(id)
return m.fail(ctx, id, a.Name, err)
}
}
if err := m.storeCapabilities(ctx, c, save); err != nil {
m.host.Stop(a.Name)
return m.fail(ctx, a.Name, err)
if err := m.storeCapabilities(ctx, a, c, save); err != nil {
m.host.Stop(id)
return m.fail(ctx, id, a.Name, err)
}
m.mu.Lock()
m.running[a.Name] = c
delete(m.failed, a.Name)
m.running[id] = c
delete(m.failed, id)
m.mu.Unlock()
m.log.InfoContext(ctx, "connector started", "connector", a.Name)
m.log.InfoContext(ctx, "connector started", "connector", a.Name, "installation", id, "scope", a.Scope)
return nil
}
// processSpec is what a connector, guard or secret engine runs with: its
// settings with secret references resolved, and the secrets its credential
// slots name.
func (m *Module) processSpec(ctx context.Context, a store.Installed) (Spec, error) {
var settings map[string]string
if len(a.Settings) > 0 {
if err := json.Unmarshal(a.Settings, &settings); err != nil {
return Spec{}, fmt.Errorf("settings: %w", err)
}
}
settings, secretSettings, err := m.splitSecretSettings(ctx, a, settings)
if err != nil {
return Spec{}, err
}
secrets, err := m.secrets(ctx, a)
if err != nil {
return Spec{}, err
}
maps.Copy(secrets, secretSettings)
return Spec{
Name: a.Name, Key: a.ID.String(), Path: a.Path, SHA256: a.SHA256,
Env: a.Env, Egress: a.Egress, Settings: settings, Secrets: secrets,
}, nil
}
// startGuard launches a guard and records it as running.
func (m *Module) startGuard(ctx context.Context, a store.Accepted, spec Spec) error {
func (m *Module) startGuard(ctx context.Context, a store.Installed, spec Spec) error {
id := a.ID.String()
g, err := m.host.StartGuard(ctx, spec)
if err != nil {
return m.fail(ctx, a.Name, err)
return m.fail(ctx, id, a.Name, err)
}
m.mu.Lock()
m.guards[a.Name] = g
delete(m.failed, a.Name)
m.guards[id] = g
delete(m.failed, id)
m.mu.Unlock()
m.log.InfoContext(ctx, "guard started", "guard", a.Name)
m.log.InfoContext(ctx, "guard started", "guard", a.Name, "installation", id, "scope", a.Scope)
return nil
}
@@ -626,7 +586,7 @@ func (m *Module) checkDeclarations(ctx context.Context, name string, caps Capabi
// storeCapabilities records what a connector declared, so workflows and
// triggers can be checked against it while the connector is stopped.
func (m *Module) storeCapabilities(ctx context.Context, c *Connector, save func(context.Context, jsontext.Value) error) error {
func (m *Module) storeCapabilities(ctx context.Context, a store.Installed, c *Connector, save func(context.Context, jsontext.Value) error) error {
raw, err := json.Marshal(c.Capabilities())
if err != nil {
return fmt.Errorf("encode capabilities: %w", err)
@@ -634,7 +594,7 @@ func (m *Module) storeCapabilities(ctx context.Context, c *Connector, save func(
if save != nil {
return save(ctx, raw)
}
return m.store.SetCapabilities(ctx, m.orgID, c.Name(), raw)
return m.store.SetCapabilities(ctx, a.PackageID, raw)
}
// refSuffix marks a setting that names a secret rather than holding one. The
@@ -642,11 +602,24 @@ func (m *Module) storeCapabilities(ctx context.Context, c *Connector, save func(
// reference.
const refSuffix = "_ref"
// splitSecretSettings separates a package's secret settings from the rest,
// resolves each reference, and returns the plain settings and the secrets the
// extension is configured with. A secret engine's own settings must hold
// their values: an engine never waits on another engine.
func (m *Module) splitSecretSettings(ctx context.Context, a store.Accepted, settings map[string]string) (map[string]string, map[string]string, error) {
// engineAt returns the running secret engine name resolves to for what o
// owns: the engine of the same person or organisation, then the instance's.
func (m *Module) engineAt(o store.Owner, name string) (*Engine, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
mem, ok := m.idx.resolve(scopeOf(o), name)
if !ok || mem.contract != store.ContractSecretEngine {
return nil, false
}
e, ok := m.engines[mem.id]
return e, ok
}
// splitSecretSettings separates an installation's secret settings from the
// rest, resolves each reference, and returns the plain settings and the
// secrets the extension is configured with. A secret engine's own settings
// must hold their values: an engine never waits on another engine.
func (m *Module) splitSecretSettings(ctx context.Context, a store.Installed, settings map[string]string) (map[string]string, map[string]string, error) {
plain := make(map[string]string, len(settings))
secrets := map[string]string{}
for key, value := range settings {
@@ -662,9 +635,7 @@ func (m *Module) splitSecretSettings(ctx context.Context, a store.Accepted, sett
if !ok || engineName == "" || ref == "" {
return nil, nil, fmt.Errorf("setting %q wants engine:key", key)
}
m.mu.RLock()
engine, running := m.engines[engineName]
m.mu.RUnlock()
engine, running := m.engineAt(a.Owner(), engineName)
if !running {
return nil, nil, fmt.Errorf("setting %q: secret engine %q isn't running", key, engineName)
}
@@ -677,22 +648,21 @@ func (m *Module) splitSecretSettings(ctx context.Context, a store.Accepted, sett
return plain, secrets, nil
}
// release stops whatever ran under name, so one accepted package is what a
// name runs.
func (m *Module) release(name string) {
// release stops whatever ran as installation id.
func (m *Module) release(id string) {
m.mu.Lock()
_, running := m.running[name]
_, engine := m.engines[name]
_, guard := m.guards[name]
s, stop := m.servers[name], m.stops[name]
delete(m.running, name)
delete(m.engines, name)
delete(m.guards, name)
delete(m.servers, name)
delete(m.stops, name)
_, running := m.running[id]
_, engine := m.engines[id]
_, guard := m.guards[id]
s, stop := m.servers[id], m.stops[id]
delete(m.running, id)
delete(m.engines, id)
delete(m.guards, id)
delete(m.servers, id)
delete(m.stops, id)
m.mu.Unlock()
if running || engine || guard {
m.host.Stop(name)
m.host.Stop(id)
}
if stop != nil {
stop()
@@ -702,35 +672,47 @@ func (m *Module) release(name string) {
}
}
// releaseAs stops whatever ran under name and records what it is about to be.
func (m *Module) releaseAs(name, contract string) {
m.release(name)
// releaseAs stops whatever ran as a's installation and records what it is
// about to be.
func (m *Module) releaseAs(a store.Installed) {
id := a.ID.String()
m.release(id)
m.mu.Lock()
defer m.mu.Unlock()
if m.contracts == nil {
m.contracts = map[string]string{}
if m.launched == nil {
m.launched = map[string]launchedInfo{}
}
m.contracts[name] = contract
m.launched[id] = launchedInfo{name: a.Name, contract: a.Contract, scope: a.Scope}
}
// markStopped forgets a name's failure now that it is not meant to run.
func (m *Module) markStopped(name string) {
// forget drops what the module knows of a removed installation.
func (m *Module) forget(id string) {
m.release(id)
m.mu.Lock()
defer m.mu.Unlock()
delete(m.failed, name)
delete(m.failed, id)
delete(m.failedAt, id)
delete(m.launched, id)
}
func (m *Module) fail(ctx context.Context, name string, err error) error {
// markStopped forgets an installation's failure now that it is not meant to run.
func (m *Module) markStopped(id string) {
m.mu.Lock()
delete(m.running, name)
delete(m.engines, name)
delete(m.guards, name)
m.failed[name] = err.Error()
defer m.mu.Unlock()
delete(m.failed, id)
}
func (m *Module) fail(ctx context.Context, id, name string, err error) error {
m.mu.Lock()
delete(m.running, id)
delete(m.engines, id)
delete(m.guards, id)
m.failed[id] = err.Error()
if m.failedAt == nil {
m.failedAt = map[string]time.Time{}
}
m.failedAt[name] = time.Now()
m.failedAt[id] = time.Now()
m.mu.Unlock()
m.log.ErrorContext(ctx, "extension failed to start", "extension", name, "error", err)
m.log.ErrorContext(ctx, "extension failed to start", "extension", name, "installation", id, "error", err)
return err
}
+94 -50
View File
@@ -3,6 +3,7 @@ package connectors
import (
"bytes"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
@@ -12,10 +13,12 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/connectors/internal/catalogue"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// packageRecord is the lifecycle of an extension installed from the catalogue,
@@ -28,11 +31,11 @@ type packageRecord struct {
// packageOf reads a row's lifecycle; ok is false for a package accepted by
// path.
func packageOf(a store.Accepted) (rec packageRecord, ok bool, err error) {
if len(a.Package) == 0 {
func packageOf(a store.Installed) (rec packageRecord, ok bool, err error) {
if len(a.Manifest) == 0 {
return packageRecord{}, false, nil
}
if err := json.Unmarshal(a.Package, &rec); err != nil {
if err := json.Unmarshal(a.Manifest, &rec); err != nil {
return packageRecord{}, false, fmt.Errorf("package %q: %w", a.Name, err)
}
return rec, true, nil
@@ -41,14 +44,14 @@ func packageOf(a store.Accepted) (rec packageRecord, ok bool, err error) {
// rowOf derives the row a lifecycle stores: the live pin is what runs and the
// accepted grants are what it runs with. Nothing is enabled before an
// operator has accepted grants, and a slot the grants don't name is dropped.
func rowOf(base store.Accepted, rec packageRecord, enabled bool) (store.Accepted, error) {
func rowOf(base store.Installed, rec packageRecord, enabled bool) (store.Installed, error) {
raw, err := json.Marshal(rec)
if err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
slots, err := decodeSlots(base.Credentials)
if err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
granted := catalogue.Grants{}
if g := rec.State.Accepted; g != nil {
@@ -57,54 +60,63 @@ func rowOf(base store.Accepted, rec packageRecord, enabled bool) (store.Accepted
maps.DeleteFunc(slots, func(slot, _ string) bool { return !slices.Contains(granted.Credentials, slot) })
base.Credentials, err = json.Marshal(slots, json.FormatNilMapAsNull(false))
if err != nil {
return store.Accepted{}, err
return store.Installed{}, err
}
base.Path, base.SHA256 = rec.State.Current.Path, rec.State.Current.Digest
base.Egress, base.Env = granted.Egress, granted.Env
base.Package = raw
base.Manifest = raw
base.Enabled = enabled && rec.State.Accepted != nil
return base, nil
}
// restarts reports whether a change to the row needs the process restarted.
func restarts(old, next store.Accepted) bool {
func restarts(old, next store.Installed) bool {
return old.Path != next.Path || old.SHA256 != next.SHA256 || old.Enabled != next.Enabled ||
!slices.Equal(old.Egress, next.Egress) || !slices.Equal(old.Env, next.Env) ||
!bytes.Equal(old.Credentials, next.Credentials) || !bytes.Equal(old.Settings, next.Settings)
}
// acceptedRow returns the stored acceptance of name; ok is false when there is
// none.
func (m *Module) acceptedRow(ctx context.Context, name string) (a store.Accepted, ok bool, err error) {
accepted, err := m.store.List(ctx, m.orgID)
// instanceRow returns the instance installation of name; ok is false when
// there is none.
func (m *Module) instanceRow(ctx context.Context, name string) (a store.Installed, ok bool, err error) {
installed, err := m.store.List(ctx)
if err != nil {
return store.Accepted{}, false, err
return store.Installed{}, false, err
}
i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == name })
i := slices.IndexFunc(installed, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == name })
if i < 0 {
return store.Accepted{}, false, nil
return store.Installed{}, false, nil
}
return installed[i], true, nil
}
// persistInstance stores an instance installation together with its package,
// accepted by the caller.
func (m *Module) persistInstance(ctx context.Context) persistFunc {
by := governance.CallerID(ctx)
return func(ctx context.Context, in store.Installed, caps jsontext.Value) (store.Installed, error) {
return m.store.SaveInstalled(ctx, in, by, caps)
}
return accepted[i], true, nil
}
var errNotManaged = errors.New("not installed from the catalogue")
// find returns the installed package name.
func (m *Module) find(ctx context.Context, name string) (store.Accepted, packageRecord, error) {
accepted, err := m.store.List(ctx, m.orgID)
func (m *Module) find(ctx context.Context, name string) (store.Installed, packageRecord, error) {
accepted, err := m.store.List(ctx)
if err != nil {
return store.Accepted{}, packageRecord{}, err
return store.Installed{}, packageRecord{}, err
}
i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == name })
i := slices.IndexFunc(accepted, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == name })
if i < 0 {
return store.Accepted{}, packageRecord{}, fmt.Errorf("no extension named %s: %w", name, errNotManaged)
return store.Installed{}, packageRecord{}, fmt.Errorf("no extension named %s: %w", name, errNotManaged)
}
rec, ok, err := packageOf(accepted[i])
if err != nil {
return store.Accepted{}, packageRecord{}, err
return store.Installed{}, packageRecord{}, err
}
if !ok {
return store.Accepted{}, packageRecord{}, fmt.Errorf("%s is accepted by path: %w", name, errNotManaged)
return store.Installed{}, packageRecord{}, fmt.Errorf("%s is accepted by path: %w", name, errNotManaged)
}
return accepted[i], rec, nil
}
@@ -133,19 +145,43 @@ func (m *Module) lifecycleError(ctx context.Context, err error) error {
// replace stores next and restarts what changed. next is stored only once it
// has started and its settings are accepted, so a refused change leaves the
// extension, its stored settings and its declarations as they were.
func (m *Module) replace(ctx context.Context, old, next store.Accepted) error {
func (m *Module) replace(ctx context.Context, old, next store.Installed) error {
persist := m.persistInstance(ctx)
if !restarts(old, next) {
return m.store.Save(ctx, next, nil)
if _, err := persist(ctx, next, nil); err != nil {
return err
}
_, err := m.refresh(ctx)
return err
}
if err := m.commit(context.WithoutCancel(ctx), next, true, old); err != nil {
if err := m.commit(context.WithoutCancel(ctx), next, true, old, persist); err != nil {
if errors.As(err, new(persistError)) {
return err
}
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
if old.Path != next.Path || old.SHA256 != next.SHA256 {
m.relaunchPackage(context.WithoutCancel(ctx), next)
}
return nil
}
// relaunchPackage restarts the other installations of a package whose binary
// changed, so they run the binary the package now pins.
func (m *Module) relaunchPackage(ctx context.Context, changed store.Installed) {
installed, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "read installations to restart", "package", changed.PackageName, "error", err)
return
}
for _, a := range ordered(installed) {
if a.PackageID != changed.PackageID || a.ID == changed.ID {
continue
}
_ = m.launch(ctx, a)
}
}
// extensionName is the path of an operation on one installed extension.
type extensionName struct {
Name string `path:"name"`
@@ -162,7 +198,7 @@ type Lifecycle struct {
Enabled bool `json:"enabled"`
}
func lifecycleOf(a store.Accepted, rec packageRecord) *httpapi.Reply[Lifecycle] {
func lifecycleOf(a store.Installed, rec packageRecord) *httpapi.Reply[Lifecycle] {
return httpapi.OK(Lifecycle{
Name: a.Name, Version: rec.State.Current.Version, Digest: rec.State.Current.Digest,
Pending: rec.State.Pending != nil, Enabled: a.Enabled,
@@ -170,7 +206,7 @@ func lifecycleOf(a store.Accepted, rec packageRecord) *httpapi.Reply[Lifecycle]
}
// change applies one lifecycle step to an installed extension.
func (m *Module) change(ctx context.Context, name, action string, step func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error)) (*httpapi.Reply[Lifecycle], error) {
func (m *Module) change(ctx context.Context, name, action string, step func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error)) (*httpapi.Reply[Lifecycle], error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
old, rec, err := m.find(ctx, name)
@@ -203,11 +239,13 @@ func (m *Module) install(ctx context.Context, in *extensionName) (*httpapi.Reply
if !slices.Contains(catalogueContracts, entry.Contract) {
return nil, huma.NewError(http.StatusUnprocessableEntity, fmt.Sprintf("%s serves contract %q, which a catalogue doesn't install", entry.Name, entry.Contract))
}
accepted, err := m.store.List(ctx, m.orgID)
accepted, err := m.store.List(ctx)
if err != nil {
return nil, m.lifecycleError(ctx, err)
}
if slices.ContainsFunc(accepted, func(a store.Accepted) bool { return a.Name == entry.Name }) {
if slices.ContainsFunc(accepted, func(a store.Installed) bool {
return a.PackageName == entry.Name || (a.Scope == store.ScopeInstance && a.Name == entry.Name)
}) {
return nil, huma.NewError(http.StatusConflict, entry.Name+" is already installed")
}
pin, err := m.fetchPin(ctx, location, entry)
@@ -215,14 +253,17 @@ func (m *Module) install(ctx context.Context, in *extensionName) (*httpapi.Reply
return nil, m.lifecycleError(ctx, err)
}
rec := packageRecord{DisplayName: entry.DisplayName, Description: entry.Description, State: catalogue.Install(pin)}
row, err := rowOf(store.Accepted{
OrgID: m.orgID, Name: entry.Name, Contract: entry.Contract,
row, err := rowOf(store.Installed{
ID: uuid.New(), Scope: store.ScopeInstance, Name: entry.Name, PackageName: entry.Name, Contract: entry.Contract,
Settings: []byte(`{}`), Credentials: []byte(`{}`), Tools: []byte(`[]`),
}, rec, false)
if err != nil {
return nil, m.lifecycleError(ctx, err)
}
if err := m.store.Save(ctx, row, nil); err != nil {
if row, err = m.persistInstance(ctx)(ctx, row, nil); err != nil {
return nil, m.lifecycleError(ctx, err)
}
if _, err := m.refresh(ctx); err != nil {
return nil, m.lifecycleError(ctx, err)
}
m.log.InfoContext(ctx, "extension installed", "audit", true, "action", "extension.install", "package", entry.Name, "digest", pin.Digest)
@@ -261,23 +302,23 @@ type acceptGrantsInput struct {
}
func (m *Module) acceptGrants(ctx context.Context, in *acceptGrantsInput) (*httpapi.Reply[Lifecycle], error) {
return m.change(ctx, in.Name, "accept", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, in.Name, "accept", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
grants := rec.State.Current.Declared
if in.Body != nil {
grants = catalogue.Grants{Egress: in.Body.Egress, Env: in.Body.Env, Credentials: slices.Collect(maps.Keys(in.Body.Credentials))}
settings, err := json.Marshal(in.Body.Settings, json.FormatNilMapAsNull(false))
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
slots, err := json.Marshal(in.Body.Credentials, json.FormatNilMapAsNull(false))
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
a.Settings, a.Credentials = settings, slots
}
state, err := rec.State.Accept(grants)
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
rec.State = state
row, err := rowOf(a, rec, a.Enabled)
@@ -301,7 +342,7 @@ func (m *Module) putExtensionSettings(ctx context.Context, in *extensionSettings
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
return m.change(ctx, in.Name, "settings", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, in.Name, "settings", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
a.Settings = settings
row, err := rowOf(a, rec, a.Enabled)
return row, rec, err
@@ -324,13 +365,13 @@ func (m *Module) updateFrom(ctx context.Context, doc catalogue.Document, locatio
if !ok {
return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s", name))
}
return m.change(ctx, name, "update", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, name, "update", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
if entry.Digest == rec.State.Current.Digest || (rec.State.Pending != nil && rec.State.Pending.Digest == entry.Digest) {
return a, rec, nil
}
pin, err := m.fetchPin(ctx, location, entry)
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
rec.State, _ = rec.State.Offer(pin)
rec.DisplayName, rec.Description = entry.DisplayName, entry.Description
@@ -340,10 +381,10 @@ func (m *Module) updateFrom(ctx context.Context, doc catalogue.Document, locatio
}
func (m *Module) approveUpdate(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) {
return m.change(ctx, in.Name, "approve_update", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, in.Name, "approve_update", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
state, err := rec.State.Approve()
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
rec.State = state
row, err := rowOf(a, rec, a.Enabled)
@@ -352,10 +393,10 @@ func (m *Module) approveUpdate(ctx context.Context, in *extensionName) (*httpapi
}
func (m *Module) rollback(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) {
return m.change(ctx, in.Name, "rollback", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, in.Name, "rollback", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
state, err := rec.State.Rollback()
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
rec.State = state
row, err := rowOf(a, rec, a.Enabled)
@@ -372,10 +413,10 @@ type extensionPolicyInput struct {
}
func (m *Module) setPolicy(ctx context.Context, in *extensionPolicyInput) (*httpapi.Reply[Lifecycle], error) {
return m.change(ctx, in.Name, "update_policy", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, in.Name, "update_policy", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
state, err := rec.State.SetPolicy(in.Body.Policy)
if err != nil {
return store.Accepted{}, rec, err
return store.Installed{}, rec, err
}
rec.State = state
row, err := rowOf(a, rec, a.Enabled)
@@ -393,9 +434,9 @@ type extensionEnabledInput struct {
func (m *Module) setEnabled(ctx context.Context, in *extensionEnabledInput) (*httpapi.Reply[Lifecycle], error) {
enabled := in.Body.Enabled
return m.change(ctx, in.Name, "enable", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
return m.change(ctx, in.Name, "enable", func(a store.Installed, rec packageRecord) (store.Installed, packageRecord, error) {
if enabled && rec.State.Accepted == nil {
return store.Accepted{}, rec, huma.NewError(http.StatusConflict, "accept the extension's grants before enabling it")
return store.Installed{}, rec, huma.NewError(http.StatusConflict, "accept the extension's grants before enabling it")
}
row, err := rowOf(a, rec, enabled)
return row, rec, err
@@ -406,12 +447,15 @@ func (m *Module) setEnabled(ctx context.Context, in *extensionEnabledInput) (*ht
// catalogue pins. One that fails doesn't stop the rest. It does nothing when no
// catalogue source is set.
func (m *Module) UpdateAuto(ctx context.Context) error {
accepted, err := m.store.List(ctx, m.orgID)
accepted, err := m.store.List(ctx)
if err != nil {
return err
}
var auto []string
for _, a := range accepted {
if a.Scope != store.ScopeInstance {
continue
}
if rec, ok, err := packageOf(a); err == nil && ok && rec.State.Policy == catalogue.PolicyAuto {
auto = append(auto, a.Name)
}
+110 -31
View File
@@ -2,12 +2,14 @@ package connectors
import (
"context"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
@@ -19,65 +21,88 @@ func (m *Module) remove(contract string) func(context.Context, *nameInput) (*htt
}
}
// removeAs retires an accepted package: its row (and so its credential slots)
// is deleted and its process stopped. A name that isn't accepted under this
// route's contract is a 404, which keeps a repeated removal harmless. A secret
// engine a stored credential still resolves through is refused, since those
// credentials would stop resolving.
// removeAs retires an accepted package: the package and its instance
// installations are deleted, and their processes stopped. A name that isn't an
// accepted package of this route's contract is a 404, which keeps a repeated
// removal harmless. A package an organisation or a person still has an
// installation of is refused, and so is a secret engine a stored credential
// still resolves through, since those credentials would stop resolving.
func (m *Module) removeAs(ctx context.Context, in *nameInput, contract string) (*httpapi.Reply[packageState], error) {
name := in.Name
accepted, err := m.store.List(ctx, m.orgID)
installed, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list accepted packages", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
m.log.ErrorContext(ctx, "list installations", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
if !slices.ContainsFunc(accepted, func(a store.Accepted) bool { return a.Name == name && a.Contract == contract }) {
i := slices.IndexFunc(installed, func(a store.Installed) bool {
return a.Scope == store.ScopeInstance && a.Name == name && a.Contract == contract
})
if i < 0 {
return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("no accepted %s named %s", contract, name))
}
if contract == store.ContractSecretEngine {
users, err := m.engineUsers(ctx, name)
if err != nil {
m.log.ErrorContext(ctx, "check secret engine use", "engine", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't check the credentials that use "+name)
}
if len(users) > 0 {
return nil, huma.NewError(http.StatusConflict,
fmt.Sprintf("secret engine %s is still used by credentials: %s", name, strings.Join(users, ", ")))
}
if err := m.checkEngineUnused(ctx, installed[i]); err != nil {
return nil, err
}
found, err := m.store.Delete(ctx, m.orgID, name)
if err != nil {
found, err := m.store.DeletePackage(ctx, installed[i].PackageName)
switch {
case errors.Is(err, store.ErrInstalled):
return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("%s is still installed by an organisation or a person", name))
case err != nil:
m.log.ErrorContext(ctx, "remove accepted package", "package", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't remove "+name)
}
if !found {
case !found:
return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("no accepted %s named %s", contract, name))
}
m.release(name)
m.mu.Lock()
delete(m.failed, name)
m.mu.Unlock()
for _, a := range installed {
if a.PackageID == installed[i].PackageID {
m.forget(a.ID.String())
}
}
if _, err := m.refresh(ctx); err != nil {
m.log.ErrorContext(ctx, "read installations", "error", err)
}
// There is no audit trail module yet, so the removal is a structured log
// line.
m.log.InfoContext(ctx, "accepted package removed", "audit", true, "action", "package.remove", "contract", contract, "package", name)
return httpapi.OK(packageState{Name: name, State: "removed"}), nil
}
// checkEngineUnused refuses the removal of a secret engine that a stored
// credential still resolves through.
func (m *Module) checkEngineUnused(ctx context.Context, a store.Installed) error {
if a.Contract != store.ContractSecretEngine {
return nil
}
users, err := m.engineUsers(ctx, a)
if err != nil {
m.log.ErrorContext(ctx, "check secret engine use", "engine", a.Name, "error", err)
return huma.NewError(http.StatusInternalServerError, "couldn't check the credentials that use "+a.Name)
}
if len(users) > 0 {
return huma.NewError(http.StatusConflict,
fmt.Sprintf("secret engine %s is still used by credentials: %s", a.Name, strings.Join(users, ", ")))
}
return nil
}
// engineUsers names, in order, the credentials with a field resolved through
// the secret engine.
func (m *Module) engineUsers(ctx context.Context, engine string) ([]string, error) {
creds, err := m.store.Credentials(ctx, m.orgID)
// the secret engine installation a: those its owner's scope can reach.
func (m *Module) engineUsers(ctx context.Context, a store.Installed) ([]string, error) {
creds, err := m.store.Credentials(ctx)
if err != nil {
return nil, err
}
var users []string
for _, c := range creds {
if !uses(c.Owner(), a.Owner()) {
continue
}
fields, err := m.openCredential(c)
if err != nil {
return nil, err
}
for _, f := range fields {
if f.Engine == engine {
if f.Engine == a.Name {
users = append(users, c.Name)
break
}
@@ -85,3 +110,57 @@ func (m *Module) engineUsers(ctx context.Context, engine string) ([]string, erro
}
return users, nil
}
type installationInput struct {
ID uuid.UUID `path:"id"`
}
// removeInstallation deletes one installation the caller manages and stops it.
// The package stays accepted.
func (m *Module) removeInstallation(ctx context.Context, in *installationInput) (*httpapi.Reply[packageState], error) {
a, _, err := m.installationFor(ctx, in.ID, true)
if err != nil {
return nil, err
}
if err := m.checkEngineUnused(ctx, a); err != nil {
return nil, err
}
found, err := m.store.DeleteInstallation(ctx, a.ID)
if err != nil {
m.log.ErrorContext(ctx, "remove installation", "installation", a.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't remove "+a.Name)
}
if !found {
return nil, huma.NewError(http.StatusNotFound, "no such installation")
}
m.forget(a.ID.String())
if _, err := m.refresh(ctx); err != nil {
m.log.ErrorContext(ctx, "read installations", "error", err)
}
m.log.InfoContext(ctx, "installation removed", "audit", true, "action", "installation.remove",
"installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName)
return httpapi.OK(packageState{Name: a.Name, State: "removed"}), nil
}
// installationFor reads one installation the caller can see. With manage set,
// it must be one the caller may change; an installation the caller may not see
// is a 404, so another organisation's installations are not confirmed to exist.
func (m *Module) installationFor(ctx context.Context, id uuid.UUID, manage bool) (store.Installed, authority, error) {
auth, err := authorityOf(ctx)
if err != nil {
return store.Installed{}, authority{}, err
}
installed, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list installations", "error", err)
return store.Installed{}, authority{}, huma.NewError(http.StatusInternalServerError, "couldn't read the installations")
}
i := slices.IndexFunc(installed, func(a store.Installed) bool { return a.ID == id })
if i < 0 || !auth.sees(installed[i].Owner()) {
return store.Installed{}, authority{}, huma.NewError(http.StatusNotFound, "no such installation")
}
if manage && !auth.manages(installed[i].Owner()) {
return store.Installed{}, authority{}, huma.NewError(http.StatusForbidden, "you may not change this installation")
}
return installed[i], auth, nil
}
+36 -31
View File
@@ -12,6 +12,7 @@ import (
"filippo.io/age"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
@@ -19,45 +20,50 @@ import (
// fakeRegistry is an in-memory registry.
type fakeRegistry struct {
accepted map[string]store.Accepted
creds []store.Credential
installed map[string]store.Installed
creds []store.Credential
}
func (f *fakeRegistry) List(context.Context, string) ([]store.Accepted, error) {
var out []store.Accepted
for _, a := range f.accepted {
func (f *fakeRegistry) List(context.Context) ([]store.Installed, error) {
var out []store.Installed
for _, a := range f.installed {
out = append(out, a)
}
return out, nil
}
func (f *fakeRegistry) Delete(_ context.Context, _, name string) (bool, error) {
_, ok := f.accepted[name]
delete(f.accepted, name)
func (f *fakeRegistry) Overrides(context.Context) ([]store.Override, error) { return nil, nil }
func (f *fakeRegistry) Packages(context.Context) ([]store.Package, error) { return nil, nil }
func (f *fakeRegistry) DeletePackage(_ context.Context, name string) (bool, error) {
_, ok := f.installed[name]
delete(f.installed, name)
return ok, nil
}
func (f *fakeRegistry) Credential(_ context.Context, _, name string) (store.Credential, bool, error) {
for _, c := range f.creds {
if c.Name == name {
return c, true, nil
}
}
return store.Credential{}, false, nil
func (f *fakeRegistry) DeleteInstallation(context.Context, uuid.UUID) (bool, error) {
return false, nil
}
func (f *fakeRegistry) Credentials(context.Context, string) ([]store.Credential, error) {
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) SetCapabilities(context.Context, string, string, jsontext.Value) error {
func (f *fakeRegistry) SetCapabilities(context.Context, uuid.UUID, jsontext.Value) error {
return nil
}
func (f *fakeRegistry) Capabilities(context.Context, string, string) (jsontext.Value, bool, error) {
return nil, false, nil
func (f *fakeRegistry) SetOverride(context.Context, store.Override, bool, string) error { return nil }
func (f *fakeRegistry) SaveInstalled(_ context.Context, in store.Installed, _ string, _ jsontext.Value) (store.Installed, error) {
return in, nil
}
func (f *fakeRegistry) SaveInstallation(_ context.Context, in store.Installed, _ jsontext.Value) (store.Installed, error) {
return in, nil
}
// TestRemovingAPackage guards the credential boundary of removal: a secret
@@ -74,17 +80,17 @@ func TestRemovingAPackage(t *testing.T) {
t.Fatal(err)
}
log := slog.New(slog.DiscardHandler)
m := &Module{orgID: "org", sealer: sealer, log: log, host: NewHost(log), failed: map[string]string{}}
m := &Module{sealer: sealer, log: log, host: NewHost(log), failed: map[string]string{}, running: map[string]*Connector{}, engines: map[string]*Engine{}, guards: map[string]*Guard{}, servers: map[string]*Server{}, stops: map[string]context.CancelFunc{}}
credential := func(name string, fields map[string]Field) store.Credential {
plain, err := json.Marshal(fields)
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal(m.credentialLabel(name, "bearer"), plain)
sealed, err := sealer.Seal(credentialLabel(store.Owner{Scope: store.ScopeInstance}, name, "bearer"), plain)
if err != nil {
t.Fatal(err)
}
return store.Credential{OrgID: "org", Name: name, Kind: "bearer", Sealed: sealed}
return store.Credential{Scope: store.ScopeInstance, Name: name, Kind: "bearer", Sealed: sealed}
}
tests := []struct {
name string
@@ -100,13 +106,14 @@ func TestRemovingAPackage(t *testing.T) {
{name: "missing package is a 404", contract: store.ContractConnector, target: "gone", wantStatus: 404},
{name: "wrong route is a 404 and keeps the package", contract: store.ContractMCP, target: "chat", wantStatus: 404, wantKept: true},
}
ids := map[string]uuid.UUID{"vault": uuid.New(), "idle-engine": uuid.New(), "chat": uuid.New(), "gone": uuid.New()}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &fakeRegistry{
accepted: map[string]store.Accepted{
"vault": {Name: "vault", Contract: store.ContractSecretEngine},
"idle-engine": {Name: "idle-engine", Contract: store.ContractSecretEngine},
"chat": {Name: "chat", Contract: store.ContractConnector},
installed: map[string]store.Installed{
"vault": {ID: ids["vault"], Scope: store.ScopeInstance, Name: "vault", PackageName: "vault", Contract: store.ContractSecretEngine},
"idle-engine": {ID: ids["idle-engine"], Scope: store.ScopeInstance, Name: "idle-engine", PackageName: "idle-engine", Contract: store.ContractSecretEngine},
"chat": {ID: ids["chat"], Scope: store.ScopeInstance, Name: "chat", PackageName: "chat", Contract: store.ContractConnector},
},
creds: []store.Credential{
credential("api-token", map[string]Field{"token": {Engine: "vault", Key: "k"}}),
@@ -115,7 +122,7 @@ func TestRemovingAPackage(t *testing.T) {
},
}
m.store = reg
m.failed[tt.target] = "boom"
m.failed[ids[tt.target].String()] = "boom"
_, err := m.removeAs(t.Context(), &nameInput{Name: tt.target}, tt.contract)
status, body := statusOf(err)
if status != tt.wantStatus {
@@ -124,10 +131,10 @@ func TestRemovingAPackage(t *testing.T) {
if !strings.Contains(body, tt.wantBody) {
t.Errorf("body %q lacks %q", body, tt.wantBody)
}
if _, kept := reg.accepted[tt.target]; kept != tt.wantKept {
if _, kept := reg.installed[tt.target]; kept != tt.wantKept {
t.Errorf("package kept = %v, want %v", kept, tt.wantKept)
}
if _, stillFailed := m.failed[tt.target]; tt.wantStatus == http.StatusOK && stillFailed {
if _, stillFailed := m.failed[ids[tt.target].String()]; tt.wantStatus == http.StatusOK && stillFailed {
t.Error("readiness still reports the removed package")
}
})
@@ -144,5 +151,3 @@ func statusOf(err error) (int, string) {
}
return http.StatusInternalServerError, err.Error()
}
func (f *fakeRegistry) Save(context.Context, store.Accepted, jsontext.Value) error { return nil }
+271
View File
@@ -0,0 +1,271 @@
package connectors
import (
"context"
"net/http"
"slices"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// Scope is who a request acts for: a person in an organisation. A background
// job acts for an organisation alone, so it never reaches a person's
// installations or credentials.
type Scope struct {
OrgID string
PersonID string
}
type scopeKey struct{}
// WithScope makes every installation and credential lookup made with ctx act
// for s.
func WithScope(ctx context.Context, s Scope) context.Context {
return context.WithValue(ctx, scopeKey{}, s)
}
// ScopeFromContext returns the scope ctx acts for: the one WithScope set, or
// the organisation and the user the request is authenticated as.
func ScopeFromContext(ctx context.Context) Scope {
if s, ok := ctx.Value(scopeKey{}).(Scope); ok {
return s
}
s := Scope{OrgID: string(governance.OrgFromContext(ctx))}
if p, ok := governance.PrincipalFromContext(ctx); ok && p.Kind == governance.KindUser {
s.PersonID = string(p.IdentityID)
}
return s
}
// Scopes an installation can be owned by.
const (
ScopeInstance = store.ScopeInstance
ScopeOrg = store.ScopeOrg
ScopePerson = store.ScopePerson
)
// Installation identifies the installation a tool, a guard or a credential
// came from, so a decision can record which configuration acted.
type Installation struct {
ID uuid.UUID `json:"id"`
Scope string `json:"scope" enum:"instance,org,person"`
}
// owners lists the owners whose installations and credentials s may use, most
// specific first.
func (s Scope) owners() []store.Owner {
var out []store.Owner
if s.PersonID != "" {
out = append(out, store.Owner{Scope: store.ScopePerson, PersonID: s.PersonID})
}
if s.OrgID != "" {
out = append(out, store.Owner{Scope: store.ScopeOrg, OrgID: s.OrgID})
}
return append(out, store.Owner{Scope: store.ScopeInstance})
}
// scopeOf is the scope an installation or a credential owner acts for when it
// looks up the credentials and engines it is configured with. A person's
// installation reaches the person's credentials, then the instance's.
func scopeOf(o store.Owner) Scope {
return Scope{OrgID: o.OrgID, PersonID: o.PersonID}
}
// member is what resolution needs to know of one installation.
type member struct {
id string
name string
owner store.Owner
contract string
enabled bool
}
type override struct {
id string
owner store.Owner
}
// index resolves names to installations. It is read-only: the module builds a
// new one whenever an installation or an override changes.
type index struct {
members map[string]member
overrides map[override]struct{}
}
func newIndex(installed []store.Installed, overrides []store.Override) index {
ix := index{members: make(map[string]member, len(installed)), overrides: make(map[override]struct{}, len(overrides))}
for _, a := range installed {
ix.members[a.ID.String()] = member{
id: a.ID.String(), name: a.Name, owner: a.Owner(), contract: a.Contract, enabled: a.Enabled,
}
}
for _, o := range overrides {
ix.overrides[override{id: o.InstallationID.String(), owner: store.Owner{Scope: o.Scope, OrgID: o.OrgID, PersonID: o.PersonID}}] = struct{}{}
}
return ix
}
// usable reports whether s may use m: m is owned by s's person or
// organisation or by the instance, and no override of s's switches it off.
func (ix index) usable(s Scope, m member) bool {
if !m.enabled {
return false
}
switch m.owner.Scope {
case store.ScopePerson:
return s.PersonID != "" && m.owner.PersonID == s.PersonID
case store.ScopeOrg:
return s.OrgID != "" && m.owner.OrgID == s.OrgID && !ix.hidden(s, m)
}
return !ix.hidden(s, m)
}
// hidden reports whether an organisation or a person switched m off for s.
func (ix index) hidden(s Scope, m member) bool {
return len(ix.overriddenBy(s, m)) > 0
}
// overriddenBy lists the scopes of s that switched m off, person first.
func (ix index) overriddenBy(s Scope, m member) []string {
var out []string
if s.PersonID != "" {
if _, off := ix.overrides[override{id: m.id, owner: store.Owner{Scope: store.ScopePerson, PersonID: s.PersonID}}]; off {
out = append(out, store.ScopePerson)
}
}
if s.OrgID != "" {
if _, off := ix.overrides[override{id: m.id, owner: store.Owner{Scope: store.ScopeOrg, OrgID: s.OrgID}}]; off {
out = append(out, store.ScopeOrg)
}
}
return out
}
// resolve finds the installation ref names for s. An installation ID wins when
// s may use it. A name resolves to the person's installation, then the
// organisation's, then the instance's.
func (ix index) resolve(s Scope, ref string) (member, bool) {
if _, err := uuid.Parse(ref); err == nil {
m, ok := ix.members[ref]
return m, ok && ix.usable(s, m)
}
for _, o := range s.owners() {
for _, m := range ix.members {
if m.name == ref && m.owner == o && ix.usable(s, m) {
return m, true
}
}
}
return member{}, false
}
// visible lists what each name resolves to for s, in name order.
func (ix index) visible(s Scope) []member {
seen := map[string]bool{}
var out []member
for _, o := range s.owners() {
for _, m := range ix.members {
if m.owner == o && !seen[m.name] && ix.usable(s, m) {
seen[m.name] = true
out = append(out, m)
}
}
}
slices.SortFunc(out, func(a, b member) int { return strings.Compare(a.name, b.name) })
return out
}
// authority is what a caller may manage and read.
type authority struct{ p governance.Principal }
func authorityOf(ctx context.Context) (authority, error) {
p, ok := governance.PrincipalFromContext(ctx)
if !ok {
return authority{}, huma.NewError(http.StatusUnauthorized, "sign in to manage installations")
}
return authority{p}, nil
}
// manages reports whether the caller may change what o owns: an instance
// administrator for the instance, an organisation owner for that organisation,
// and a person for their own.
func (a authority) manages(o store.Owner) bool {
switch o.Scope {
case store.ScopeInstance:
return a.p.InstanceAdmin()
case store.ScopeOrg:
return a.p.Kind == governance.KindUser && o.OrgID == string(a.p.Org) && a.p.RoleIn(a.p.Org) == governance.RoleOwner
case store.ScopePerson:
return a.p.Kind == governance.KindUser && a.p.IdentityID != "" && o.PersonID == string(a.p.IdentityID)
}
return false
}
// sees reports whether the caller may list what o owns: everything the
// instance owns, the caller's own organisation's, and the caller's own.
func (a authority) sees(o store.Owner) bool {
switch o.Scope {
case store.ScopeInstance:
return true
case store.ScopeOrg:
return o.OrgID == string(a.p.Org) && a.p.Member(a.p.Org)
case store.ScopePerson:
return a.manages(o)
}
return false
}
// ownerAt returns the owner the caller means by naming scope: the caller's own
// organisation or person, or the instance. It fails when the caller may not
// manage what that owner holds.
func (a authority) ownerAt(scope string) (store.Owner, error) {
var o store.Owner
switch scope {
case store.ScopeInstance:
o = store.Owner{Scope: scope}
case store.ScopeOrg:
o = store.Owner{Scope: scope, OrgID: string(a.p.Org)}
case store.ScopePerson:
o = store.Owner{Scope: scope, PersonID: string(a.p.IdentityID)}
default:
return store.Owner{}, huma.NewError(http.StatusBadRequest, "scope is instance, org or person")
}
if !a.manages(o) {
return store.Owner{}, huma.NewError(http.StatusForbidden, "you may not change "+scope+" installations")
}
return o, nil
}
// overrideScopes lists the scopes the caller may switch installation o off at.
// An organisation may switch off an instance installation and a person may
// switch off one owned by the instance or their organisation, which are the
// scopes they inherit. The installation's own scope and narrower ones are not
// inherited, so they cannot override it.
func overrideScopes(a authority, o store.Owner) []string {
var out []string
if a.p.Kind == governance.KindUser && a.p.RoleIn(a.p.Org) == governance.RoleOwner && o.Scope == store.ScopeInstance {
out = append(out, store.ScopeOrg)
}
if a.p.Kind == governance.KindUser && a.p.IdentityID != "" && o.Scope != store.ScopePerson {
out = append(out, store.ScopePerson)
}
return out
}
// pickInstalled finds the installation name resolves to for s among installed,
// running or not: the person's, then the organisation's, then the instance's.
func pickInstalled(installed []store.Installed, s Scope, name string) (store.Installed, bool) {
for _, o := range s.owners() {
for _, a := range installed {
if a.Name == name && a.Owner() == o {
return a, true
}
}
}
return store.Installed{}, false
}
+178
View File
@@ -0,0 +1,178 @@
package connectors
import (
"slices"
"testing"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
)
// TestInstallationResolutionRespectsScope guards the installation boundary: a
// name resolves to the person's installation, then their organisation's, then
// the instance's; an override hides only what the scope that set it inherits;
// and an installation ID is usable only by a scope that may see it.
func TestInstallationResolutionRespectsScope(t *testing.T) {
instance := store.Installed{ID: uuid.New(), Scope: store.ScopeInstance, Name: "pager", Enabled: true}
instanceOnly := store.Installed{ID: uuid.New(), Scope: store.ScopeInstance, Name: "ledger", Enabled: true}
orgOwn := store.Installed{ID: uuid.New(), Scope: store.ScopeOrg, OrgID: "own", Name: "pager", Enabled: true}
orgOther := store.Installed{ID: uuid.New(), Scope: store.ScopeOrg, OrgID: "other", Name: "pager", Enabled: true}
personOwn := store.Installed{ID: uuid.New(), Scope: store.ScopePerson, PersonID: "me", Name: "pager", Enabled: true}
personOff := store.Installed{ID: uuid.New(), Scope: store.ScopePerson, PersonID: "me", Name: "off", Enabled: false}
ix := newIndex(
[]store.Installed{instance, instanceOnly, orgOwn, orgOther, personOwn, personOff},
[]store.Override{
{InstallationID: instance.ID, Scope: store.ScopeOrg, OrgID: "own"},
{InstallationID: instanceOnly.ID, Scope: store.ScopeOrg, OrgID: "own"},
{InstallationID: orgOwn.ID, Scope: store.ScopePerson, PersonID: "me"},
},
)
me := Scope{OrgID: "own", PersonID: "me"}
org := Scope{OrgID: "own"}
other := Scope{OrgID: "other", PersonID: "them"}
third := Scope{OrgID: "third", PersonID: "someone"}
tests := []struct {
name string
scope Scope
ref string
want uuid.UUID
wantOK bool
visible int
}{
{name: "the person's own installation wins over the organisation's and the instance's", scope: me, ref: "pager", want: personOwn.ID, wantOK: true, visible: 1},
{name: "an organisation sees only its own installation once it has switched the instance's off", scope: org, ref: "pager", want: orgOwn.ID, wantOK: true, visible: 1},
{name: "another organisation never reaches the first organisation's installation", scope: other, ref: "pager", want: orgOther.ID, wantOK: true, visible: 2},
{name: "a scope with no installation of its own inherits the instance's", scope: third, ref: "pager", want: instance.ID, wantOK: true, visible: 2},
{name: "an organisation's override hides an instance installation it would inherit", scope: org, ref: "ledger", wantOK: false, visible: 1},
{name: "a scope without the override still reaches the instance installation", scope: third, ref: "ledger", want: instanceOnly.ID, wantOK: true, visible: 2},
{name: "an explicit installation ID wins for a scope that may use it", scope: third, ref: instance.ID.String(), want: instance.ID, wantOK: true},
{name: "an explicit ID does not reach another organisation's installation", scope: other, ref: orgOwn.ID.String(), wantOK: false},
{name: "an explicit ID does not reach an installation the scope switched off", scope: me, ref: orgOwn.ID.String(), wantOK: false},
{name: "a disabled installation never resolves", scope: me, ref: "off", wantOK: false, visible: 1},
{name: "an unknown name resolves to nothing", scope: me, ref: "missing", wantOK: false, visible: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := ix.resolve(tt.scope, tt.ref)
if ok != tt.wantOK {
t.Fatalf("resolve(%q) ok = %v, want %v", tt.ref, ok, tt.wantOK)
}
if ok && got.id != tt.want.String() {
t.Errorf("resolve(%q) = %s, want %s", tt.ref, got.id, tt.want)
}
if tt.visible != 0 {
if got := ix.visible(tt.scope); len(got) != tt.visible {
t.Errorf("visible() has %d names, want %d", len(got), tt.visible)
}
}
})
}
}
// TestOverridesNameTheScopeThatSetThem guards the restore action: a caller is
// told which of its own scopes switched an inherited installation off, so it
// restores that one rather than a scope that never hid it.
func TestOverridesNameTheScopeThatSetThem(t *testing.T) {
instance := store.Installed{ID: uuid.New(), Scope: store.ScopeInstance, Name: "pager", Enabled: true}
orgOwn := store.Installed{ID: uuid.New(), Scope: store.ScopeOrg, OrgID: "own", Name: "pager", Enabled: true}
ix := newIndex(
[]store.Installed{instance, orgOwn},
[]store.Override{
{InstallationID: instance.ID, Scope: store.ScopeOrg, OrgID: "own"},
{InstallationID: instance.ID, Scope: store.ScopePerson, PersonID: "me"},
},
)
me := Scope{OrgID: "own", PersonID: "me"}
tests := []struct {
name string
ref string
want []string
}{
{name: "an instance installation hidden by the organisation and the person names both, person first", ref: instance.ID.String(), want: []string{store.ScopePerson, store.ScopeOrg}},
{name: "an installation with no override names none", ref: orgOwn.ID.String(), want: nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mem, ok := ix.members[tt.ref]
if !ok {
t.Fatalf("no installation %s", tt.ref)
}
got := ix.overriddenBy(me, mem)
if !slices.Equal(got, tt.want) {
t.Errorf("overriddenBy() = %v, want %v", got, tt.want)
}
})
}
}
// TestCredentialResolutionRespectsScope guards the credential boundary: a name
// resolves to the person's credential, then their organisation's, then the
// instance's, and never to another organisation's or person's.
func TestCredentialResolutionRespectsScope(t *testing.T) {
instance := store.Credential{Scope: store.ScopeInstance, Name: "token", Kind: "bearer"}
orgOwn := store.Credential{Scope: store.ScopeOrg, OrgID: "own", Name: "token", Kind: "bearer"}
orgOnly := store.Credential{Scope: store.ScopeOrg, OrgID: "own", Name: "own-only", Kind: "bearer"}
orgOther := store.Credential{Scope: store.ScopeOrg, OrgID: "other", Name: "token", Kind: "bearer"}
personOwn := store.Credential{Scope: store.ScopePerson, PersonID: "me", Name: "token", Kind: "bearer"}
creds := []store.Credential{instance, orgOwn, orgOnly, orgOther, personOwn}
tests := []struct {
name string
scope Scope
ref string
want store.Credential
wantOK bool
}{
{name: "the person's own credential wins", scope: Scope{OrgID: "own", PersonID: "me"}, ref: "token", want: personOwn, wantOK: true},
{name: "an organisation reaches its own credential", scope: Scope{OrgID: "own"}, ref: "token", want: orgOwn, wantOK: true},
{name: "another organisation reaches only its own", scope: Scope{OrgID: "other", PersonID: "them"}, ref: "token", want: orgOther, wantOK: true},
{name: "a scope with no credential of its own inherits the instance's", scope: Scope{OrgID: "third", PersonID: "someone"}, ref: "token", want: instance, wantOK: true},
{name: "another organisation never reaches the first organisation's credential", scope: Scope{OrgID: "other", PersonID: "them"}, ref: "own-only", wantOK: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok, err := pickCredential(creds, tt.scope, tt.ref)
if err != nil {
t.Fatal(err)
}
if ok != tt.wantOK {
t.Fatalf("pickCredential(%q) ok = %v, want %v", tt.ref, ok, tt.wantOK)
}
if ok && got.Owner() != tt.want.Owner() {
t.Errorf("pickCredential(%q) owner = %+v, want %+v", tt.ref, got.Owner(), tt.want.Owner())
}
})
}
}
// TestCredentialUseStaysAtItsScope guards which installations a stored
// credential may restart: the instance's reach every installation, and an
// organisation's or a person's reach only their own.
func TestCredentialUseStaysAtItsScope(t *testing.T) {
instance := store.Owner{Scope: store.ScopeInstance}
org := store.Owner{Scope: store.ScopeOrg, OrgID: "own"}
person := store.Owner{Scope: store.ScopePerson, PersonID: "me"}
tests := []struct {
name string
installation, cred store.Owner
want bool
}{
{name: "an instance credential reaches an instance installation", installation: instance, cred: instance, want: true},
{name: "an instance credential reaches an organisation installation", installation: org, cred: instance, want: true},
{name: "an instance credential reaches a person installation", installation: person, cred: instance, want: true},
{name: "an organisation credential reaches its own installation", installation: org, cred: org, want: true},
{name: "an organisation credential does not reach another organisation", installation: store.Owner{Scope: store.ScopeOrg, OrgID: "other"}, cred: org, want: false},
{name: "a person credential reaches that person's installation", installation: person, cred: person, want: true},
{name: "a person credential does not reach another person", installation: store.Owner{Scope: store.ScopePerson, PersonID: "them"}, cred: person, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := uses(tt.installation, tt.cred); got != tt.want {
t.Errorf("uses(%+v, %+v) = %v, want %v", tt.installation, tt.cred, got, tt.want)
}
})
}
}
+2 -2
View File
@@ -53,9 +53,9 @@ func (l *ledger) GaveUp(_ context.Context, _ int64, _ int, reason string, _ time
// so a send that was attempted fails and a send that was refused never looks.
type channelLookups struct{ looked int }
func (c *channelLookups) Delivering(string) []*connectors.Connector { return nil }
func (c *channelLookups) Delivering(context.Context, string) []*connectors.Connector { return nil }
func (c *channelLookups) Get(string) (*connectors.Connector, bool) {
func (c *channelLookups) Get(context.Context, string) (*connectors.Connector, bool) {
c.looked++
return nil, false
}
+5 -5
View File
@@ -105,8 +105,8 @@ type Attempt struct {
// Channels are the running connectors a message can go out on.
type Channels interface {
Delivering(delivery string) []*connectors.Connector
Get(name string) (*connectors.Connector, bool)
Delivering(ctx context.Context, delivery string) []*connectors.Connector
Get(ctx context.Context, name string) (*connectors.Connector, bool)
}
// Module delivers one organisation's notifications, approval requests and
@@ -157,7 +157,7 @@ func (m *Module) Notify(ctx context.Context, n Notification) error {
// channel has accepted it. The key makes the delivery idempotent on the
// channel, so a step that is replayed after a crash does not send twice.
func (m *Module) Send(ctx context.Context, channel, chatID, text, key string) error {
c, ok := m.channels.Get(channel)
c, ok := m.channels.Get(ctx, channel)
if !ok {
return fmt.Errorf("connector %q isn't running", channel)
}
@@ -205,7 +205,7 @@ func (m *Module) send(ctx context.Context, msg store.Message) error {
if created {
m.hub.Publish(hub.Note{Topic: topicComposer, Seq: seq})
}
for _, c := range m.channels.Delivering(connectors.DeliveryMessage) {
for _, c := range m.channels.Delivering(ctx, connectors.DeliveryMessage) {
// Each channel keeps its own row, so each carries its own id.
row := msg
row.ID, row.Channel, row.Sent = uuid.New(), c.Name(), false
@@ -298,7 +298,7 @@ func (m *Module) recordFailure(ctx context.Context, msg store.Message, cause err
}
func (m *Module) sendTo(ctx context.Context, msg store.Message) (string, error) {
c, ok := m.channels.Get(msg.Channel)
c, ok := m.channels.Get(ctx, msg.Channel)
if !ok {
return "", fmt.Errorf("connector %q isn't running", msg.Channel)
}
+4 -4
View File
@@ -43,7 +43,7 @@ var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
// Connectors finds the running connector a source reads with, and says what a
// connector declared when it last loaded.
type Connectors interface {
Get(name string) (*connectors.Connector, bool)
Get(ctx context.Context, name string) (*connectors.Connector, bool)
Capabilities(ctx context.Context, connector string) (connectors.Capabilities, bool, error)
}
@@ -340,7 +340,7 @@ func (m *Module) UseTrustedProxies(read func(context.Context) ([]netip.Prefix, e
// parseWith has a running connector parse a delivery.
func (m *Module) parseWith(ctx context.Context, connector string, body []byte, headers map[string]string) ([]connectors.Event, error) {
conn, ok := m.connectors.Get(connector)
conn, ok := m.connectors.Get(ctx, connector)
if !ok {
return nil, fmt.Errorf("connector %s: %w", connector, errConnectorDown)
}
@@ -414,7 +414,7 @@ func (m *Module) startListeners(ctx context.Context, wg *sync.WaitGroup, listeni
return
}
for _, src := range sources {
conn, ok := m.connectors.Get(src.Connector)
conn, ok := m.connectors.Get(ctx, src.Connector)
if listening[src.Name] || !ok || !conn.Listens() {
continue
}
@@ -429,7 +429,7 @@ func (m *Module) startListeners(ctx context.Context, wg *sync.WaitGroup, listeni
func (m *Module) listen(ctx context.Context, src store.Source) {
cursor := src.Cursor
for ctx.Err() == nil {
conn, ok := m.connectors.Get(src.Connector)
conn, ok := m.connectors.Get(ctx, src.Connector)
var err error
if !ok {
err = fmt.Errorf("connector %q isn't running", src.Connector)
+3 -2
View File
@@ -9,9 +9,10 @@ import (
"github.com/samcharles93/archie-core/modules/connectors"
)
// GuardExtensions lists the guard extensions running now.
// GuardExtensions lists the guard extensions running now that the scope ctx
// acts for can use.
type GuardExtensions interface {
Guards() []*connectors.Guard
Guards(ctx context.Context) []*connectors.Guard
}
// identified is a guard that says which package answered.
+1 -1
View File
@@ -38,7 +38,7 @@ func (c *fakeGuardClient) Judge(ctx context.Context, _ *gpb.JudgeRequest, _ ...g
type extensions []*connectors.Guard
func (e extensions) Guards() []*connectors.Guard { return e }
func (e extensions) Guards(context.Context) []*connectors.Guard { return e }
// TestGuardExtensionsDecideAtTheLowestCeiling guards the extension path of the
// weakest-link decision (spec section 5, R22): two guard extensions judging
+10 -6
View File
@@ -23,9 +23,13 @@ type Decision struct {
Action string `db:"action"`
TargetKind string `db:"target_kind"`
Environment string `db:"environment"`
Level string `db:"level"`
Dry bool `db:"dry"`
Body []byte `db:"body"`
// InstallationID and InstallationScope name the installation the action
// resolved to.
InstallationID uuid.UUID `db:"installation_id"`
InstallationScope string `db:"installation_scope"`
Level string `db:"level"`
Dry bool `db:"dry"`
Body []byte `db:"body"`
// CreatedAt is set by the database and read only by the action type history.
CreatedAt time.Time `db:"created_at"`
}
@@ -44,11 +48,11 @@ func (s *Store) Record(ctx context.Context, d Decision) (Decision, error) {
var kept Decision
err := s.db.GetContext(ctx, &kept, `
INSERT INTO judgement.decisions
(id, org_id, run_id, key, connector, action, target_kind, environment, level, dry, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
(id, org_id, run_id, key, connector, installation_id, installation_scope, action, target_kind, environment, level, dry, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
ON CONFLICT (org_id, key) DO NOTHING
RETURNING id, org_id, run_id, key, connector, action, target_kind, environment, level, body`,
d.ID, d.OrgID, d.RunID, d.Key, d.Connector, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body)
d.ID, d.OrgID, d.RunID, d.Key, d.Connector, d.InstallationID, d.InstallationScope, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body)
if errors.Is(err, sql.ErrNoRows) {
err = s.db.GetContext(ctx, &kept, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
+20 -12
View File
@@ -42,12 +42,16 @@ var (
// Action is one concrete action: the exact operation on the exact target.
type Action struct {
Connector string `json:"connector"`
Name string `json:"name"`
Input jsontext.Value `json:"input"`
Digest string `json:"digest"`
Target connectors.Target `json:"target"`
Effect connectors.Effect `json:"effect"`
Connector string `json:"connector"`
// Installation is the installation Connector resolved to when the action
// was judged. Executing the decision runs there, whatever scope the
// approver acts for.
Installation connectors.Installation `json:"installation"`
Name string `json:"name"`
Input jsontext.Value `json:"input"`
Digest string `json:"digest"`
Target connectors.Target `json:"target"`
Effect connectors.Effect `json:"effect"`
}
// ActionType identifies the actions that share an autonomy level: one
@@ -203,9 +207,12 @@ type Request struct {
Overlay *PolicyOverlay
}
// Tools finds the tool that resolves and runs an action.
// Tools finds the tool that resolves and runs an action. Tool resolves a
// connector's name for the scope ctx acts for. Installed finds the tool of an
// installation a decision already recorded.
type Tools interface {
Tool(name string) (connectors.Tool, bool)
Tool(ctx context.Context, name string) (connectors.Tool, bool)
Installed(id string) (connectors.Tool, bool)
}
// FailureRecorder is told when an action failed, so the action type loses
@@ -280,7 +287,7 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tools Tools, rules [
// Assess judges one action and records the decision. Judging the same key
// again returns the recorded decision.
func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
tool, ok := m.tools.Tool(req.Connector)
tool, ok := m.tools.Tool(ctx, req.Connector)
if !ok {
return Decision{}, fmt.Errorf("%q isn't running", req.Connector)
}
@@ -291,7 +298,7 @@ func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
return Decision{}, fmt.Errorf("resolve %s %s: %w", req.Connector, req.Action, err)
}
a := Action{
Connector: req.Connector, Name: req.Action, Input: req.Input,
Connector: req.Connector, Installation: tool.Installation(), Name: req.Action, Input: req.Input,
Digest: connectors.Digest(req.Action, req.Input), Target: res.Target, Effect: res.Effect,
}
d := m.decide(withRun(ctx, RunContext{RunID: req.RunID, Key: req.Key, Workflow: req.Workflow, Diagnosis: req.Diagnosis, Evidence: req.Evidence, Overlay: req.Overlay}), a)
@@ -314,7 +321,7 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
}
guards := slices.Clone(m.guards)
if m.extensions != nil {
for _, e := range m.extensions.Guards() {
for _, e := range m.extensions.Guards(ctx) {
guards = append(guards, extensionGuard{e})
}
}
@@ -402,7 +409,7 @@ func (m *Module) Execute(ctx context.Context, d Decision, input jsontext.Value,
// invoke runs the judged action. A failure, or an outcome nobody can confirm,
// drops the action type to propose and wait at once, whatever level it ran at.
func (m *Module) invoke(ctx context.Context, d Decision, input jsontext.Value, key string) (string, error) {
tool, ok := m.tools.Tool(d.Action.Connector)
tool, ok := m.tools.Installed(d.Action.Installation.ID.String())
if !ok {
return "", fmt.Errorf("%q isn't running", d.Action.Connector)
}
@@ -502,6 +509,7 @@ func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
row, err := m.store.Record(ctx, store.Decision{
ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key,
Connector: c.Connector, Action: c.Action, TargetKind: c.TargetKind, Environment: c.Environment,
InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope,
Level: d.Level.String(), Dry: d.Dry, Body: body,
})
if err != nil {
+5 -1
View File
@@ -136,13 +136,17 @@ func (t countingTool) Invoke(context.Context, connectors.Invocation) (string, er
return "done", nil
}
func (t countingTool) Installation() connectors.Installation { return connectors.Installation{} }
func (t countingTool) Resolve(context.Context, string, jsontext.Value) (connectors.Resolution, error) {
return connectors.Resolution{}, nil
}
type oneTool struct{ tool connectors.Tool }
func (o oneTool) Tool(string) (connectors.Tool, bool) { return o.tool, true }
func (o oneTool) Tool(context.Context, string) (connectors.Tool, bool) { return o.tool, true }
func (o oneTool) Installed(string) (connectors.Tool, bool) { return o.tool, true }
// TestExecuteRunsOnlyTheJudgedAction guards spec section 5 rule 6 and
// decision tree 8.5: an action runs only at a level that runs without
+1 -1
View File
@@ -47,7 +47,7 @@ func (m *Module) Judges(ctx context.Context) ([]JudgeControl, error) {
if m.extensions == nil {
return []JudgeControl{}, nil
}
guards := m.extensions.Guards()
guards := m.extensions.Guards(ctx)
out := make([]JudgeControl, 0, len(guards))
for _, g := range guards {
control := JudgeControl{
+2 -2
View File
@@ -40,8 +40,8 @@ func (j *decidingJudge) ForRun(context.Context, uuid.UUID) ([]judgement.Decision
type anyBox struct{}
func (anyBox) Declarations() []connectors.Declaration { return nil }
func (anyBox) Tool(string) (connectors.Tool, bool) { return nil, true }
func (anyBox) Declarations(context.Context) []connectors.Declaration { return nil }
func (anyBox) Tool(context.Context, string) (connectors.Tool, bool) { return nil, true }
// TestStartDryRefusesWhatCannotStart guards the dry-run entry point against
// testing a document a live run could not start: a declared identity or
+5 -5
View File
@@ -44,8 +44,8 @@ type Settings interface {
// Toolbox is where a workflow finds the connector lookups and actions and the
// MCP server tools it may offer an agent, and the tools that run them.
type Toolbox interface {
Declarations() []connectors.Declaration
Tool(name string) (connectors.Tool, bool)
Declarations(ctx context.Context) []connectors.Declaration
Tool(ctx context.Context, name string) (connectors.Tool, bool)
}
// Judge decides whether an agent's action runs, and runs only what it
@@ -347,8 +347,8 @@ func (d Deps) pin(rc *Context, p *progress, aliases []string, withMemory bool) e
return err
}
p.pin.instructions = instructions
decls, err := rc.Step("agent-tools", func(context.Context, string) ([]connectors.Declaration, error) {
return d.Toolbox.Declarations(), nil
decls, err := rc.Step("agent-tools", func(ctx context.Context, _ string) ([]connectors.Declaration, error) {
return d.Toolbox.Declarations(ctx), nil
})
if err != nil {
return err
@@ -938,7 +938,7 @@ func toolSet(box Toolbox, judge Judge, rc *Context, decls []connectors.Declarati
}
func call(ctx context.Context, box Toolbox, judge Judge, rc *Context, d connectors.Declaration, input jsontext.Value) (string, error) {
tool, ok := box.Tool(d.Connector)
tool, ok := box.Tool(ctx, d.Ref())
if !ok {
return "", fmt.Errorf("%q isn't running", d.Connector)
}
+2 -2
View File
@@ -107,7 +107,7 @@ func (investigateSettings) EscalationPath(context.Context, string, bool) ([]gove
// judge decides it, so the connector itself is never invoked.
type investigateBox struct{}
func (investigateBox) Declarations() []connectors.Declaration {
func (investigateBox) Declarations(context.Context) []connectors.Declaration {
return []connectors.Declaration{{
Connector: "host", Kind: connectors.KindAction, Name: "restart",
Description: "Restart a host",
@@ -115,7 +115,7 @@ func (investigateBox) Declarations() []connectors.Declaration {
}}
}
func (investigateBox) Tool(string) (connectors.Tool, bool) { return nil, true }
func (investigateBox) Tool(context.Context, string) (connectors.Tool, bool) { return nil, true }
// heldJudge is actionJudge with the real Execute contract for held actions: a
// held action is not run by the agent's tool call, only by an approval.
+2 -2
View File
@@ -40,9 +40,9 @@ func (j *countingJudge) ForRun(context.Context, uuid.UUID) ([]judgement.Decision
type stubBox struct{ tool connectors.Tool }
func (stubBox) Declarations() []connectors.Declaration { return nil }
func (stubBox) Declarations(context.Context) []connectors.Declaration { return nil }
func (b stubBox) Tool(string) (connectors.Tool, bool) { return b.tool, true }
func (b stubBox) Tool(context.Context, string) (connectors.Tool, bool) { return b.tool, true }
// TestActionStartedBeforeItsResultIsNeverRunAgain guards R15: a crash between
// a connector's effect and its recorded result leaves a started marker and no
+70 -2
View File
@@ -258,6 +258,15 @@ export const api = {
extensionKinds: () => request<ExtensionKindInfo[]>("/api/extension-kinds"),
extensions: (kind: ExtensionKind) => request<Extension[]>(`/api/${kind}`),
allExtensions: () => request<Extension[]>("/api/extensions"),
packages: () => request<PackageView[]>("/api/packages"),
createInstallation: (body: InstallationInput) =>
request<Extension>("/api/installations", { method: "POST", body, timeoutMs: 120_000 }),
updateInstallation: (id: string, body: InstallationUpdate) =>
request<Extension>(`/api/installations/${id}`, { method: "PUT", body, timeoutMs: 120_000 }),
removeInstallation: (id: string) =>
request<{ name: string; state: string }>(`/api/installations/${id}`, { method: "DELETE" }),
putInstallationOverride: (id: string, scope: "org" | "person", off: boolean) =>
request<{ name: string; state: string }>(`/api/installations/${id}/override`, { method: "PUT", body: { scope, off } }),
removeAnyExtension: (name: string) =>
request<{ name: string; state: string }>(`/api/extensions/${encodeURIComponent(name)}`, { method: "DELETE" }),
catalogue: () => request<CatalogueEntry[]>("/api/extensions/catalogue"),
@@ -286,8 +295,8 @@ export const api = {
request<{ name: string; state: string }>(`/api/${kind}/${encodeURIComponent(name)}`, { method: "DELETE" }),
credentials: () => request<Credential[]>("/api/credentials"),
credentialKinds: () => request<CredentialKind[]>("/api/credential-kinds"),
putCredential: (name: string, kind: string, fields: Record<string, CredentialField>) =>
request<{ name: string; kind: string; restarted: string[] }>(`/api/credentials/${encodeURIComponent(name)}`, { method: "PUT", body: { kind, fields }, timeoutMs: 60_000 }),
putCredential: (name: string, kind: string, fields: Record<string, CredentialField>, scope: ExtensionScope = "instance") =>
request<{ name: string; kind: string; scope: ExtensionScope; restarted: string[] }>(`/api/credentials/${encodeURIComponent(name)}`, { method: "PUT", body: { kind, fields, scope }, timeoutMs: 60_000 }),
orgSettings: () => request<OrgSettings>("/api/settings"),
putOrgSettings: (settings: OrgSettings) =>
request<OrgSettings>("/api/settings", { method: "PUT", body: settings }),
@@ -1084,11 +1093,17 @@ export interface StepType {
export type ExtensionGroup = "platform" | "integration" | "agent";
/** Who owns an installation or a credential: the instance, an organisation or
* a person. */
export type ExtensionScope = "instance" | "org" | "person";
/** An accepted-package kind, as the server lists it: the path segment of its API. */
export type ExtensionKind = string;
export interface ExtensionKindInfo {
kind: ExtensionKind;
/** The package contract this kind accepts. */
contract: string;
label: string;
singular: string;
group: ExtensionGroup;
@@ -1122,7 +1137,22 @@ export interface Capabilities {
}
export interface Extension {
/** The installation's ID, which a decision records. */
id: string;
name: string;
/** The package the installation configures. */
package: string;
scope: ExtensionScope;
/** The organisation or person that owns the installation; empty for the instance. */
owner_id?: string;
/** Whether the caller may change the installation. */
editable: boolean;
/** Whether the caller's organisation or person switched an inherited installation off. */
overridden: boolean;
/** The caller's scopes that switched it off. */
overridden_by?: ExtensionScope[];
/** The scopes the caller may switch an inherited installation off at. */
can_override?: ExtensionScope[];
state: string;
error?: string;
path?: string;
@@ -1156,6 +1186,43 @@ export interface Extension {
update_policy?: "manual" | "auto";
}
/** One package the instance accepted: the binary and manifest, without the
* configuration an installation gives it. */
export interface PackageView {
id: string;
name: string;
contract: string;
group: ExtensionGroup;
display_name?: string;
description?: string;
version?: string;
digest: string;
/** Installed from the catalogue rather than accepted by path. */
managed: boolean;
/** Whether the instance accepted the package's grants, so another scope can install it. */
installed: boolean;
accepted_at: string;
}
/** One installation's configuration. A create names the package and the scope
* that owns it; an update changes only what the installation is configured
* with. */
export interface InstallationInput {
package: string;
name?: string;
scope: ExtensionScope;
settings?: Record<string, string>;
egress?: string[];
env?: string[];
credentials?: Record<string, string>;
args?: string[];
url?: string;
tools?: unknown;
enabled: boolean;
}
export type InstallationUpdate = Omit<InstallationInput, "package" | "name" | "scope">;
/** What an extension may use: hosts it reaches, host variables it sees and
* credential slots it is configured with. */
export interface Grants {
@@ -1255,6 +1322,7 @@ export interface OrgSettings {
export interface Credential {
name: string;
kind: string;
scope: ExtensionScope;
/** Per field: "stored", or "engine:key" for one a secret engine resolves. */
fields: Record<string, string>;
}
+29 -4
View File
@@ -18,8 +18,9 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { errors } from "@/copy/errors";
import { api, describeError, type Credential, type CredentialField } from "@/lib/api";
import { api, describeError, type Credential, type CredentialField, type ExtensionScope } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { useOrgStore } from "@/stores/org";
/** Credentials are sealed and never read back: the list says only where each
* field comes from, and a save replaces every field. */
@@ -35,17 +36,32 @@ onMounted(() => {
const columns: DataTableColumn<Credential>[] = [
{ id: "name", label: "Credential", fixed: true, sort: (c) => c.name },
{ id: "kind", label: "Kind", hide: "sm", width: "10rem", sort: (c) => c.kind },
{ id: "scope", label: "Scope", hide: "sm", width: "9rem", sort: (c) => c.scope },
{ id: "fields", label: "Fields", hide: "md", width: "24rem" },
];
const scopeLabels: Record<ExtensionScope, string> = { instance: "Instance", org: "Organisation", person: "Person" };
const org = useOrgStore();
onMounted(org.loadOrg);
// Who may own a new credential: the instance when the caller administers it,
// their organisation when they own it, and always themselves.
const scopes = computed<ExtensionScope[]>(() => {
const out: ExtensionScope[] = [];
if (org.instanceAdmin) out.push("instance");
if (org.org?.role === "owner") out.push("org");
out.push("person");
return out;
});
interface FieldForm { from: "value" | "engine"; value: string; engine: string; key: string }
const editing = ref(false);
const isNew = ref(true);
const name = ref("");
const kind = ref("");
const scope = ref<ExtensionScope>("instance");
const fields = ref<Record<string, FieldForm>>({});
const kindSpec = computed(() => kinds.data.value?.find((k) => k.kind === kind.value));
const fieldNames = computed(() => [...(kindSpec.value?.required ?? []), ...(kindSpec.value?.optional ?? [])]);
const availableEngines = computed(() => (engines.data.value ?? []).filter((e) => e.scope === "instance" || e.scope === scope.value));
function pickKind(next: unknown): void {
kind.value = String(next);
fields.value = Object.fromEntries(fieldNames.value.map((f) => [f, fields.value[f] ?? { from: "value", value: "", engine: "", key: "" }]));
@@ -54,6 +70,7 @@ function open(cred?: Credential): void {
isNew.value = !cred;
actionError.value = "";
name.value = cred?.name ?? "";
scope.value = cred?.scope ?? "instance";
fields.value = {};
for (const [field, from] of Object.entries(cred?.fields ?? {})) {
const at = from.indexOf(":");
@@ -80,7 +97,7 @@ async function submit(): Promise<void> {
else if (f.from === "value" && f.value) body[field] = { value: f.value };
}
try {
restarted.value = (await api.putCredential(name.value.trim(), kind.value, body)).restarted ?? [];
restarted.value = (await api.putCredential(name.value.trim(), kind.value, body, scope.value)).restarted ?? [];
editing.value = false;
} catch (cause) {
actionError.value = describeError(cause, errors.common.unknown);
@@ -102,6 +119,7 @@ async function submit(): Promise<void> {
<DataTable v-else :columns="columns" :rows="data" :row-key="(c) => c.name" storage-key="credentials">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
<template #cell-kind="{ row }"><Badge variant="outline">{{ row.kind }}</Badge></template>
<template #cell-scope="{ row }"><Badge variant="outline">{{ scopeLabels[row.scope] }}</Badge></template>
<template #cell-fields="{ row }">
<span class="font-mono text-caption">{{ Object.entries(row.fields).map(([f, from]) => from === "stored" ? f : `${f} ← ${from}`).join(", ") }}</span>
</template>
@@ -122,16 +140,23 @@ async function submit(): Promise<void> {
<SelectContent><SelectItem v-for="k in kinds.data.value ?? []" :key="k.kind" :value="k.kind">{{ k.kind }}</SelectItem></SelectContent>
</Select>
</SettingRow>
<SettingRow label="Scope" for="cred-scope" hint="Who owns the credential. Installations resolve the person's, then the organisation's, then the instance's.">
<Select v-if="isNew" v-model="scope">
<SelectTrigger id="cred-scope" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem v-for="value in scopes" :key="value" :value="value">{{ scopeLabels[value] }}</SelectItem></SelectContent>
</Select>
<span v-else class="text-label">{{ scopeLabels[scope] }}</span>
</SettingRow>
<SettingRow v-for="field in fieldNames" :key="field" :label="field" :for="`cred-${field}`" :hint="optional(field) ? 'Optional' : undefined">
<div class="space-y-2">
<ToggleGroup v-if="engines.data.value?.length" v-model="fields[field].from" type="single" variant="outline" size="sm" :aria-label="`${field} from`">
<ToggleGroup v-if="availableEngines.length" v-model="fields[field].from" type="single" variant="outline" size="sm" :aria-label="`${field} from`">
<ToggleGroupItem value="value">Value</ToggleGroupItem>
<ToggleGroupItem value="engine">Secret engine</ToggleGroupItem>
</ToggleGroup>
<template v-if="fields[field].from === 'engine'">
<Select v-model="fields[field].engine">
<SelectTrigger class="w-full" :aria-label="`${field} engine`"><SelectValue placeholder="Engine" /></SelectTrigger>
<SelectContent><SelectItem v-for="e in engines.data.value ?? []" :key="e.name" :value="e.name">{{ e.name }}</SelectItem></SelectContent>
<SelectContent><SelectItem v-for="e in availableEngines" :key="e.name" :value="e.name">{{ e.name }}</SelectItem></SelectContent>
</Select>
<Input v-model="fields[field].key" :aria-label="`${field} key`" placeholder="Key" class="font-mono" :required="!optional(field)" />
</template>
-226
View File
@@ -1,226 +0,0 @@
<script setup lang="ts">
import { Plus } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { MoreMenu } from "@/components/ui/more-menu";
import { ReadError } from "@/components/ui/read-error";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SettingRow } from "@/components/ui/setting-row";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { errors } from "@/copy/errors";
import { api, describeError, type Extension, type ExtensionInput, type ExtensionKind } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { stateTone } from "@/runs/state";
import { fromLines, toLines } from "@/lib/lines";
/** The packages of one kind the binary runs: each is accepted by path and
* digest, and runs only while its digest matches. */
const props = defineProps<{ kind: ExtensionKind; noun: string }>();
const { data, error, reload } = useRead(() => api.extensions(props.kind));
onMounted(reload);
const columns = computed<DataTableColumn<Extension>[]>(() => [
{ id: "name", label: "Name", fixed: true, sort: (e) => e.name },
{ id: "state", label: "State", fixed: true, width: "9rem", sort: (e) => e.state },
{ id: "version", label: "Version", hide: "sm", width: "8rem", sort: (e) => e.version ?? "" },
...(props.kind === "connectors" ? [{ id: "capabilities", label: "Declares", hide: "md" as const, width: "14rem" }] : []),
{ id: "path", label: "Path", hidden: true, hide: "md", width: "18rem" },
{ id: "egress", label: "Egress", hidden: true, hide: "md", width: "14rem" },
]);
const CAPABILITY_GROUPS = [
{ key: "events", label: "Events" },
{ key: "actions", label: "Actions" },
{ key: "deliveries", label: "Deliveries" },
{ key: "lookups", label: "Lookups" },
] as const;
function declared(ext: Extension) {
return CAPABILITY_GROUPS.map((g) => ({ ...g, items: ext.capabilities?.[g.key] ?? [] })).filter((g) => g.items.length);
}
const mcp = computed(() => props.kind === "mcp-servers");
/** What an operator declares about an MCP server's tools. Chat offers a server
* only when its effects are declared and neither one applies. */
const EFFECT_OPTIONS = [
{ value: "unset", label: "Not declared", effects: undefined },
{ value: "none", label: "No privileged effects", effects: { privilege_change: false, secret_access: false } },
{ value: "privilege_change", label: "Changes privileges", effects: { privilege_change: true, secret_access: false } },
{ value: "secret_access", label: "Accesses secrets", effects: { privilege_change: false, secret_access: true } },
{ value: "both", label: "Changes privileges and accesses secrets", effects: { privilege_change: true, secret_access: true } },
] as const;
function effectOf(ext?: Extension): string {
const e = ext?.effects;
if (!e) return "unset";
if (e.privilege_change && e.secret_access) return "both";
return e.privilege_change ? "privilege_change" : e.secret_access ? "secret_access" : "none";
}
const editing = ref(false);
const isNew = ref(true);
const schema = ref<Extension["settings_schema"]>([]);
const form = ref({ name: "", path: "", sha256: "", url: "", args: "", egress: "", env: "", credentials: "", tools: "", effects: "unset", settings: {} as Record<string, string>, other: "" });
function open(ext?: Extension): void {
isNew.value = !ext;
actionError.value = "";
schema.value = ext?.settings_schema ?? [];
const known = new Set(schema.value.map((f) => f.key));
const settings = ext?.settings ?? {};
form.value = {
name: ext?.name ?? "",
path: ext?.path ?? "",
sha256: ext?.digest ?? "",
url: ext?.url ?? "",
args: (ext?.args ?? []).join("\n"),
egress: (ext?.egress ?? []).join("\n"),
env: (ext?.env ?? []).join("\n"),
credentials: toLines(ext?.credentials ?? {}),
tools: ext?.tools ? JSON.stringify(ext.tools, null, 2) : "[]",
effects: effectOf(ext),
settings: Object.fromEntries(Object.entries(settings).filter(([k]) => known.has(k))),
other: toLines(Object.fromEntries(Object.entries(settings).filter(([k]) => !known.has(k)))),
};
editing.value = true;
}
const list = (text: string) => text.split("\n").map((l) => l.trim()).filter(Boolean);
const busy = ref(false);
const actionError = ref("");
async function submit(): Promise<void> {
const f = form.value;
busy.value = true;
actionError.value = "";
try {
const settings = { ...fromLines(f.other), ...Object.fromEntries(Object.entries(f.settings).filter(([, v]) => v !== "")) };
const body: ExtensionInput = {
path: f.path.trim() || undefined,
sha256: f.sha256.trim() || undefined,
egress: list(f.egress),
env: list(f.env),
settings,
credentials: fromLines(f.credentials),
};
if (mcp.value) {
body.url = f.url.trim() || undefined;
body.args = list(f.args);
body.tools = JSON.parse(f.tools || "[]");
body.effects = EFFECT_OPTIONS.find((o) => o.value === f.effects)?.effects;
}
await api.acceptExtension(props.kind, f.name.trim(), body);
editing.value = false;
} catch (cause) {
actionError.value = cause instanceof SyntaxError ? `Tools: ${cause.message}` : describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
await reload();
}
}
const removing = ref<Extension | null>(null);
async function remove(): Promise<void> {
if (!removing.value) return;
busy.value = true;
actionError.value = "";
try {
await api.removeExtension(props.kind, removing.value.name);
} catch (cause) {
actionError.value = describeError(cause, errors.common.unknown);
} finally {
removing.value = null;
busy.value = false;
await reload();
}
}
</script>
<template>
<div>
<p v-if="actionError && !editing" role="alert" class="mb-2 text-caption text-danger">{{ actionError }}</p>
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<div v-else-if="!data" role="status" :aria-label="`Loading ${noun}s`" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<template v-else>
<div class="mb-2 flex justify-end">
<Button size="icon-sm" variant="ghost" :aria-label="`Add ${noun}`" :title="`Add ${noun}`" @click="open()"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="data" :row-key="(e) => e.name" :storage-key="`extensions-${kind}`">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
<template #cell-state="{ row }">
<Badge :variant="stateTone(row.state === 'running' ? 'succeeded' : row.state)" :title="row.error || undefined">{{ row.state }}</Badge>
<p v-if="row.error" class="mt-1 text-caption text-danger">{{ row.error }}</p>
</template>
<template #cell-version="{ row }">{{ row.version }}</template>
<template #cell-capabilities="{ row }">
<dl v-for="group in declared(row)" :key="group.key" class="mb-1 text-caption">
<dt class="text-fg-subtle">{{ group.label }}</dt>
<dd v-for="item in group.items" :key="item.name"><span class="font-mono">{{ item.name }}</span><span v-if="item.description" class="text-fg-subtle"> {{ item.description }}</span></dd>
</dl>
</template>
<template #cell-path="{ row }"><span class="font-mono text-caption [overflow-wrap:anywhere]">{{ row.path || row.url }}</span></template>
<template #cell-egress="{ row }"><span class="font-mono text-caption">{{ (row.egress ?? []).join(", ") }}</span></template>
<template #actions="{ row }">
<MoreMenu :label="`${row.name} actions`">
<DropdownMenuItem v-if="!row.managed" @select="open(row)">Edit</DropdownMenuItem>
<DropdownMenuItem class="text-danger" @select="removing = row">Remove</DropdownMenuItem>
</MoreMenu>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No {{ noun }}s</EmptyTitle></EmptyHeader></Empty></template>
</DataTable>
</template>
<Dialog v-model:open="editing">
<DialogContent class="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
<DialogHeader><DialogTitle>{{ isNew ? `Add ${noun}` : `Edit ${form.name}` }}</DialogTitle></DialogHeader>
<form :id="`extension-${kind}`" @submit.prevent="submit">
<SettingRow v-if="isNew" label="Name" for="ext-name"><Input id="ext-name" v-model="form.name" pattern="[a-z0-9][a-z0-9-]*" required /></SettingRow>
<SettingRow label="Path" for="ext-path" hint="The binary on this host."><Input id="ext-path" v-model="form.path" class="font-mono" :required="!mcp" /></SettingRow>
<SettingRow label="SHA-256" for="ext-sha" hint="It runs only while the binary has this digest."><Input id="ext-sha" v-model="form.sha256" class="font-mono" :required="!mcp" /></SettingRow>
<template v-if="mcp">
<SettingRow label="URL" for="ext-url" hint="For a server reached over HTTP instead of run from a path."><Input id="ext-url" v-model="form.url" type="url" /></SettingRow>
<SettingRow label="Arguments" for="ext-args" hint="One per line."><Textarea id="ext-args" v-model="form.args" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Tools" for="ext-tools" hint="The tools it may offer, as JSON: name, kind, read_only, reversibility, summary."><Textarea id="ext-tools" v-model="form.tools" class="font-mono" rows="5" /></SettingRow>
</template>
<SettingRow v-if="mcp" label="Effects" for="ext-effects" hint="Chat offers a server only once this says its tools change no privileges and access no secrets.">
<Select v-model="form.effects">
<SelectTrigger id="ext-effects" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem v-for="o in EFFECT_OPTIONS" :key="o.value" :value="o.value">{{ o.label }}</SelectItem></SelectContent>
</Select>
</SettingRow>
<SettingRow v-for="field in schema" :key="field.key" :label="field.label || field.key" :for="`ext-set-${field.key}`" :hint="field.description">
<Select v-if="field.options?.length" v-model="form.settings[field.key]">
<SelectTrigger :id="`ext-set-${field.key}`" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem v-for="o in field.options" :key="o" :value="o">{{ o }}</SelectItem></SelectContent>
</Select>
<Input v-else :id="`ext-set-${field.key}`" v-model="form.settings[field.key]" :required="field.required" :placeholder="field.secret ? 'engine:key' : undefined" />
</SettingRow>
<SettingRow :label="schema?.length ? 'Other settings' : 'Settings'" for="ext-settings" hint="key=value, one per line. A key ending in _ref takes engine:key."><Textarea id="ext-settings" v-model="form.other" class="font-mono" rows="3" /></SettingRow>
<SettingRow label="Credentials" for="ext-creds" hint="slot=credential, one per line."><Textarea id="ext-creds" v-model="form.credentials" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Egress" for="ext-egress" hint="Hosts it may reach, one per line."><Textarea id="ext-egress" v-model="form.egress" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Environment" for="ext-env" hint="Host variables it may see, one per line."><Textarea id="ext-env" v-model="form.env" class="font-mono" rows="2" /></SettingRow>
<p v-if="actionError" role="alert" class="pt-2 text-caption text-danger">{{ actionError }}</p>
</form>
<DialogFooter><Button type="submit" :form="`extension-${kind}`" :disabled="busy">{{ isNew ? "Accept and start" : "Save and restart" }}</Button></DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog :open="!!removing" @update:open="(o) => { if (!o) removing = null; }">
<AlertDialogContent>
<AlertDialogHeader><AlertDialogTitle>Stop and remove {{ removing?.name }}?</AlertDialogTitle></AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction :disabled="busy" @click="remove">Remove</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
+240 -141
View File
@@ -4,7 +4,7 @@ import { ReadError } from "@/components/ui/read-error";
import { Item, ItemGroup } from "@/components/ui/item";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, onMounted, ref, watch } from "vue";
import { ChevronRight, Plus, Settings2, Trash2 } from "@lucide/vue";
import { ChevronRight, Pencil, Plus, Settings2, Trash2 } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import {
@@ -21,9 +21,11 @@ import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Card } from "@/components/ui/card";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { MoreMenu } from "@/components/ui/more-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SettingRow } from "@/components/ui/setting-row";
import { Switch } from "@/components/ui/switch";
@@ -31,16 +33,20 @@ import { Section } from "@/components/ui/section";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { grants, stage, useExtensionsStore } from "@/stores/extensions";
import { api, type Extension, type SettingField } from "@/lib/api";
import { useOrgStore } from "@/stores/org";
import { api, type Extension, type ExtensionScope, type SettingField } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { fromLines, toLines } from "@/lib/lines";
import ExtensionList from "./ExtensionList.vue";
import { stateTone } from "@/runs/state";
import InstallationDialog from "./InstallationDialog.vue";
import PackageList from "./PackageList.vue";
import ExtensionsMarketplace from "./ExtensionsMarketplace.vue";
const store = useExtensionsStore();
const org = useOrgStore();
const loading = ref(true);
onMounted(async () => {
await store.load();
await Promise.all([store.load(), org.loadOrg()]);
loading.value = false;
});
@@ -48,6 +54,17 @@ onMounted(async () => {
// catalogue pins a different digest than the one installed.
const updates = computed(() => new Map(store.catalogue.filter((entry) => entry.update_available).map((entry) => [entry.name, entry])));
// A new installation may be owned by the instance when the caller administers
// it, by their organisation when they own it, and always by themselves.
const scopes = computed<ExtensionScope[]>(() => {
const out: ExtensionScope[] = [];
if (org.instanceAdmin) out.push("instance");
if (org.org?.role === "owner") out.push("org");
out.push("person");
return out;
});
const scopeLabels: Record<ExtensionScope, string> = { instance: "Instance", org: "Organisation", person: "Person" };
const sourceLocation = ref("");
const sourceKey = ref("");
watch(
@@ -65,10 +82,10 @@ async function saveSource(): Promise<void> {
}
}
// Credentials a declared slot may resolve through.
// Credentials a declared slot may resolve through at the instance scope.
const credentials = useRead(() => api.credentials());
onMounted(credentials.reload);
const credentialNames = computed(() => (credentials.data.value ?? []).map((c) => c.name));
const instanceCredentials = computed(() => (credentials.data.value ?? []).filter((c) => c.scope === "instance").map((c) => c.name));
// The dialog's action closes it before its click handler runs, so the target
// outlives the open flag rather than being cleared on close.
@@ -91,6 +108,41 @@ async function accept(): Promise<void> {
});
}
// A managed package's instance installation changes through its lifecycle
// routes; every other installation changes through its own configuration.
const managedInstance = (extension: Extension) => extension.editable && extension.managed === true && extension.scope === "instance";
const installation = ref<Extension | null>(null);
const installationOpen = ref(false);
function openInstallation(extension: Extension | null = null): void {
installation.value = extension;
installationOpen.value = true;
}
async function reload(): Promise<void> {
await store.load();
}
async function setEnabled(extension: Extension, enabled: boolean): Promise<void> {
await store.updateInstallation(extension.id, {
settings: extension.settings,
egress: extension.egress,
env: extension.env,
credentials: extension.credentials,
args: extension.args ?? [],
url: extension.url ?? "",
tools: extension.tools ?? [],
enabled,
});
}
async function overrideInstallation(extension: Extension, scope: "org" | "person", off: boolean): Promise<void> {
await store.overrideInstallation(extension.id, scope, off);
}
function overrideScope(extension: Extension, scope: ExtensionScope, off: boolean): Promise<void> {
return scope === "org" || scope === "person" ? overrideInstallation(extension, scope, off) : Promise.resolve();
}
const editing = ref<Extension | null>(null);
const settingsOpen = ref(false);
const schema = ref<SettingField[]>([]);
@@ -114,9 +166,17 @@ async function saveSettings(): Promise<void> {
}
const removing = ref<Extension | null>(null);
const removeOpen = ref(false);
const removePackage = ref(false);
function askRemove(extension: Extension): void {
removing.value = extension;
// An instance installation is what makes the package usable, so removing it
// removes the package too. A narrower installation is its own configuration.
removePackage.value = extension.scope === "instance";
}
async function remove(): Promise<void> {
if (removing.value) await store.remove(removing.value.name);
if (!removing.value) return;
if (removePackage.value) await store.remove(removing.value.name);
else await store.removeInstallation(removing.value.id);
}
const tones = {
@@ -125,11 +185,11 @@ const tones = {
enabled: { tone: undefined, label: "" },
} as const;
// Path-accepted packages keep their editor: one tab lists each kind.
// Packages are accepted per kind; the tab lists one kind at a time.
const kinds = useRead(() => api.extensionKinds());
onMounted(kinds.reload);
const pathGroups = computed(() => {
const byGroup = new Map<string, { id: string; label: string; kinds: { kind: string; label: string; singular: string }[] }>();
const byGroup = new Map<string, { id: string; label: string; kinds: { kind: string; label: string; singular: string; contract: string }[] }>();
for (const kind of kinds.data.value ?? []) {
const group = byGroup.get(kind.group) ?? { id: kind.group, label: kind.group[0]!.toUpperCase() + kind.group.slice(1), kinds: [] };
group.kinds.push(kind);
@@ -147,125 +207,178 @@ const active = computed(() => (kinds.data.value ?? []).find((kind) => kind.kind
<Alert v-if="store.error" variant="destructive" class="mb-4"><AlertDescription>{{ store.error }}</AlertDescription></Alert>
<Tabs default-value="installed" class="space-y-4">
<Tabs default-value="installations" class="space-y-4">
<TabsList>
<TabsTrigger value="installed">Installed</TabsTrigger>
<TabsTrigger value="installations">Installations</TabsTrigger>
<TabsTrigger value="packages">Packages</TabsTrigger>
<TabsTrigger value="marketplace">Marketplace</TabsTrigger>
<TabsTrigger value="path">By path</TabsTrigger>
</TabsList>
<TabsContent value="installed">
<TabsContent value="installations">
<Section>
<ItemGroup aria-label="Extensions">
<Item v-for="extension in store.extensions" :key="extension.name" as="li" variant="outline">
<div class="min-w-0 w-full @3xl:w-auto @3xl:flex-1">
<p class="truncate text-label font-medium">
{{ extension.display_name || extension.name }}
<span class="font-mono text-caption text-fg-subtle">{{ extension.version }}</span>
</p>
<p v-if="extension.description" class="text-caption text-fg-subtle">{{ extension.description }}</p>
<p class="truncate font-mono text-caption text-fg-subtle">{{ extension.digest }}</p>
<Collapsible v-if="extension.declared">
<CollapsibleTrigger as-child>
<Button variant="ghost" size="sm" class="-ml-2 h-6 px-2 text-caption font-normal text-fg-subtle">
<ChevronRight class="transition-transform group-data-[state=open]/button:rotate-90" />
Declared authority
<div class="mb-2 flex justify-end">
<Button size="icon-sm" variant="ghost" aria-label="New installation" title="New installation" @click="openInstallation()"><Plus /></Button>
</div>
<ItemGroup aria-label="Installations">
<Item v-for="extension in store.extensions" :key="extension.id" as="li" variant="outline">
<div class="min-w-0 w-full @3xl:w-auto @3xl:flex-1">
<p class="truncate text-label font-medium">
{{ extension.display_name || extension.name }}
<span class="font-mono text-caption text-fg-subtle">{{ extension.version }}</span>
</p>
<p v-if="extension.package !== extension.name" class="truncate font-mono text-caption text-fg-subtle">{{ extension.package }}</p>
<p v-if="extension.description" class="text-caption text-fg-subtle">{{ extension.description }}</p>
<p class="truncate font-mono text-caption text-fg-subtle">{{ extension.digest }}</p>
<Collapsible v-if="extension.declared">
<CollapsibleTrigger as-child>
<Button variant="ghost" size="sm" class="-ml-2 h-6 px-2 text-caption font-normal text-fg-subtle">
<ChevronRight class="transition-transform group-data-[state=open]/button:rotate-90" />
Declared authority
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<ul class="font-mono text-caption text-fg-subtle">
<li v-for="line in grants(extension.declared)" :key="line">{{ line }}</li>
</ul>
</CollapsibleContent>
</Collapsible>
<Collapsible v-if="extension.accepted">
<CollapsibleTrigger as-child>
<Button variant="ghost" size="sm" class="-ml-2 h-6 px-2 text-caption font-normal text-fg-subtle">
<ChevronRight class="transition-transform group-data-[state=open]/button:rotate-90" />
Accepted authority
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<ul class="font-mono text-caption text-fg-subtle">
<li v-for="line in grants(extension.accepted)" :key="line">{{ line }}</li>
</ul>
</CollapsibleContent>
</Collapsible>
</div>
<Badge variant="outline">{{ scopeLabels[extension.scope] }}</Badge>
<Badge v-if="extension.overridden" variant="idle">Switched off</Badge>
<Badge v-if="tones[stage(extension)].tone" :variant="tones[stage(extension)].tone">{{ tones[stage(extension)].label }}</Badge>
<Badge :variant="stateTone(extension.state === 'running' ? 'succeeded' : extension.state)" :title="extension.error || undefined">{{ extension.state }}</Badge>
<Card v-if="extension.pending" size="sm" class="w-full">
<p class="text-caption font-medium">Update awaiting approval. It adds:</p>
<ul class="font-mono text-caption">
<li v-for="line in grants(extension.pending.added).filter((line) => !line.startsWith('network:'))" :key="line">{{ line }}</li>
</ul>
<Button v-if="managedInstance(extension)" size="sm" class="mt-2" :disabled="!!store.busy" @click="store.approveUpdate(extension.name)">Approve</Button>
</Card>
<Button
v-if="managedInstance(extension) && updates.has(extension.name) && !extension.pending"
variant="outline"
size="sm"
:disabled="!!store.busy"
@click="store.update(extension.name)"
>Update to {{ updates.get(extension.name)?.version }}</Button
>
<Switch
v-if="managedInstance(extension)"
:model-value="extension.update_policy === 'auto'"
:disabled="!!store.busy"
:aria-label="`Auto-update ${extension.name}`"
@update:model-value="(value: boolean) => store.setUpdatePolicy(extension.name, value ? 'auto' : 'manual')"
/>
<Button v-if="managedInstance(extension) && extension.can_rollback" variant="ghost" size="sm" :disabled="!!store.busy" @click="store.rollback(extension.name)"
>Roll back</Button
>
<Button
v-if="managedInstance(extension) && stage(extension) === 'accept'"
variant="ghost"
size="sm"
:disabled="!!store.busy"
@click="openAccept(extension)"
>Review authority</Button
>
<Switch
v-if="extension.editable && !managedInstance(extension)"
:model-value="!!extension.enabled"
:disabled="!!store.busy"
:aria-label="`Enable ${extension.name}`"
@update:model-value="(value: boolean) => setEnabled(extension, value)"
/>
<Switch
v-if="managedInstance(extension) && stage(extension) !== 'accept'"
:model-value="!!extension.enabled"
:disabled="!!store.busy"
:aria-label="`Enable ${extension.name}`"
@update:model-value="(value: boolean) => store.setEnabled(extension.name, value)"
/>
<Tooltip v-if="extension.editable">
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon"
:aria-label="`Edit ${extension.name}`"
:disabled="!!store.busy"
@click="managedInstance(extension) ? openSettings(extension) : openInstallation(extension)"
>
<Settings2 v-if="managedInstance(extension)" /><Pencil v-else />
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<ul class="font-mono text-caption text-fg-subtle">
<li v-for="line in grants(extension.declared)" :key="line">{{ line }}</li>
</ul>
</CollapsibleContent>
</Collapsible>
<Collapsible v-if="extension.accepted">
<CollapsibleTrigger as-child>
<Button variant="ghost" size="sm" class="-ml-2 h-6 px-2 text-caption font-normal text-fg-subtle">
<ChevronRight class="transition-transform group-data-[state=open]/button:rotate-90" />
Accepted authority
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<ul class="font-mono text-caption text-fg-subtle">
<li v-for="line in grants(extension.accepted)" :key="line">{{ line }}</li>
</ul>
</CollapsibleContent>
</Collapsible>
</div>
<Badge v-if="tones[stage(extension)].tone" :variant="tones[stage(extension)].tone">{{ tones[stage(extension)].label }}</Badge>
<Card v-if="extension.pending" size="sm" class="w-full">
<p class="text-caption font-medium">Update awaiting approval. It adds:</p>
<ul class="font-mono text-caption">
<li v-for="line in grants(extension.pending.added).filter((line) => !line.startsWith('network:'))" :key="line">{{ line }}</li>
</ul>
<Button size="sm" class="mt-2" :disabled="!!store.busy" @click="store.approveUpdate(extension.name)">Approve</Button>
</Card>
<Button
v-if="updates.has(extension.name) && !extension.pending"
variant="outline"
size="sm"
:disabled="!!store.busy"
@click="store.update(extension.name)"
>Update to {{ updates.get(extension.name)?.version }}</Button
>
<Switch
v-if="extension.managed"
:model-value="extension.update_policy === 'auto'"
:disabled="!!store.busy"
:aria-label="`Auto-update ${extension.name}`"
@update:model-value="(value: boolean) => store.setUpdatePolicy(extension.name, value ? 'auto' : 'manual')"
/>
<Button v-if="extension.can_rollback" variant="ghost" size="sm" :disabled="!!store.busy" @click="store.rollback(extension.name)"
>Roll back</Button
>
<Button
v-if="stage(extension) === 'accept'"
variant="ghost"
size="sm"
:disabled="!!store.busy"
@click="openAccept(extension)"
>Review authority</Button
>
<Switch
v-else-if="extension.managed"
:model-value="!!extension.enabled"
:disabled="!!store.busy"
:aria-label="`Enable ${extension.name}`"
@update:model-value="(value: boolean) => store.setEnabled(extension.name, value)"
/>
<Tooltip v-if="extension.managed">
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" :aria-label="`Settings for ${extension.name}`" :disabled="!!store.busy" @click="openSettings(extension)"
><Settings2
/></Button>
</TooltipTrigger>
<TooltipContent>Settings</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon"
:aria-label="`Remove ${extension.name}`"
:disabled="!!store.busy"
@click="(removing = extension), (removeOpen = true)"
><Trash2
/></Button>
</TooltipTrigger>
<TooltipContent>Remove</TooltipContent>
</Tooltip>
</Item>
<li v-if="loading" class="py-3 text-label text-fg-muted" role="status">Loading extensions…</li>
<li v-else-if="!store.extensions.length && !store.error">
<Empty class="py-6">
<EmptyHeader>
<EmptyTitle>Nothing installed</EmptyTitle>
</EmptyHeader>
</Empty>
</li>
</ItemGroup>
</TooltipTrigger>
<TooltipContent>{{ managedInstance(extension) ? "Settings" : "Edit" }}</TooltipContent>
</Tooltip>
<MoreMenu
v-if="!extension.editable && ((extension.overridden_by?.length ?? 0) > 0 || (extension.can_override?.length ?? 0) > 0)"
:label="`${extension.name} use`"
>
<template v-for="scope in extension.overridden_by ?? []" :key="`restore-${scope}`">
<DropdownMenuItem @select="overrideScope(extension, scope, false)"
>Use again {{ scope === 'org' ? 'for the organisation' : 'for me' }}</DropdownMenuItem
>
</template>
<template v-for="scope in extension.can_override ?? []" :key="`off-${scope}`">
<DropdownMenuItem v-if="!(extension.overridden_by?.length)" @select="overrideScope(extension, scope, true)"
>Switch off {{ scope === 'org' ? 'for the organisation' : 'for me' }}</DropdownMenuItem
>
</template>
</MoreMenu>
<Tooltip v-if="extension.editable">
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon"
:aria-label="`Remove ${extension.name}`"
:disabled="!!store.busy"
@click="askRemove(extension)"
><Trash2
/></Button>
</TooltipTrigger>
<TooltipContent>Remove</TooltipContent>
</Tooltip>
</Item>
<li v-if="loading" class="py-3 text-label text-fg-muted" role="status">Loading installations…</li>
<li v-else-if="!store.extensions.length && !store.error">
<Empty class="py-6">
<EmptyHeader>
<EmptyTitle>Nothing installed</EmptyTitle>
</EmptyHeader>
</Empty>
</li>
</ItemGroup>
</Section>
</TabsContent>
<TabsContent value="packages">
<ReadError v-if="kinds.error.value" :message="kinds.error.value" retry-label="Retry" @retry="kinds.reload" />
<template v-else-if="active">
<Tabs :model-value="active.kind" class="mb-4" @update:model-value="(value) => (activeKind = String(value))">
<div class="flex flex-wrap gap-x-6 gap-y-3">
<div v-for="group in pathGroups" :key="group.id">
<h2 class="mb-1 text-caption text-fg-subtle">{{ group.label }}</h2>
<TabsList variant="line" class="justify-start">
<TabsTrigger v-for="kind in group.kinds" :key="kind.kind" :value="kind.kind" class="flex-none px-3">{{ kind.label }}</TabsTrigger>
</TabsList>
</div>
</div>
</Tabs>
<PackageList :key="active.kind" :kind="active.kind" :contract="active.contract" :noun="active.singular" />
</template>
</TabsContent>
<TabsContent value="marketplace">
<Collapsible class="mb-3" default-open>
<CollapsibleTrigger class="cursor-pointer text-caption text-fg-muted">Catalogue source</CollapsibleTrigger>
@@ -280,25 +393,10 @@ const active = computed(() => (kinds.data.value ?? []).find((kind) => kind.kind
<ReadError v-if="store.catalogueError" :message="store.catalogueError" retry-label="Retry" @retry="store.load()" />
<ExtensionsMarketplace v-else :updates="updates" />
</TabsContent>
<TabsContent value="path">
<ReadError v-if="kinds.error.value" :message="kinds.error.value" retry-label="Retry" @retry="kinds.reload" />
<template v-else-if="active">
<Tabs :model-value="active.kind" class="mb-4" @update:model-value="(value) => (activeKind = String(value))">
<div class="flex flex-wrap gap-x-6 gap-y-3">
<div v-for="group in pathGroups" :key="group.id">
<h2 class="mb-1 text-caption text-fg-subtle">{{ group.label }}</h2>
<TabsList variant="line" class="justify-start">
<TabsTrigger v-for="kind in group.kinds" :key="kind.kind" :value="kind.kind" class="flex-none px-3">{{ kind.label }}</TabsTrigger>
</TabsList>
</div>
</div>
</Tabs>
<ExtensionList :key="active.kind" :kind="active.kind" :noun="active.singular" />
</template>
</TabsContent>
</Tabs>
<InstallationDialog v-model:open="installationOpen" :extension="installation" :packages="store.packages" :scopes="scopes" @saved="reload" />
<AlertDialog v-model:open="acceptOpen">
<AlertDialogContent>
<AlertDialogHeader>
@@ -313,7 +411,7 @@ const active = computed(() => (kinds.data.value ?? []).find((kind) => kind.kind
<Select :model-value="acceptKeys[slot]" @update:model-value="(value) => (acceptKeys = { ...acceptKeys, [slot]: String(value) })">
<SelectTrigger class="w-56" :aria-label="`Credential for ${slot}`"><SelectValue placeholder="no credential" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="name in credentialNames" :key="name" :value="name">{{ name }}</SelectItem>
<SelectItem v-for="name in instanceCredentials" :key="name" :value="name">{{ name }}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -343,11 +441,12 @@ const active = computed(() => (kinds.data.value ?? []).find((kind) => kind.kind
</DialogContent>
</Dialog>
<AlertDialog v-model:open="removeOpen">
<AlertDialog :open="!!removing" @update:open="(value) => { if (!value) removing = null; }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove {{ removing?.name }}?</AlertDialogTitle>
<AlertDialogDescription>Its process stops.</AlertDialogDescription>
<AlertDialogDescription v-if="removePackage">Its process stops and the package is no longer accepted.</AlertDialogDescription>
<AlertDialogDescription v-else>Its process stops and its configuration is deleted. The package stays accepted.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
+173
View File
@@ -0,0 +1,173 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SettingRow } from "@/components/ui/setting-row";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { errors } from "@/copy/errors";
import { api, describeError, type Extension, type ExtensionScope, type InstallationInput, type InstallationUpdate, type PackageView, type SettingField } from "@/lib/api";
import { fromLines, toLines } from "@/lib/lines";
import { useRead } from "@/lib/use-read";
/** One installation's configuration. A new installation names the accepted
* package and the scope that owns it; an existing one changes only its
* settings, grants and state. */
const props = defineProps<{
extension: Extension | null;
packages: PackageView[];
scopes: ExtensionScope[];
}>();
const open = defineModel<boolean>("open", { required: true });
const emit = defineEmits<{ saved: [] }>();
const credentials = useRead(() => api.credentials());
onMounted(credentials.reload);
const creating = computed(() => !props.extension);
const schema = computed<SettingField[]>(() => props.extension?.settings_schema ?? []);
const selected = computed(() => props.packages.find((p) => p.name === packageName.value));
const contract = computed(() => props.extension?.contract ?? selected.value?.contract ?? "");
const isMCP = computed(() => contract.value === "mcp");
const scope = ref<ExtensionScope>("person");
const packageName = ref("");
const name = ref("");
const settings = ref<Record<string, string>>({});
const other = ref("");
const credentialSlots = ref("");
const egress = ref("");
const env = ref("");
const args = ref("");
const url = ref("");
const tools = ref("[]");
const enabled = ref(true);
const busy = ref(false);
const actionError = ref("");
/** The credentials this installation may name: the instance's, plus its own
* scope's. The server returns only the caller's organisation and person, so
* the scope is enough to tell them apart. */
const credentialNames = computed(() =>
(credentials.data.value ?? [])
.filter((c) => c.scope === "instance" || c.scope === scope.value)
.map((c) => c.name),
);
// A dialog's action closes it before its click handler runs, so the target
// outlives the open flag rather than being reset on close.
watch(open, (value) => {
if (value) reset();
});
function reset(): void {
const e = props.extension;
const known = new Set((e?.settings_schema ?? []).map((field) => field.key));
settings.value = Object.fromEntries(Object.entries(e?.settings ?? {}).filter(([key]) => known.has(key)));
other.value = toLines(Object.fromEntries(Object.entries(e?.settings ?? {}).filter(([key]) => !known.has(key))));
credentialSlots.value = toLines(e?.credentials ?? {});
egress.value = (e?.egress ?? []).join("\n");
env.value = (e?.env ?? []).join("\n");
args.value = (e?.args ?? []).join("\n");
url.value = e?.url ?? "";
tools.value = e?.tools ? JSON.stringify(e.tools, null, 2) : "[]";
enabled.value = e?.enabled ?? true;
packageName.value = e?.package ?? props.packages.find((p) => p.installed)?.name ?? "";
scope.value = "person";
name.value = "";
actionError.value = "";
}
const list = (text: string) => text.split("\n").map((line) => line.trim()).filter(Boolean);
async function submit(): Promise<void> {
busy.value = true;
actionError.value = "";
try {
const body: InstallationUpdate = {
settings: { ...fromLines(other.value), ...Object.fromEntries(Object.entries(settings.value).filter(([, value]) => value !== "")) },
credentials: fromLines(credentialSlots.value),
egress: list(egress.value),
env: list(env.value),
enabled: enabled.value,
};
if (isMCP.value) {
body.url = url.value.trim();
body.args = list(args.value);
body.tools = JSON.parse(tools.value || "[]");
}
if (props.extension) {
await api.updateInstallation(props.extension.id, body);
} else {
const create: InstallationInput = { package: packageName.value, scope: scope.value, ...body };
if (name.value.trim()) create.name = name.value.trim();
await api.createInstallation(create);
}
emit("saved");
open.value = false;
} catch (cause) {
actionError.value = cause instanceof SyntaxError ? `Tools: ${cause.message}` : describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
<DialogHeader><DialogTitle>{{ creating ? "New installation" : `Edit ${extension?.name}` }}</DialogTitle></DialogHeader>
<form id="installation-form" @submit.prevent="submit">
<SettingRow v-if="creating" label="Package" for="installation-package">
<Select v-model="packageName">
<SelectTrigger id="installation-package" class="w-full"><SelectValue placeholder="Accepted package" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="pkg in packages.filter((p) => p.installed)" :key="pkg.name" :value="pkg.name">
{{ pkg.display_name || pkg.name }}<span v-if="pkg.display_name" class="text-fg-subtle"> ({{ pkg.name }})</span>
</SelectItem>
</SelectContent>
</Select>
</SettingRow>
<SettingRow v-else label="Package" for="installation-package-name">{{ extension?.package }}</SettingRow>
<SettingRow v-if="creating" label="Scope" for="installation-scope" hint="Who owns the installation and its configuration.">
<Select v-model="scope">
<SelectTrigger id="installation-scope" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem v-for="value in scopes" :key="value" :value="value">{{ value === "org" ? "Organisation" : value === "instance" ? "Instance" : "Person" }}</SelectItem>
</SelectContent>
</Select>
</SettingRow>
<SettingRow v-if="creating" label="Name" for="installation-name" hint="What a binding calls it. Default: the package's name.">
<Input id="installation-name" v-model="name" pattern="[a-z0-9][a-z0-9-]*" :placeholder="selected?.name" />
</SettingRow>
<template v-if="isMCP">
<SettingRow label="URL" for="installation-url" hint="For a server reached over HTTP instead of run from a path."><Input id="installation-url" v-model="url" type="url" /></SettingRow>
<SettingRow label="Arguments" for="installation-args" hint="One per line."><Textarea id="installation-args" v-model="args" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Tools" for="installation-tools" hint="The tools it may offer, as JSON: name, kind, read_only, reversibility, summary.">
<Textarea id="installation-tools" v-model="tools" class="font-mono" rows="5" />
</SettingRow>
</template>
<SettingRow v-for="field in schema" :key="field.key" :label="field.label || field.key" :for="`installation-set-${field.key}`" :hint="field.description">
<Select v-if="field.options?.length" v-model="settings[field.key]">
<SelectTrigger :id="`installation-set-${field.key}`" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem v-for="option in field.options" :key="option" :value="option">{{ option }}</SelectItem></SelectContent>
</Select>
<Input v-else :id="`installation-set-${field.key}`" v-model="settings[field.key]" :required="field.required" :placeholder="field.secret ? 'engine:key' : undefined" />
</SettingRow>
<SettingRow :label="schema.length ? 'Other settings' : 'Settings'" for="installation-settings" hint="key=value, one per line. A key ending in _ref takes engine:key.">
<Textarea id="installation-settings" v-model="other" class="font-mono" rows="3" />
</SettingRow>
<SettingRow label="Credentials" for="installation-credentials" hint="slot=credential, one per line.">
<Textarea id="installation-credentials" v-model="credentialSlots" class="font-mono" rows="2" :placeholder="credentialNames.join('\n')" />
</SettingRow>
<SettingRow label="Egress" for="installation-egress" hint="Hosts it may reach, one per line."><Textarea id="installation-egress" v-model="egress" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Environment" for="installation-env" hint="Host variables it may see, one per line."><Textarea id="installation-env" v-model="env" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Run" for="installation-enabled" hint="Start it when it is saved."><Switch id="installation-enabled" v-model="enabled" /></SettingRow>
<p v-if="actionError" role="alert" class="pt-2 text-caption text-danger">{{ actionError }}</p>
</form>
<DialogFooter><Button type="submit" form="installation-form" :disabled="busy || (creating && !packageName)">{{ creating ? "Install" : "Save and restart" }}</Button></DialogFooter>
</DialogContent>
</Dialog>
</template>
+175
View File
@@ -0,0 +1,175 @@
<script setup lang="ts">
import { Plus } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { MoreMenu } from "@/components/ui/more-menu";
import { ReadError } from "@/components/ui/read-error";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SettingRow } from "@/components/ui/setting-row";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { errors } from "@/copy/errors";
import { api, describeError, type ExtensionInput, type ExtensionKind, type PackageView } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { fromLines } from "@/lib/lines";
/** The packages of one contract the instance accepted: each is accepted by
* path and digest, and runs only while its digest matches. */
const props = defineProps<{ kind: ExtensionKind; contract: string; noun: string }>();
const { data, error, reload } = useRead(() => api.packages());
onMounted(reload);
const rows = computed(() => (data.value ?? []).filter((pkg) => pkg.contract === props.contract));
const columns = computed<DataTableColumn<PackageView>[]>(() => [
{ id: "name", label: "Package", fixed: true, sort: (pkg) => pkg.name },
{ id: "version", label: "Version", hide: "sm", width: "8rem", sort: (pkg) => pkg.version ?? "" },
{ id: "managed", label: "Source", hide: "sm", width: "10rem" },
{ id: "digest", label: "Digest", hidden: true, hide: "md", width: "18rem" },
]);
const mcp = computed(() => props.contract === "mcp");
/** What an operator declares about an MCP server's tools. Chat offers a server
* only when its effects are declared and neither one applies. */
const EFFECT_OPTIONS = [
{ value: "unset", label: "Not declared", effects: undefined },
{ value: "none", label: "No privileged effects", effects: { privilege_change: false, secret_access: false } },
{ value: "privilege_change", label: "Changes privileges", effects: { privilege_change: true, secret_access: false } },
{ value: "secret_access", label: "Accesses secrets", effects: { privilege_change: false, secret_access: true } },
{ value: "both", label: "Changes privileges and accesses secrets", effects: { privilege_change: true, secret_access: true } },
] as const;
const editing = ref(false);
const form = ref({ name: "", path: "", sha256: "", url: "", args: "", egress: "", env: "", credentials: "", tools: "", effects: "unset", settings: "", other: "" });
function open(): void {
actionError.value = "";
form.value = { name: "", path: "", sha256: "", url: "", args: "", egress: "", env: "", credentials: "", tools: "[]", effects: "unset", settings: "", other: "" };
editing.value = true;
}
const list = (text: string) => text.split("\n").map((line) => line.trim()).filter(Boolean);
const busy = ref(false);
const actionError = ref("");
async function submit(): Promise<void> {
const f = form.value;
busy.value = true;
actionError.value = "";
try {
const body: ExtensionInput = {
path: f.path.trim() || undefined,
sha256: f.sha256.trim() || undefined,
egress: list(f.egress),
env: list(f.env),
settings: fromLines(f.settings),
credentials: fromLines(f.credentials),
};
if (mcp.value) {
body.url = f.url.trim() || undefined;
body.args = list(f.args);
body.tools = JSON.parse(f.tools || "[]");
body.effects = EFFECT_OPTIONS.find((option) => option.value === f.effects)?.effects;
}
await api.acceptExtension(props.kind, f.name.trim(), body);
editing.value = false;
} catch (cause) {
actionError.value = cause instanceof SyntaxError ? `Tools: ${cause.message}` : describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
await reload();
}
}
const removing = ref<PackageView | null>(null);
async function remove(): Promise<void> {
if (!removing.value) return;
busy.value = true;
actionError.value = "";
try {
await api.removeExtension(props.kind, removing.value.name);
} catch (cause) {
actionError.value = describeError(cause, errors.common.unknown);
} finally {
removing.value = null;
busy.value = false;
await reload();
}
}
</script>
<template>
<div>
<p v-if="actionError && !editing" role="alert" class="mb-2 text-caption text-danger">{{ actionError }}</p>
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<div v-else-if="!data" role="status" :aria-label="`Loading ${noun}s`" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<template v-else>
<div class="mb-2 flex justify-end">
<Button size="icon-sm" variant="ghost" :aria-label="`Accept ${noun}`" :title="`Accept ${noun}`" @click="open()"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="rows" :row-key="(pkg) => pkg.name" :storage-key="`packages-${kind}`">
<template #cell-name="{ row }">
<span class="font-medium">{{ row.display_name || row.name }}</span>
<span v-if="row.display_name" class="font-mono text-caption text-fg-subtle"> {{ row.name }}</span>
</template>
<template #cell-version="{ row }">{{ row.version || "–" }}</template>
<template #cell-managed="{ row }">
<Badge :variant="row.managed ? 'outline' : 'idle'">{{ row.managed ? "Catalogue" : "By path" }}</Badge>
</template>
<template #cell-digest="{ row }"><span class="font-mono text-caption [overflow-wrap:anywhere]">{{ row.digest }}</span></template>
<template #actions="{ row }">
<MoreMenu :label="`${row.name} actions`">
<DropdownMenuItem class="text-danger" @select="removing = row">Remove</DropdownMenuItem>
</MoreMenu>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No {{ noun }}s</EmptyTitle></EmptyHeader></Empty></template>
</DataTable>
</template>
<Dialog v-model:open="editing">
<DialogContent class="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
<DialogHeader><DialogTitle>Accept {{ noun }}</DialogTitle></DialogHeader>
<form :id="`package-${kind}`" @submit.prevent="submit">
<SettingRow label="Name" for="package-name"><Input id="package-name" v-model="form.name" pattern="[a-z0-9][a-z0-9-]*" required /></SettingRow>
<SettingRow label="Path" for="package-path" hint="The binary on this host."><Input id="package-path" v-model="form.path" class="font-mono" :required="!mcp" /></SettingRow>
<SettingRow label="SHA-256" for="package-sha" hint="It runs only while the binary has this digest."><Input id="package-sha" v-model="form.sha256" class="font-mono" :required="!mcp" /></SettingRow>
<template v-if="mcp">
<SettingRow label="URL" for="package-url" hint="For a server reached over HTTP instead of run from a path."><Input id="package-url" v-model="form.url" type="url" /></SettingRow>
<SettingRow label="Arguments" for="package-args" hint="One per line."><Textarea id="package-args" v-model="form.args" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Tools" for="package-tools" hint="The tools it may offer, as JSON: name, kind, read_only, reversibility, summary."><Textarea id="package-tools" v-model="form.tools" class="font-mono" rows="5" /></SettingRow>
<SettingRow label="Effects" for="package-effects" hint="Chat offers a server only once this says its tools change no privileges and access no secrets.">
<Select v-model="form.effects">
<SelectTrigger id="package-effects" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem v-for="option in EFFECT_OPTIONS" :key="option.value" :value="option.value">{{ option.label }}</SelectItem></SelectContent>
</Select>
</SettingRow>
</template>
<SettingRow label="Settings" for="package-settings" hint="key=value, one per line. A key ending in _ref takes engine:key."><Textarea id="package-settings" v-model="form.settings" class="font-mono" rows="3" /></SettingRow>
<SettingRow label="Credentials" for="package-credentials" hint="slot=credential, one per line."><Textarea id="package-credentials" v-model="form.credentials" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Egress" for="package-egress" hint="Hosts it may reach, one per line."><Textarea id="package-egress" v-model="form.egress" class="font-mono" rows="2" /></SettingRow>
<SettingRow label="Environment" for="package-env" hint="Host variables it may see, one per line."><Textarea id="package-env" v-model="form.env" class="font-mono" rows="2" /></SettingRow>
<p v-if="actionError" role="alert" class="pt-2 text-caption text-danger">{{ actionError }}</p>
</form>
<DialogFooter><Button type="submit" :form="`package-${kind}`" :disabled="busy">Accept and start</Button></DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog :open="!!removing" @update:open="(value) => { if (!value) removing = null; }">
<AlertDialogContent>
<AlertDialogHeader><AlertDialogTitle>Remove {{ removing?.name }}?</AlertDialogTitle></AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction :disabled="busy" @click="remove">Remove</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
+18 -3
View File
@@ -2,9 +2,9 @@ import { defineStore } from "pinia";
import { ref } from "vue";
import { errors } from "@/copy/errors";
import { api, describeError, type CatalogueEntry, type CatalogueSourceView, type Extension, type ExtensionGrantsInput, type Grants, type SettingField } from "@/lib/api";
import { api, describeError, type CatalogueEntry, type CatalogueSourceView, type Extension, type ExtensionGrantsInput, type Grants, type InstallationInput, type InstallationUpdate, type PackageView, type SettingField } from "@/lib/api";
export type { CatalogueEntry, Extension } from "@/lib/api";
export type { CatalogueEntry, Extension, PackageView } from "@/lib/api";
/** One setting a package declares. */
export type ExtensionSettingSpec = SettingField;
@@ -29,6 +29,7 @@ export function stage(extension: Extension): "accept" | "disabled" | "enabled" {
export const useExtensionsStore = defineStore("extensions", () => {
const extensions = ref<Extension[]>([]);
const packages = ref<PackageView[]>([]);
const catalogue = ref<CatalogueEntry[]>([]);
const source = ref<CatalogueSourceView>({ configured: false });
const catalogueError = ref("");
@@ -44,6 +45,14 @@ export const useExtensionsStore = defineStore("extensions", () => {
}
}
async function loadPackages(): Promise<void> {
try {
packages.value = await api.packages();
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
}
}
async function loadSource(): Promise<void> {
try {
source.value = await api.catalogueSource();
@@ -53,7 +62,7 @@ export const useExtensionsStore = defineStore("extensions", () => {
}
async function load(): Promise<void> {
await Promise.all([loadInstalled(), loadSource()]);
await Promise.all([loadInstalled(), loadPackages(), loadSource()]);
// The catalogue is remote; its failure leaves the installed list usable.
try {
catalogue.value = await api.catalogue();
@@ -81,6 +90,7 @@ export const useExtensionsStore = defineStore("extensions", () => {
return {
extensions,
packages,
catalogue,
source,
catalogueLoaded,
@@ -89,7 +99,12 @@ export const useExtensionsStore = defineStore("extensions", () => {
busy,
load,
loadInstalled,
loadPackages,
loadSource,
createInstallation: (body: InstallationInput) => mutate("new-installation", () => api.createInstallation(body)),
updateInstallation: (id: string, body: InstallationUpdate) => mutate(id, () => api.updateInstallation(id, body)),
removeInstallation: (id: string) => mutate(id, () => api.removeInstallation(id)),
overrideInstallation: (id: string, scope: "org" | "person", off: boolean) => mutate(id, () => api.putInstallationOverride(id, scope, off)),
installFromCatalogue: (name: string) => mutate(name, () => api.installCatalogue(name)),
accept: (name: string, body?: ExtensionGrantsInput) => mutate(name, () => api.acceptGrants(name, body)),
update: (name: string) => mutate(name, () => api.updateExtension(name)),