From c9ed3b1ae2b662f99a01a27b1d53bdbb9c6355fc Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 25 Nov 2026 22:10:06 +1100 Subject: [PATCH] feat(connectors): version packages and pin installations A package is now a set of immutable versions with declared grants and a default version that installations run unless they pin another. Adopting a version is what accepts its grants, replacing the per-extension lifecycle actions with version, pin and update-policy commands. --- api/openapi.yaml | 647 +++++++------ deployments/archie/compose.yml | 2 + deployments/archie/deploy.sh | 7 +- .../migrations/00014_connectors_versions.sql | 82 ++ modules/connectors/api.go | 17 +- modules/connectors/catalogue.go | 114 ++- modules/connectors/extensions_api.go | 15 +- modules/connectors/installations.go | 134 ++- .../internal/catalogue/catalogue_test.go | 81 +- .../connectors/internal/catalogue/document.go | 105 +- .../internal/catalogue/lifecycle.go | 116 +-- modules/connectors/internal/store/store.go | 289 +++++- modules/connectors/list.go | 80 +- modules/connectors/mcpaccept.go | 3 +- modules/connectors/module.go | 17 +- modules/connectors/packages.go | 897 ++++++++++-------- modules/connectors/remove_test.go | 14 + ui/src/lib/api.ts | 108 ++- ui/src/settings/CatalogueInstallDialog.vue | 119 +++ ui/src/settings/ExtensionChannelSettings.vue | 2 +- ui/src/settings/ExtensionsMarketplace.vue | 19 +- ui/src/settings/ExtensionsPage.vue | 161 +--- ui/src/settings/InstallationDialog.vue | 23 +- ui/src/settings/PackageList.vue | 6 +- ui/src/settings/PackageVersionsDialog.vue | 89 ++ ui/src/stores/extensions.ts | 43 +- 26 files changed, 1925 insertions(+), 1265 deletions(-) create mode 100644 internal/platform/pg/migrations/00014_connectors_versions.sql create mode 100644 ui/src/settings/CatalogueInstallDialog.vue create mode 100644 ui/src/settings/PackageVersionsDialog.vue diff --git a/api/openapi.yaml b/api/openapi.yaml index 5bbc5220e..8e3fd663e 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -482,14 +482,12 @@ components: properties: contract: type: string - description: + default_version: type: string - digest: + description: type: string display_name: type: string - grants: - $ref: "#/components/schemas/CatalogueGrants" group: enum: - platform @@ -498,23 +496,26 @@ components: type: string installed: type: boolean - installed_version: + latest: type: string name: type: string update_available: type: boolean - version: - type: string + versions: + items: + $ref: "#/components/schemas/ConnectorsCatalogueVersion" + type: + - array + - "null" required: - name - display_name - description - contract - group - - version - - digest - - grants + - latest + - versions - installed - update_available type: object @@ -535,6 +536,30 @@ components: - location - public_key type: object + ConnectorsCatalogueVersion: + additionalProperties: false + properties: + digest: + type: string + grants: + $ref: "#/components/schemas/CatalogueGrants" + registered: + type: boolean + settings: + items: + $ref: "#/components/schemas/ConnectorsSetting" + type: + - array + - "null" + version: + type: string + required: + - version + - digest + - grants + - settings + - registered + type: object ConnectorsCredentialKind: additionalProperties: false properties: @@ -694,8 +719,6 @@ components: type: - array - "null" - can_rollback: - type: boolean capabilities: $ref: "#/components/schemas/ConnectorsCapabilities" contract: @@ -761,8 +784,6 @@ components: type: string path: type: string - pending: - $ref: "#/components/schemas/ConnectorsPendingView" scope: enum: - instance @@ -782,12 +803,12 @@ components: state: type: string tools: {} - update_policy: - type: string url: type: string version: type: string + version_pinned: + type: boolean required: - id - name @@ -805,8 +826,8 @@ components: - settings_schema - credentials - enabled + - version_pinned - managed - - can_rollback type: object ConnectorsField: additionalProperties: false @@ -822,28 +843,20 @@ components: ConnectorsGrantsRequest: additionalProperties: false properties: - credentials: - additionalProperties: - type: string - type: object egress: - description: Every host the extension may reach; empty leaves it unconfined, which only an extension that declares no hosts may be given + description: "Every host the extension may reach. Omitted: the hosts the version declares" items: type: string type: - array - "null" env: - description: Host environment variables the extension may see + description: "Host environment variables the extension may see. Omitted: those the version declares" items: type: string type: - array - "null" - settings: - additionalProperties: - type: string - type: object type: object ConnectorsHealth: additionalProperties: false @@ -934,27 +947,10 @@ components: - "null" url: type: string - required: - - enabled - type: object - ConnectorsLifecycle: - additionalProperties: false - properties: - digest: - type: string - enabled: - type: boolean - name: - type: string - pending: - type: boolean version: + description: "An accepted version of the package to run. Default: the package's default version" type: string required: - - name - - version - - digest - - pending - enabled type: object ConnectorsMcpRequest: @@ -1024,9 +1020,9 @@ components: type: string contract: type: string - description: + default_version: type: string - digest: + description: type: string display_name: type: string @@ -1038,39 +1034,32 @@ components: 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: + update_policy: + enum: + - manual + - auto type: string + versions: + items: + $ref: "#/components/schemas/ConnectorsVersionView" + type: + - array + - "null" required: - id - name - contract - group - - digest + - default_version - managed - - installed + - update_policy + - versions - accepted_at type: object - ConnectorsPendingView: - additionalProperties: false - properties: - added: - $ref: "#/components/schemas/CatalogueGrants" - digest: - type: string - version: - type: string - required: - - version - - digest - - added - type: object ConnectorsPrivilegedEffects: additionalProperties: false properties: @@ -1165,6 +1154,41 @@ components: - name - kind type: object + ConnectorsVersionView: + additionalProperties: false + properties: + accepted: + $ref: "#/components/schemas/CatalogueGrants" + created_at: + format: date-time + type: string + declared: + $ref: "#/components/schemas/CatalogueGrants" + default: + type: boolean + digest: + type: string + installations: + format: int64 + type: integer + settings: + items: + $ref: "#/components/schemas/ConnectorsSetting" + type: + - array + - "null" + version: + type: string + required: + - version + - digest + - declared + - accepted + - settings + - default + - installations + - created_at + type: object CorrectInputBody: additionalProperties: false properties: @@ -1289,6 +1313,15 @@ components: - id - name type: object + DefaultVersionInputBody: + additionalProperties: false + properties: + version: + description: An accepted version of the package + type: string + required: + - version + type: object DeliveriesAttempt: additionalProperties: false properties: @@ -2070,33 +2103,6 @@ components: type: string type: object type: object - ExtensionEnabledInputBody: - additionalProperties: false - properties: - enabled: - type: boolean - required: - - enabled - type: object - ExtensionPolicyInputBody: - additionalProperties: false - properties: - policy: - enum: - - manual - - auto - type: string - required: - - policy - type: object - ExtensionSettingsInputBody: - additionalProperties: false - properties: - settings: - additionalProperties: - type: string - type: object - type: object GovernanceAuthStatusBody: additionalProperties: false properties: @@ -2900,6 +2906,35 @@ components: required: - workspaces type: object + InstallInputBody: + additionalProperties: false + properties: + credentials: + additionalProperties: + type: string + description: Each credential slot and the credential, by name, that fills it + type: object + enabled: + type: boolean + installation: + type: string + scope: + description: "Who owns the installation. Default: the instance" + enum: + - instance + - org + - person + type: string + settings: + additionalProperties: + type: string + type: object + version: + description: "The catalogue version to install. Default: the latest" + type: string + required: + - enabled + type: object Item: additionalProperties: false properties: @@ -3829,6 +3864,13 @@ components: required: - code type: object + RegisterVersionInputBody: + additionalProperties: false + properties: + version: + description: "The catalogue version to fetch. Default: the latest" + type: string + type: object RejectInputBody: additionalProperties: false properties: @@ -4787,6 +4829,17 @@ components: - name - rule type: object + UpdatePolicyInputBody: + additionalProperties: false + properties: + policy: + enum: + - manual + - auto + type: string + required: + - policy + type: object Usage: additionalProperties: false properties: @@ -6552,56 +6605,6 @@ paths: /api/extensions/catalogue/{name}/install: post: operationId: install-extension - parameters: - - in: path - name: name - required: true - schema: - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Fetch an extension at the digest the catalogue pins and install it, not yet accepted - tags: - - Extension catalogue - /api/extensions/{name}: - delete: - operationId: remove-extension - parameters: - - in: path - name: name - 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 accepted package - tags: - - Extensions - /api/extensions/{name}/accept: - post: - operationId: accept-extension-grants parameters: - in: path name: name @@ -6612,69 +6615,14 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/ConnectorsGrantsRequest" - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Accept the grants an installed extension may use, and its settings - tags: - - Extension catalogue - /api/extensions/{name}/approve-update: - post: - operationId: approve-extension-update - parameters: - - in: path - name: name - required: true - schema: - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Apply the pending update and accept the grants it declares - tags: - - Extension catalogue - /api/extensions/{name}/enabled: - put: - operationId: put-extension-enabled - parameters: - - in: path - name: name - required: true - schema: - type: string - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/ExtensionEnabledInputBody" + $ref: "#/components/schemas/InstallInputBody" required: true responses: "200": content: application/json: schema: - $ref: "#/components/schemas/ConnectorsLifecycle" + $ref: "#/components/schemas/ConnectorsExtensionView" description: OK default: content: @@ -6682,119 +6630,7 @@ paths: schema: $ref: "#/components/schemas/ErrorModel" description: Error - summary: Start or stop an accepted extension - tags: - - Extension catalogue - /api/extensions/{name}/rollback: - post: - operationId: rollback-extension - parameters: - - in: path - name: name - required: true - schema: - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Restore the previous version with the grants accepted for it - tags: - - Extension catalogue - /api/extensions/{name}/settings: - put: - operationId: put-extension-settings - parameters: - - in: path - name: name - required: true - schema: - type: string - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/ExtensionSettingsInputBody" - required: true - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Save an installed extension's settings and restart it - tags: - - Extension catalogue - /api/extensions/{name}/update: - post: - operationId: update-extension - parameters: - - in: path - name: name - required: true - schema: - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Move an extension to the digest the catalogue now pins - tags: - - Extension catalogue - /api/extensions/{name}/update-policy: - put: - operationId: put-extension-update-policy - parameters: - - in: path - name: name - required: true - schema: - type: string - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/ExtensionPolicyInputBody" - required: true - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/ConnectorsLifecycle" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Set whether an extension follows the catalogue on its own + summary: Fetch a catalogue version, accept its grants, and create and start an installation tags: - Extension catalogue /api/groups: @@ -8071,6 +7907,189 @@ paths: summary: List the packages the instance accepted tags: - Installations + /api/packages/{name}: + delete: + operationId: remove-package + parameters: + - in: path + name: name + 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 a package, its versions and its instance installations + tags: + - Packages + /api/packages/{name}/default-version: + put: + operationId: put-package-default-version + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/DefaultVersionInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsVersionView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Run an accepted version in every installation that follows the package + tags: + - Packages + /api/packages/{name}/update-policy: + put: + operationId: put-package-update-policy + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/UpdatePolicyInputBody" + 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: Set whether a package follows the catalogue on its own + tags: + - Packages + /api/packages/{name}/versions: + post: + operationId: register-package-version + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RegisterVersionInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsVersionView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Fetch another catalogue version of an installed package + tags: + - Packages + /api/packages/{name}/versions/{version}: + delete: + operationId: remove-package-version + parameters: + - in: path + name: name + required: true + schema: + type: string + - in: path + name: version + 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 a version no installation runs + tags: + - Packages + /api/packages/{name}/versions/{version}/accept: + post: + operationId: accept-package-version + parameters: + - in: path + name: name + required: true + schema: + type: string + - in: path + name: version + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsGrantsRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsVersionView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Accept the grants a package version may use + tags: + - Packages /api/policies/change-request: get: operationId: get-change-request-rules diff --git a/deployments/archie/compose.yml b/deployments/archie/compose.yml index a2d9d2940..cabb34296 100644 --- a/deployments/archie/compose.yml +++ b/deployments/archie/compose.yml @@ -31,6 +31,8 @@ services: - ./bin/archie:/archie/archie:ro - ./config.toml:/archie/config.toml:ro - ./extensions:/archie/extensions:ro + - ./state:/archie/state + - ./catalogue:/archie/catalogue:ro ports: - "${ARCHIE_BIND:?}:8080" networks: [internal] diff --git a/deployments/archie/deploy.sh b/deployments/archie/deploy.sh index ecb29ca54..4a86ee08d 100755 --- a/deployments/archie/deploy.sh +++ b/deployments/archie/deploy.sh @@ -14,7 +14,7 @@ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -C "$repo" -trimpath \ -ldflags "-X github.com/samcharles93/archie-core/internal/buildinfo.Version=$version" \ -o "$here/.build/archie" ./cmd/archie -ssh "$target" "mkdir -p $dir/bin $dir/initdb $dir/extensions" +ssh "$target" "mkdir -p $dir/bin $dir/initdb $dir/extensions $dir/catalogue $dir/state && chown 65532:65532 $dir/state" scp -q "$here/compose.yml" "$target:$dir/compose.yml" scp -q "$here/seccomp.json" "$target:$dir/seccomp.json" scp -q "$here/initdb/01-roles.sh" "$target:$dir/initdb/01-roles.sh" @@ -51,6 +51,11 @@ if ! grep -q '^admin_token_sha256' config.toml; then sed -i "1i admin_token_sha256 = \"$hash\"" config.toml chown 65532:65532 config.toml fi +# Fetched extension binaries and other state outside the database live in +# the mounted state directory, so they survive the container being recreated. +if ! grep -q '^state_dir' config.toml; then + sed -i '1i state_dir = "/archie/state"' config.toml +fi # The age identity seals the credentials Archie keeps. It is made here and # never leaves the host; back it up, or credentials die with it. if ! grep -q '^age_identity' config.toml; then diff --git a/internal/platform/pg/migrations/00014_connectors_versions.sql b/internal/platform/pg/migrations/00014_connectors_versions.sql new file mode 100644 index 000000000..9efbea2ca --- /dev/null +++ b/internal/platform/pg/migrations/00014_connectors_versions.sql @@ -0,0 +1,82 @@ +-- +goose Up +-- A package version is one release of a package: its binary, the digest it +-- must hash to, the grants and settings it declared, and the grants the +-- instance accepted for it, null until accepted. A version accepted by path is +-- accepted when it is stored, and its installations carry the grants the +-- administrator gave them. A version is immutable: the +-- same version with a different digest is refused. capabilities and effects +-- are what the version declared when it last loaded. +CREATE TABLE connectors.package_versions ( + id uuid PRIMARY KEY, + package_id uuid NOT NULL REFERENCES connectors.packages (id) ON DELETE CASCADE, + version text NOT NULL, + path text NOT NULL, + sha256 text NOT NULL, + declared jsonb NOT NULL DEFAULT '{}', + settings jsonb NOT NULL DEFAULT '[]', + accepted jsonb, + accepted_by_id text NOT NULL DEFAULT '', + capabilities jsonb, + effects jsonb, + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (package_id, version) +); + +-- A package's default version is what its installations run unless one pins +-- another. managed says the package came from the catalogue. +ALTER TABLE connectors.packages + ADD COLUMN display_name text NOT NULL DEFAULT '', + ADD COLUMN description text NOT NULL DEFAULT '', + ADD COLUMN managed boolean NOT NULL DEFAULT false, + ADD COLUMN update_policy text NOT NULL DEFAULT 'manual' CHECK (update_policy IN ('manual', 'auto')), + ADD COLUMN default_version_id uuid REFERENCES connectors.package_versions (id); + +INSERT INTO connectors.package_versions + (id, package_id, version, path, sha256, declared, accepted, accepted_by_id, capabilities, effects) +SELECT gen_random_uuid(), p.id, + COALESCE(p.manifest #>> '{state,current,version}', 'local-' || left(p.sha256, 12)), + p.path, p.sha256, + COALESCE(p.manifest #> '{state,current,declared}', '{}'), + CASE WHEN p.manifest IS NULL THEN '{}'::jsonb ELSE p.manifest #> '{state,accepted}' END, + p.accepted_by_id, p.capabilities, p.effects +FROM connectors.packages p; + +UPDATE connectors.packages p +SET default_version_id = v.id, + managed = p.manifest IS NOT NULL, + display_name = COALESCE(p.manifest ->> 'display_name', ''), + description = COALESCE(p.manifest ->> 'description', ''), + update_policy = COALESCE(p.manifest #>> '{state,policy}', 'manual') +FROM connectors.package_versions v +WHERE v.package_id = p.id; + +ALTER TABLE connectors.packages + DROP COLUMN path, + DROP COLUMN sha256, + DROP COLUMN manifest, + DROP COLUMN capabilities, + DROP COLUMN effects; + +-- An installation runs its package's default version unless it pins one. +ALTER TABLE connectors.installations + ADD COLUMN package_version_id uuid REFERENCES connectors.package_versions (id) ON DELETE RESTRICT; + +-- +goose Down +ALTER TABLE connectors.installations DROP COLUMN package_version_id; +ALTER TABLE connectors.packages + ADD COLUMN path text NOT NULL DEFAULT '', + ADD COLUMN sha256 text NOT NULL DEFAULT '', + ADD COLUMN manifest jsonb, + ADD COLUMN capabilities jsonb, + ADD COLUMN effects jsonb; +UPDATE connectors.packages p +SET path = v.path, sha256 = v.sha256, capabilities = v.capabilities, effects = v.effects +FROM connectors.package_versions v +WHERE v.id = p.default_version_id; +ALTER TABLE connectors.packages + DROP COLUMN default_version_id, + DROP COLUMN update_policy, + DROP COLUMN managed, + DROP COLUMN description, + DROP COLUMN display_name; +DROP TABLE connectors.package_versions; diff --git a/modules/connectors/api.go b/modules/connectors/api.go index dc7de45b5..9df7017be 100644 --- a/modules/connectors/api.go +++ b/modules/connectors/api.go @@ -104,6 +104,7 @@ func (m *Module) Register(api huma.API) { }, listCredentialKinds) m.registerCatalogue(api) m.registerExtensions(api) + m.registerPackages(api) } type acceptRequest struct { @@ -156,7 +157,7 @@ func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string } a := store.Installed{ ID: uuid.New(), Scope: store.ScopeInstance, Name: name, PackageName: name, Contract: contract, - Path: req.Path, SHA256: req.SHA256, + Version: localVersion(req.SHA256), 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. @@ -167,7 +168,7 @@ func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations") } if found { - if len(previous.Manifest) > 0 { + if previous.Managed { 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 @@ -176,11 +177,21 @@ func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string return nil, acceptError(err) } if found && (previous.Path != a.Path || previous.SHA256 != a.SHA256) { - m.relaunchPackage(context.WithoutCancel(ctx), a) + m.relaunchFollowers(context.WithoutCancel(ctx), a.PackageID, a.ID) } return httpapi.OK(packageState{Name: name, State: "running"}), nil } +// localVersion names the version of a binary accepted by path after its digest, +// so accepting a different binary records a new version. +func localVersion(sha256 string) string { + d := strings.ToLower(strings.TrimPrefix(sha256, "sha256:")) + if len(d) > 12 { + d = d[:12] + } + return "local-" + d +} + // acceptError maps an error returned by commit to an HTTP error. func acceptError(err error) error { if errors.As(err, new(persistError)) { diff --git a/modules/connectors/catalogue.go b/modules/connectors/catalogue.go index fbcf25b1b..dd3c47b7e 100644 --- a/modules/connectors/catalogue.go +++ b/modules/connectors/catalogue.go @@ -107,22 +107,31 @@ func (m *Module) readCatalogue(ctx context.Context) (catalogue.Document, string, return doc, src.Location, nil } -// CatalogueEntry is one extension the catalogue offers and whether it is -// installed. +// CatalogueEntry is one extension the catalogue offers, with its versions and +// the version the instance runs by default when it is installed. type CatalogueEntry struct { - Name string `json:"name"` - DisplayName string `json:"display_name"` - Description string `json:"description"` - Contract string `json:"contract"` - Group string `json:"group" enum:"platform,integration,agent"` - Version string `json:"version"` - Digest string `json:"digest"` - Grants catalogue.Grants `json:"grants"` - Installed bool `json:"installed"` - // InstalledVersion and UpdateAvailable describe an installed entry: the - // catalogue now pins a different digest than the one installed. - InstalledVersion string `json:"installed_version,omitempty"` - UpdateAvailable bool `json:"update_available"` + Name string `json:"name"` + DisplayName string `json:"display_name"` + Description string `json:"description"` + Contract string `json:"contract"` + Group string `json:"group" enum:"platform,integration,agent"` + Latest string `json:"latest"` + Versions []CatalogueVersion `json:"versions"` + Installed bool `json:"installed"` + // DefaultVersion is the version installations run unless they pin one; + // UpdateAvailable says the catalogue offers a newer one. + DefaultVersion string `json:"default_version,omitempty"` + UpdateAvailable bool `json:"update_available"` +} + +// CatalogueVersion is one version the catalogue offers. +type CatalogueVersion struct { + Version string `json:"version"` + Digest string `json:"digest"` + Grants catalogue.Grants `json:"grants"` + Settings []Setting `json:"settings"` + // Registered says the instance has fetched this version. + Registered bool `json:"registered"` } func (m *Module) listCatalogue(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]CatalogueEntry], error) { @@ -130,29 +139,58 @@ func (m *Module) listCatalogue(ctx context.Context, _ *struct{}) (*httpapi.Reply if err != nil { return nil, catalogueError(err) } - accepted, err := m.store.List(ctx) + pkgs, err := m.store.Packages(ctx) if err != nil { - m.log.ErrorContext(ctx, "list installations", "error", err) - return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations") + m.log.ErrorContext(ctx, "list packages", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the packages") + } + versions, err := m.store.Versions(ctx) + if err != nil { + m.log.ErrorContext(ctx, "list package versions", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the package versions") } out := make([]CatalogueEntry, 0, len(doc.Extensions)) for _, e := range doc.Extensions { + latest, _ := e.Latest() entry := CatalogueEntry{ 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, + Group: string(store.GroupOf(e.Contract)), Latest: latest.Version, Versions: make([]CatalogueVersion, 0, len(e.Versions)), } - if i := slices.IndexFunc(accepted, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == e.Name }); i >= 0 { + var registered map[string]bool + if i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == e.Name }); i >= 0 { entry.Installed = true - if rec, ok, err := packageOf(accepted[i]); err == nil && ok { - entry.InstalledVersion = rec.State.Current.Version - entry.UpdateAvailable = rec.State.Current.Digest != e.Digest + registered = map[string]bool{} + for _, v := range versions { + if v.PackageID != pkgs[i].ID { + continue + } + registered[v.Version] = true + if v.ID == pkgs[i].DefaultVersion.UUID { + entry.DefaultVersion = v.Version + } } + entry.UpdateAvailable = entry.DefaultVersion != "" && catalogue.Newer(latest.Version, entry.DefaultVersion) + } + for _, v := range e.Versions { + entry.Versions = append(entry.Versions, CatalogueVersion{ + Version: v.Version, Digest: v.Digest, Grants: v.Grants, Settings: catalogueSettings(v.Settings), + Registered: registered[v.Version], + }) } out = append(out, entry) } return httpapi.OK(out), nil } +// catalogueSettings converts the settings a catalogue version declares. +func catalogueSettings(in []catalogue.Setting) []Setting { + out := make([]Setting, 0, len(in)) + for _, s := range in { + out = append(out, Setting(s)) + } + return out +} + // catalogueError reports why the catalogue couldn't be used. A catalogue that // can't be fetched or verified is a bad gateway, never an empty list. func catalogueError(err error) error { @@ -184,34 +222,6 @@ func (m *Module) registerCatalogue(api huma.API) { }, m.listCatalogue) httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindConnector), huma.Operation{ OperationID: "install-extension", Method: http.MethodPost, Path: "/api/extensions/catalogue/{name}/install", - Summary: "Fetch an extension at the digest the catalogue pins and install it, not yet accepted", Tags: tags, + Summary: "Fetch a catalogue version, accept its grants, and create and start an installation", Tags: tags, }, m.install) - httpapi.Register(api, write, huma.Operation{ - OperationID: "accept-extension-grants", Method: http.MethodPost, Path: "/api/extensions/{name}/accept", - Summary: "Accept the grants an installed extension may use, and its settings", Tags: tags, - }, m.acceptGrants) - httpapi.Register(api, write, huma.Operation{ - OperationID: "update-extension", Method: http.MethodPost, Path: "/api/extensions/{name}/update", - Summary: "Move an extension to the digest the catalogue now pins", Tags: tags, - }, m.updateExtension) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionApprove, governance.KindConnector), huma.Operation{ - OperationID: "approve-extension-update", Method: http.MethodPost, Path: "/api/extensions/{name}/approve-update", - Summary: "Apply the pending update and accept the grants it declares", Tags: tags, - }, m.approveUpdate) - httpapi.Register(api, write, huma.Operation{ - OperationID: "rollback-extension", Method: http.MethodPost, Path: "/api/extensions/{name}/rollback", - Summary: "Restore the previous version with the grants accepted for it", Tags: tags, - }, m.rollback) - httpapi.Register(api, write, huma.Operation{ - OperationID: "put-extension-update-policy", Method: http.MethodPut, Path: "/api/extensions/{name}/update-policy", - Summary: "Set whether an extension follows the catalogue on its own", Tags: tags, - }, m.setPolicy) - httpapi.Register(api, write, huma.Operation{ - OperationID: "put-extension-enabled", Method: http.MethodPut, Path: "/api/extensions/{name}/enabled", - Summary: "Start or stop an accepted extension", Tags: tags, - }, m.setEnabled) - httpapi.Register(api, write, huma.Operation{ - OperationID: "put-extension-settings", Method: http.MethodPut, Path: "/api/extensions/{name}/settings", - Summary: "Save an installed extension's settings and restart it", Tags: tags, - }, m.putExtensionSettings) } diff --git a/modules/connectors/extensions_api.go b/modules/connectors/extensions_api.go index b32968239..0f17bd2d4 100644 --- a/modules/connectors/extensions_api.go +++ b/modules/connectors/extensions_api.go @@ -20,10 +20,10 @@ func (m *Module) listExtensions(ctx context.Context, _ *struct{}) (*httpapi.Repl return m.listViews(ctx, func(store.Installed) bool { return true }) } -// removeExtension removes an accepted package without naming its contract +// removePackage removes an accepted package without naming its contract // 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) { +func (m *Module) removePackage(ctx context.Context, in *packageNameInput) (*httpapi.Reply[packageState], error) { installed, err := m.store.List(ctx) if err != nil { m.log.ErrorContext(ctx, "list installations", "error", err) @@ -33,11 +33,8 @@ func (m *Module) removeExtension(ctx context.Context, in *nameInput) (*httpapi.R if i < 0 { return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("no accepted package named %s", in.Name)) } - _, managed, err := packageOf(installed[i]) - if err != nil { - return nil, huma.NewError(http.StatusInternalServerError, err.Error()) - } - reply, err := m.removeAs(ctx, in, installed[i].Contract) + managed := installed[i].Managed + reply, err := m.removeAs(ctx, &nameInput{Name: in.Name}, installed[i].Contract) if err != nil { return nil, err } @@ -55,8 +52,4 @@ func (m *Module) registerExtensions(api huma.API) { OperationID: "list-extensions", Method: http.MethodGet, Path: "/api/extensions", 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}", - Summary: "Remove an accepted package", Tags: tags, - }, m.removeExtension) } diff --git a/modules/connectors/installations.go b/modules/connectors/installations.go index a313ae7e7..3e3023856 100644 --- a/modules/connectors/installations.go +++ b/modules/connectors/installations.go @@ -6,6 +6,7 @@ import ( "encoding/json/jsontext" json "encoding/json/v2" "fmt" + "maps" "net/http" "slices" "time" @@ -14,6 +15,7 @@ import ( "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" ) @@ -44,7 +46,7 @@ func (m *Module) registerInstallations(api huma.API) { }, m.putOverride) } -// PackageView is one package the instance accepted. +// PackageView is one package the instance accepted, with its versions. type PackageView struct { ID uuid.UUID `json:"id"` Name string `json:"name"` @@ -52,34 +54,45 @@ type PackageView struct { 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"` + // DefaultVersion is the version installations run unless they pin one. + DefaultVersion string `json:"default_version"` + // Managed says the package was installed from the catalogue. + Managed bool `json:"managed"` + UpdatePolicy string `json:"update_policy" enum:"manual,auto"` + Versions []VersionView `json:"versions"` + AcceptedAt time.Time `json:"accepted_at"` } func (m *Module) listPackages(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]PackageView], error) { - pkgs, err := m.store.Packages(ctx) + pkgs, installed, err := m.packagesAndInstallations(ctx) if err != nil { - m.log.ErrorContext(ctx, "list packages", "error", err) - return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the packages") + return nil, err + } + versions, err := m.store.Versions(ctx) + if err != nil { + m.log.ErrorContext(ctx, "list package versions", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the package versions") + } + running := map[uuid.UUID]int{} + for _, a := range installed { + running[a.VersionID]++ } 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, + DisplayName: p.DisplayName, Description: p.Description, Managed: p.Managed, UpdatePolicy: p.UpdatePolicy, + AcceptedAt: p.AcceptedAt, Versions: []VersionView{}, } - 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 + for _, v := range versions { + if v.PackageID != p.ID { + continue + } + vv := versionView(v, p, running) + if vv.Default { + view.DefaultVersion = v.Version + } + view.Versions = append(view.Versions, vv) } out = append(out, view) } @@ -97,6 +110,9 @@ type installationRequest struct { URL string `json:"url,omitzero"` Tools []ToolDecl `json:"tools,omitzero"` Enabled bool `json:"enabled"` + // Version pins the installation to one accepted version of its package; + // empty runs the package's default version. + Version string `json:"version,omitzero" doc:"An accepted version of the package to run. Default: the package's default version"` } type createInstallationInput struct { @@ -127,11 +143,18 @@ func (m *Module) createInstallation(ctx context.Context, in *createInstallationI if err != nil { return nil, err } - i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == req.Package }) - if i < 0 { + if !slices.ContainsFunc(pkgs, func(p store.Package) bool { return p.Name == req.Package }) { return nil, errNoPackage(req.Package) } - pkg := pkgs[i] + pv, err := m.packageNamed(ctx, req.Package) + if err != nil { + return nil, err + } + pkg := pv.pkg + def, ok := pv.defaultVersion() + if !ok { + return nil, huma.NewError(http.StatusConflict, pkg.Name+" has no default version") + } name := cmp.Or(req.Name, pkg.Name) if !validName.MatchString(name) { return nil, huma.NewError(http.StatusBadRequest, "an installation needs a lowercase name") @@ -139,10 +162,12 @@ func (m *Module) createInstallation(ctx context.Context, in *createInstallationI 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{ + a := withVersion(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, + PackageName: pkg.Name, Contract: pkg.Contract, Managed: pkg.Managed, DisplayName: pkg.DisplayName, Description: pkg.Description, + }, def, false) + if a, err = pinVersion(a, pv, req.Version); err != nil { + return nil, err } return m.saveInstallation(ctx, auth, a, req.installationRequest, installed, false, store.Installed{}) } @@ -152,22 +177,42 @@ func (m *Module) updateInstallation(ctx context.Context, in *updateInstallationI 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) + pv, err := m.packageNamed(ctx, previous.PackageName) + if err != nil { + return nil, err + } + def, ok := pv.defaultVersion() + if !ok { + return nil, huma.NewError(http.StatusConflict, previous.PackageName+" has no default version") + } + next, err := pinVersion(withVersion(previous, def, false), pv, in.Body.Version) + if err != nil { + return nil, err + } + return m.saveInstallation(ctx, auth, next, in.Body, installed, true, previous) +} + +// pinVersion points a at the named version of its package, or leaves it on the +// default version when version is empty. +func pinVersion(a store.Installed, pv packageVersions, version string) (store.Installed, error) { + if version == "" { + return a, nil + } + v, ok := pv.version(version) + if !ok { + return store.Installed{}, errNoVersion(pv.pkg.Name, version) + } + return withVersion(a, v, true), nil } // 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) + if err := checkAccepted(a, req); err != nil { + return nil, err } settings, err := json.Marshal(req.Settings, json.FormatNilMapAsNull(false)) if err != nil { @@ -223,6 +268,29 @@ func (m *Module) packagesAndInstallations(ctx context.Context) ([]store.Package, return pkgs, installed, nil } +// checkAccepted bounds an installation of a catalogue version by what the +// instance accepted for that version: the version must be accepted, and the +// installation may reach only accepted hosts, see only accepted environment +// variables and fill only accepted credential slots. +func checkAccepted(a store.Installed, req installationRequest) error { + if !a.Managed { + return nil + } + held, ok, err := grantsOf(a.Accepted) + if err != nil { + return huma.NewError(http.StatusInternalServerError, err.Error()) + } + if !ok { + return huma.NewError(http.StatusConflict, fmt.Sprintf("the instance hasn't accepted %s %s", a.PackageName, a.Version)) + } + want := catalogue.Grants{Egress: req.Egress, Env: req.Env, Credentials: slices.Collect(maps.Keys(req.Credentials))}.Normalised() + if !held.Covers(want) { + return huma.NewError(http.StatusUnprocessableEntity, + fmt.Sprintf("%s %s isn't granted %v", a.PackageName, a.Version, held.Added(want))) + } + return 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 diff --git a/modules/connectors/internal/catalogue/catalogue_test.go b/modules/connectors/internal/catalogue/catalogue_test.go index 9eac83053..f0e19a6d8 100644 --- a/modules/connectors/internal/catalogue/catalogue_test.go +++ b/modules/connectors/internal/catalogue/catalogue_test.go @@ -60,10 +60,9 @@ func TestFetchRefusesAnArtifactWhoseDigestDoesNotMatch(t *testing.T) { } // TestAcceptRefusesGrantsTheExtensionNeverDeclared guards the grant boundary: -// an operator may narrow what an extension declared, never widen it. +// an operator may narrow what a version declared, never widen it. func TestAcceptRefusesGrantsTheExtensionNeverDeclared(t *testing.T) { declared := Grants{Egress: []string{"api.example.com"}, Env: []string{"HOME"}, Credentials: []string{"token"}} - state := Install(Pin{Version: "1.0.0", Digest: "d1", Declared: declared}) cases := []struct { name string @@ -74,84 +73,17 @@ func TestAcceptRefusesGrantsTheExtensionNeverDeclared(t *testing.T) { {"fewer than declared are accepted", Grants{Egress: []string{"api.example.com"}}, nil}, {"an undeclared host is refused", Grants{Egress: []string{"elsewhere.example.com"}}, ErrBeyondDeclared}, {"an undeclared credential is refused", Grants{Credentials: []string{"other"}}, ErrBeyondDeclared}, + {"the whole network is refused when hosts are declared", Grants{}, ErrBeyondDeclared}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - if _, err := state.Accept(c.grants); !errors.Is(err, c.wantErr) { + if _, err := Accept(declared, c.grants); !errors.Is(err, c.wantErr) { t.Fatalf("Accept() error = %v, want %v", err, c.wantErr) } }) } } -// TestAnUpdateThatAsksForMoreWaitsForApproval guards the update boundary: a -// pin that widens the grants changes nothing that runs until an operator -// approves it, and the approval accepts what that pin declares. -func TestAnUpdateThatAsksForMoreWaitsForApproval(t *testing.T) { - first := Pin{Version: "1.0.0", Digest: "d1", Declared: Grants{Credentials: []string{"token"}}} - state, err := Install(first).Accept(Grants{Credentials: []string{"token"}}) - if err != nil { - t.Fatal(err) - } - wider := Pin{Version: "1.1.0", Digest: "d2", Declared: Grants{Credentials: []string{"token"}, Env: []string{"HOME"}}} - - offered, applied := state.Offer(wider) - if applied { - t.Fatal("a wider update applied without approval") - } - if offered.Pending == nil || offered.Pending.Digest != "d2" { - t.Fatalf("Offer() pending = %+v, want d2", offered.Pending) - } - if offered.Current.Digest != "d1" || offered.Accepted == nil || len(offered.Accepted.Env) != 0 { - t.Fatalf("Offer() changed what runs: current %q accepted %+v", offered.Current.Digest, offered.Accepted) - } - - approved, err := offered.Approve() - if err != nil { - t.Fatal(err) - } - if approved.Current.Digest != "d2" || approved.Pending != nil { - t.Fatalf("Approve() current = %q pending = %+v", approved.Current.Digest, approved.Pending) - } - if approved.Accepted == nil || len(approved.Accepted.Env) != 1 || approved.Accepted.Env[0] != "HOME" { - t.Fatalf("Approve() accepted = %+v, want the pin's declared grants", approved.Accepted) - } -} - -// TestRollbackRestoresThePreviousGrants guards the rollback boundary: it -// restores the version and the grants accepted for that version, never the -// grants of the version it replaces. -func TestRollbackRestoresThePreviousGrants(t *testing.T) { - first := Pin{Version: "1.0.0", Digest: "d1", Declared: Grants{Credentials: []string{"token"}}} - state, err := Install(first).Accept(Grants{Credentials: []string{"token"}}) - if err != nil { - t.Fatal(err) - } - second := Pin{Version: "1.1.0", Digest: "d2", Declared: Grants{Credentials: []string{"token"}, Env: []string{"HOME"}}} - state, applied := state.Offer(second) - if applied { - t.Fatal("a wider update applied without approval") - } - state, err = state.Approve() - if err != nil { - t.Fatal(err) - } - if state.Accepted == nil || len(state.Accepted.Env) != 1 { - t.Fatalf("Approve() accepted = %+v, want HOME", state.Accepted) - } - - rolled, err := state.Rollback() - if err != nil { - t.Fatal(err) - } - if rolled.Current.Digest != "d1" { - t.Fatalf("Rollback() current = %q, want d1", rolled.Current.Digest) - } - if rolled.Accepted == nil || len(rolled.Accepted.Env) != 0 || len(rolled.Accepted.Credentials) != 1 { - t.Fatalf("Rollback() accepted = %+v, want the grants accepted for d1", rolled.Accepted) - } -} - // TestVerifyRefusesAForgedOrMalformedCatalogue guards the trust boundary: the // catalogue is read only when the configured key signs it, and an unsigned // ordering or a duplicate entry is refused even then. @@ -161,13 +93,15 @@ func TestVerifyRefusesAForgedOrMalformedCatalogue(t *testing.T) { t.Fatal(err) } digest := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - entry := `{"name":"example","contract":"connector","artifact":"example","digest":"` + digest + `"}` + entry := `{"name":"example","contract":"connector","versions":[{"version":"1.0.0","artifact":"example","digest":"` + digest + `"}]}` + twice := `{"name":"twice","contract":"connector","versions":[{"version":"1.0.0","artifact":"a","digest":"` + digest + `"},{"version":"1.0.0","artifact":"b","digest":"` + digest + `"}]}` signed := func(body string) []byte { return []byte(base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(body)))) } good := `{"issued_at":"2026-11-22T00:00:00Z","extensions":[` + entry + `]}` unsigned := `{"extensions":[` + entry + `]}` duplicate := `{"issued_at":"2026-11-22T00:00:00Z","extensions":[` + entry + `,` + entry + `]}` + versionTwice := `{"issued_at":"2026-11-22T00:00:00Z","extensions":[` + twice + `]}` _, other, err := ed25519.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) @@ -183,7 +117,8 @@ func TestVerifyRefusesAForgedOrMalformedCatalogue(t *testing.T) { {"bytes changed after signing are refused", good + " ", signed(good), false}, {"another key's signature is refused", good, []byte(base64.StdEncoding.EncodeToString(ed25519.Sign(other, []byte(good)))), false}, {"a catalogue with no issue time is refused", unsigned, signed(unsigned), false}, - {"a entry listed twice is refused", duplicate, signed(duplicate), false}, + {"an entry listed twice is refused", duplicate, signed(duplicate), false}, + {"a version listed twice is refused", versionTwice, signed(versionTwice), false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { diff --git a/modules/connectors/internal/catalogue/document.go b/modules/connectors/internal/catalogue/document.go index 1eb16f22d..d3369b1f1 100644 --- a/modules/connectors/internal/catalogue/document.go +++ b/modules/connectors/internal/catalogue/document.go @@ -10,18 +10,25 @@ import ( "regexp" "strings" "time" + + "golang.org/x/mod/semver" ) -// Entry is one extension a catalogue offers: what it is, the artifact to -// fetch and the digest that artifact must have, and the grants it asks for. +// Entry is one extension a catalogue offers, with every version it offers. type Entry struct { Name string `json:"name"` DisplayName string `json:"display_name"` Description string `json:"description"` // Contract is the extension contract the binary serves: connector, // secretengine or guard. - Contract string `json:"contract"` - Version string `json:"version"` + Contract string `json:"contract"` + Versions []Version `json:"versions"` +} + +// Version is one release of an extension: the artifact to fetch, the digest +// that artifact must have, the grants it asks for and the settings it takes. +type Version struct { + Version string `json:"version"` // Artifact is where the binary is fetched from: an https URL, or a path on // this host. A relative reference is read from beside the catalogue. Artifact string `json:"artifact"` @@ -29,6 +36,22 @@ type Entry struct { Digest string `json:"digest"` // Grants is what the extension asks to use. Grants Grants `json:"grants"` + // Settings are the values an operator enters, so the dashboard can show + // the form before the extension first runs. The running extension's own + // declaration is what its settings are checked against. + Settings []Setting `json:"settings,omitzero"` +} + +// Setting is one value an operator enters for an extension to run. Its fields +// match the setting an extension declares when it runs. +type Setting struct { + Key string `json:"key"` + Label string `json:"label"` + Description string `json:"description,omitempty"` + Secret bool `json:"secret,omitempty"` + Required bool `json:"required,omitempty"` + Type string `json:"type,omitempty"` + Options []string `json:"options,omitempty"` } // Document is a signed list of extensions. @@ -49,6 +72,47 @@ func (d Document) Entry(name string) (Entry, bool) { return Entry{}, false } +// Version returns the named version, or the latest when version is empty. +func (e Entry) Version(version string) (Version, bool) { + if version == "" { + return e.Latest() + } + for _, v := range e.Versions { + if v.Version == version { + return v, true + } + } + return Version{}, false +} + +// Latest returns the highest version by semantic version order. A version that +// isn't a semantic version sorts below every one that is. +func (e Entry) Latest() (Version, bool) { + if len(e.Versions) == 0 { + return Version{}, false + } + best := e.Versions[0] + for _, v := range e.Versions[1:] { + if Newer(v.Version, best.Version) { + best = v + } + } + return best, true +} + +// Newer reports whether version a is higher than b by semantic version order, +// with or without a leading "v". +func Newer(a, b string) bool { + return semver.Compare(canonical(a), canonical(b)) > 0 +} + +func canonical(v string) string { + if strings.HasPrefix(v, "v") { + return v + } + return "v" + v +} + var ( entryName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`) hexDigest = regexp.MustCompile(`^[a-f0-9]{64}$`) @@ -69,22 +133,37 @@ func NormalDigest(digest string) (string, error) { return d, nil } -// Normalised checks an entry and returns it with its digest and grants in -// their stored form. +// Normalised checks an entry and returns it with each version's digest and +// grants in their stored form. func (e Entry) Normalised() (Entry, error) { - d, err := NormalDigest(e.Digest) switch { case !entryName.MatchString(e.Name): return Entry{}, fmt.Errorf("catalogue entry %q: the name is lowercase letters, digits and hyphens", e.Name) - case err != nil: - return Entry{}, fmt.Errorf("catalogue entry %q: %w", e.Name, err) - case e.Artifact == "": - return Entry{}, fmt.Errorf("catalogue entry %q: an artifact is required", e.Name) case e.Contract == "": return Entry{}, fmt.Errorf("catalogue entry %q: a contract is required", e.Name) + case len(e.Versions) == 0: + return Entry{}, fmt.Errorf("catalogue entry %q: at least one version is required", e.Name) } - e.Digest = d - e.Grants = e.Grants.Normalised() + seen := make(map[string]bool, len(e.Versions)) + versions := make([]Version, 0, len(e.Versions)) + for _, v := range e.Versions { + d, err := NormalDigest(v.Digest) + switch { + case v.Version == "": + return Entry{}, fmt.Errorf("catalogue entry %q: a version is required", e.Name) + case seen[v.Version]: + return Entry{}, fmt.Errorf("catalogue entry %q: version %s is listed twice", e.Name, v.Version) + case err != nil: + return Entry{}, fmt.Errorf("catalogue entry %q %s: %w", e.Name, v.Version, err) + case v.Artifact == "": + return Entry{}, fmt.Errorf("catalogue entry %q %s: an artifact is required", e.Name, v.Version) + } + seen[v.Version] = true + v.Digest = d + v.Grants = v.Grants.Normalised() + versions = append(versions, v) + } + e.Versions = versions return e, nil } diff --git a/modules/connectors/internal/catalogue/lifecycle.go b/modules/connectors/internal/catalogue/lifecycle.go index ce6b527bb..463c590f3 100644 --- a/modules/connectors/internal/catalogue/lifecycle.go +++ b/modules/connectors/internal/catalogue/lifecycle.go @@ -5,123 +5,37 @@ import ( "fmt" ) -// Update policies. Manual is the default; an auto package follows the -// catalogue, with an update that asks for more still waiting for approval. +// Update policies. Manual is the default. An auto package moves its default +// version to the newest the catalogue offers when that version asks for no +// more than the current default was granted; one that asks for more waits for +// an operator to accept it. const ( PolicyManual = "manual" PolicyAuto = "auto" ) var ( - // ErrBeyondDeclared means an operator accepted grants the extension never + // ErrBeyondDeclared means an operator accepted grants the version never // declared. ErrBeyondDeclared = errors.New("the extension doesn't declare those grants") - // ErrNoPending means there is no update waiting for approval. - ErrNoPending = errors.New("the extension has no update waiting for approval") - // ErrNoPrevious means there is no earlier version to roll back to. - ErrNoPrevious = errors.New("the extension has no previous version") // ErrInvalidPolicy means the update policy is neither manual nor auto. ErrInvalidPolicy = errors.New("the update policy is manual or auto") ) -// Pin is one version of an extension: a binary on this host with the digest -// it was verified against and the grants it declared. -type Pin struct { - Version string `json:"version"` - Digest string `json:"digest"` - Path string `json:"path"` - Declared Grants `json:"declared"` -} - -// State is an installed extension's place in its lifecycle. The live pin is -// Current, and the grants it runs with are Accepted, never what any pin -// declares: a pin gains no grant until an operator accepts it. -type State struct { - Policy string `json:"policy"` - Current Pin `json:"current"` - // Accepted is what the operator granted Current. Nil until they have. - Accepted *Grants `json:"accepted"` - // Pending is an update that asks for more than Accepted. Current and - // Accepted stay as they were until it is approved. - Pending *Pin `json:"pending,omitzero"` - // Previous is the pin an update, approval or rollback replaced, with the - // grants accepted against it, so a rollback restores both. - Previous *Pin `json:"previous,omitzero"` - PreviousAccepted *Grants `json:"previous_accepted,omitzero"` -} - -// Install starts the lifecycle of pin: nothing is accepted yet. -func Install(pin Pin) State { - return State{Policy: PolicyManual, Current: pin} -} - -// Accept records the operator's grants for the current pin. They may be fewer -// than the pin declares and never more. -func (s State) Accept(grants Grants) (State, error) { +// Accept returns the grants an operator accepts for a version that declared +// declared. They may be fewer than declared and never more. +func Accept(declared, grants Grants) (Grants, error) { grants = grants.Normalised() - if !s.Current.Declared.Covers(grants) { - return State{}, ErrBeyondDeclared + if !declared.Normalised().Covers(grants) { + return Grants{}, ErrBeyondDeclared } - s.Accepted = &grants - return s, nil + return grants, nil } -// Widens reports whether next asks for more than the operator accepted. An -// extension never accepted holds nothing, so any pin is wider. -func (s State) Widens(next Pin) bool { - if s.Accepted == nil { - return true - } - return !s.Accepted.Covers(next.Declared) -} - -// Offer moves to next, a version the catalogue lists. One that asks for no -// more than was accepted applies at once, keeping the accepted grants. One that -// asks for more waits as pending. applied is false when nothing took effect -// yet. -func (s State) Offer(next Pin) (_ State, applied bool) { - if next.Digest == s.Current.Digest || (s.Pending != nil && s.Pending.Digest == next.Digest) { - return s, false - } - if s.Widens(next) { - s.Pending = &next - return s, false - } - return s.swap(next, s.Accepted), true -} - -// Approve applies the pending update and accepts the grants it declares. -func (s State) Approve() (State, error) { - if s.Pending == nil { - return State{}, ErrNoPending - } - declared := s.Pending.Declared - return s.swap(*s.Pending, &declared), nil -} - -// Rollback restores the previous pin with the grants accepted against it, never -// the grants of the pin it replaces. The replaced pin becomes the previous one. -func (s State) Rollback() (State, error) { - if s.Previous == nil { - return State{}, ErrNoPrevious - } - return s.swap(*s.Previous, s.PreviousAccepted), nil -} - -// swap makes next the live pin with accepted as its grants, and keeps the pin -// it replaces for a rollback. -func (s State) swap(next Pin, accepted *Grants) State { - replaced, held := s.Current, s.Accepted - s.Previous, s.PreviousAccepted = &replaced, held - s.Current, s.Accepted, s.Pending = next, accepted, nil - return s -} - -// SetPolicy changes whether the extension follows the catalogue on its own. -func (s State) SetPolicy(policy string) (State, error) { +// CheckPolicy refuses an update policy that is neither manual nor auto. +func CheckPolicy(policy string) error { if policy != PolicyManual && policy != PolicyAuto { - return State{}, fmt.Errorf("%w, not %q", ErrInvalidPolicy, policy) + return fmt.Errorf("%w, not %q", ErrInvalidPolicy, policy) } - s.Policy = policy - return s, nil + return nil } diff --git a/modules/connectors/internal/store/store.go b/modules/connectors/internal/store/store.go index af69f60da..fa72cb034 100644 --- a/modules/connectors/internal/store/store.go +++ b/modules/connectors/internal/store/store.go @@ -1,6 +1,6 @@ // 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. +// accepted and their versions, the installations that configure them at a +// scope, and the sealed credentials those installations use. package store import ( @@ -98,12 +98,17 @@ type Installed struct { 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 string `db:"contract"` + // VersionID and Version are the package version the installation runs: + // PinnedVersion when it is set, otherwise the package's default version. + VersionID uuid.UUID `db:"version_id"` + Version string `db:"version"` + PinnedVersion uuid.NullUUID `db:"pinned_version_id"` + Path string `db:"path"` + SHA256 string `db:"sha256"` + Egress Strings `db:"egress"` + Env Strings `db:"env"` + Settings jsontext.Value `db:"settings"` // 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 @@ -123,19 +128,30 @@ type Installed struct { // Enabled says whether the installation runs. One that is not enabled is // kept but never launched. Enabled bool `db:"enabled"` - // 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"` + // Managed says the package came from the catalogue; DisplayName and + // Description are the catalogue's. + Managed bool `db:"managed"` + DisplayName string `db:"display_name"` + Description string `db:"description"` + // Declared and Accepted are the version's declared and accepted grants, as + // JSON objects. Accepted is nil until the instance accepts the version. + Declared []byte `db:"declared"` + Accepted []byte `db:"accepted"` + // DeclaredSettings are the settings the version declared in the + // catalogue, as a JSON array. + DeclaredSettings []byte `db:"declared_settings"` } // 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` + p.contract, v.id AS version_id, v.version, i.package_version_id AS pinned_version_id, v.path, v.sha256, + i.egress, i.env, i.settings, i.credentials, i.args, i.url, i.tools, v.effects, v.capabilities, i.enabled, + p.managed, p.display_name, p.description, v.declared, v.accepted, v.settings AS declared_settings` -const installedFrom = ` FROM connectors.installations i JOIN connectors.packages p ON p.id = i.package_id` +const installedFrom = ` FROM connectors.installations i JOIN connectors.packages p ON p.id = i.package_id + JOIN connectors.package_versions v ON v.id = COALESCE(i.package_version_id, p.default_version_id)` // Contracts a package can serve. const ( @@ -204,13 +220,31 @@ type Package struct { ID uuid.UUID `db:"id"` Name string `db:"name"` Contract string `db:"contract"` + DisplayName string `db:"display_name"` + Description string `db:"description"` + Managed bool `db:"managed"` + UpdatePolicy string `db:"update_policy"` + // DefaultVersion is the version installations run unless they pin one. + DefaultVersion uuid.NullUUID `db:"default_version_id"` + AcceptedByID string `db:"accepted_by_id"` + AcceptedAt time.Time `db:"accepted_at"` +} + +// Version is one release of a package. Declared, Settings and Accepted are +// JSON; Accepted is nil until the instance accepts the version. +type Version struct { + ID uuid.UUID `db:"id"` + PackageID uuid.UUID `db:"package_id"` + Version string `db:"version"` Path string `db:"path"` SHA256 string `db:"sha256"` - Manifest []byte `db:"manifest"` + Declared []byte `db:"declared"` + Settings []byte `db:"settings"` + Accepted []byte `db:"accepted"` + AcceptedByID string `db:"accepted_by_id"` Capabilities []byte `db:"capabilities"` Effects []byte `db:"effects"` - AcceptedByID string `db:"accepted_by_id"` - AcceptedAt time.Time `db:"accepted_at"` + CreatedAt time.Time `db:"created_at"` } // Override records that an organisation or a person switched off an @@ -243,13 +277,172 @@ func (s *Store) List(ctx context.Context) ([]Installed, error) { 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 + SELECT id, name, contract, display_name, description, managed, update_policy, default_version_id, + accepted_by_id, accepted_at FROM connectors.packages ORDER BY name`); err != nil { return nil, fmt.Errorf("list packages: %w", err) } return out, nil } +const versionColumns = `id, package_id, version, path, sha256, declared, settings, accepted, accepted_by_id, + capabilities, effects, created_at` + +// Versions returns every version of every package, oldest first. +func (s *Store) Versions(ctx context.Context) ([]Version, error) { + var out []Version + if err := s.db.SelectContext(ctx, &out, `SELECT `+versionColumns+` FROM connectors.package_versions ORDER BY created_at, version`); err != nil { + return nil, fmt.Errorf("list package versions: %w", err) + } + return out, nil +} + +// Errors from changing a package's versions. +var ( + // ErrVersionExists means the package already has that version with a + // different digest. A version is immutable. + ErrVersionExists = errors.New("the package already has that version with a different digest") + // ErrContractChanged means a package of that name serves another contract. + ErrContractChanged = errors.New("a package of that name serves a different contract") + // ErrDefaultVersion means the version is the package's default. + ErrDefaultVersion = errors.New("the version is the package's default") + // ErrVersionPinned means an installation pins the version. + ErrVersionPinned = errors.New("an installation pins the version") +) + +// RegisterVersion records a version of p, creating p when it is new, and +// returns both as stored. A version already stored with the same digest is +// returned unchanged. The first version of a package becomes its default. +func (s *Store) RegisterVersion(ctx context.Context, p Package, v Version, by string) (Package, Version, error) { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err) + } + defer func() { _ = tx.Rollback() }() + p, v, err = registerVersion(ctx, tx, p, v, by) + if err != nil { + return Package{}, Version{}, err + } + if err := tx.Commit(); err != nil { + return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err) + } + return p, v, nil +} + +func registerVersion(ctx context.Context, tx *sqlx.Tx, p Package, v Version, by string) (Package, Version, error) { + if GroupOf(p.Contract) == "" { + return Package{}, Version{}, fmt.Errorf("register %q: unknown contract %q", p.Name, p.Contract) + } + var stored Package + err := tx.GetContext(ctx, &stored, ` + INSERT INTO connectors.packages (id, name, contract, display_name, description, managed, accepted_by_id) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (name) DO UPDATE + SET display_name = EXCLUDED.display_name, description = EXCLUDED.description, + managed = EXCLUDED.managed, updated_at = now() + RETURNING id, name, contract, display_name, description, managed, update_policy, default_version_id, + accepted_by_id, accepted_at`, + cmp.Or(p.ID, uuid.New()), p.Name, p.Contract, p.DisplayName, p.Description, p.Managed, by) + if err != nil { + return Package{}, Version{}, fmt.Errorf("register package %q: %w", p.Name, err) + } + if stored.Contract != p.Contract { + return Package{}, Version{}, fmt.Errorf("%s: %w", p.Name, ErrContractChanged) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO connectors.package_versions + (id, package_id, version, path, sha256, declared, settings, accepted, accepted_by_id, effects) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (package_id, version) DO NOTHING`, + uuid.New(), stored.ID, v.Version, v.Path, v.SHA256, orDefault(v.Declared, "{}"), orDefault(v.Settings, "[]"), + nilIfEmpty(v.Accepted), v.AcceptedByID, nilIfEmpty(v.Effects)); err != nil { + return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err) + } + var got Version + if err := tx.GetContext(ctx, &got, `SELECT `+versionColumns+` FROM connectors.package_versions + WHERE package_id = $1 AND version = $2`, stored.ID, v.Version); err != nil { + return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err) + } + if got.SHA256 != v.SHA256 { + return Package{}, Version{}, fmt.Errorf("%s %s: %w", p.Name, v.Version, ErrVersionExists) + } + if !stored.DefaultVersion.Valid { + if err := setDefault(ctx, tx, stored.ID, got.ID); err != nil { + return Package{}, Version{}, err + } + stored.DefaultVersion = uuid.NullUUID{UUID: got.ID, Valid: true} + } + return stored, got, nil +} + +func setDefault(ctx context.Context, tx sqlx.ExecerContext, packageID, versionID uuid.UUID) error { + res, err := tx.ExecContext(ctx, ` + UPDATE connectors.packages SET default_version_id = $2, updated_at = now() + WHERE id = $1 AND EXISTS (SELECT 1 FROM connectors.package_versions WHERE id = $2 AND package_id = $1)`, + packageID, versionID) + if err != nil { + return fmt.Errorf("set default version: %w", err) + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return fmt.Errorf("set default version: no such version of the package") + } + return nil +} + +// AcceptVersion records the grants the instance accepted for a version. +func (s *Store) AcceptVersion(ctx context.Context, versionID uuid.UUID, accepted []byte, by string) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE connectors.package_versions SET accepted = $2, accepted_by_id = $3 WHERE id = $1`, + versionID, accepted, by); err != nil { + return fmt.Errorf("accept version: %w", err) + } + return nil +} + +// SetDefaultVersion makes a version its package's default. +func (s *Store) SetDefaultVersion(ctx context.Context, packageID, versionID uuid.UUID) error { + return setDefault(ctx, s.db, packageID, versionID) +} + +// SetUpdatePolicy records whether a package follows the catalogue on its own. +func (s *Store) SetUpdatePolicy(ctx context.Context, packageID uuid.UUID, policy string) error { + if _, err := s.db.ExecContext(ctx, `UPDATE connectors.packages SET update_policy = $2, updated_at = now() WHERE id = $1`, + packageID, policy); err != nil { + return fmt.Errorf("set update policy: %w", err) + } + return nil +} + +// DeleteVersion removes a version that is neither its package's default nor +// pinned by an installation. +func (s *Store) DeleteVersion(ctx context.Context, versionID uuid.UUID) error { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return fmt.Errorf("remove version: %w", err) + } + defer func() { _ = tx.Rollback() }() + var isDefault, pinned bool + if err := tx.GetContext(ctx, &isDefault, `SELECT EXISTS (SELECT 1 FROM connectors.packages WHERE default_version_id = $1)`, versionID); err != nil { + return fmt.Errorf("remove version: %w", err) + } + if isDefault { + return ErrDefaultVersion + } + if err := tx.GetContext(ctx, &pinned, `SELECT EXISTS (SELECT 1 FROM connectors.installations WHERE package_version_id = $1)`, versionID); err != nil { + return fmt.Errorf("remove version: %w", err) + } + if pinned { + return ErrVersionPinned + } + if _, err := tx.ExecContext(ctx, `DELETE FROM connectors.package_versions WHERE id = $1`, versionID); err != nil { + return fmt.Errorf("remove version: %w", err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("remove version: %w", err) + } + return nil +} + // Overrides returns every switched-off inherited installation. func (s *Store) Overrides(ctx context.Context) ([]Override, error) { var out []Override @@ -279,34 +472,38 @@ func (s *Store) SetOverride(ctx context.Context, o Override, off bool, by string 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. +// SaveInstalled records a package accepted by path and one installation of it +// in one transaction. The binary is stored as an accepted version, named +// in.Version, which becomes the package's default; the earlier installation of +// that name at the same owner is replaced. 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 Installed{}, fmt.Errorf("save %q: %w", in.Name, err) } defer func() { _ = tx.Rollback() }() - 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) + pkg, v, err := registerVersion(ctx, tx, + Package{ID: in.PackageID, Name: in.PackageName, Contract: in.Contract}, + Version{Version: in.Version, Path: in.Path, SHA256: in.SHA256, Accepted: []byte(`{}`), AcceptedByID: by, Effects: in.Effects}, + by) + if err != nil { + return Installed{}, err } + if len(in.Effects) > 0 { + if _, err := tx.ExecContext(ctx, `UPDATE connectors.package_versions SET effects = $2 WHERE id = $1`, v.ID, in.Effects); err != nil { + return Installed{}, fmt.Errorf("save %q: %w", in.Name, err) + } + } + if err := setDefault(ctx, tx, pkg.ID, v.ID); err != nil { + return Installed{}, err + } + in.PackageID, in.VersionID, in.PinnedVersion = pkg.ID, v.ID, uuid.NullUUID{} 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 { + if err := setCapabilities(ctx, tx, in.VersionID, capabilities); err != nil { return Installed{}, err } } @@ -330,7 +527,7 @@ func (s *Store) SaveInstallation(ctx context.Context, in Installed, capabilities return Installed{}, err } if capabilities != nil { - if err := setCapabilities(ctx, tx, in.PackageID, capabilities); err != nil { + if err := setCapabilities(ctx, tx, in.VersionID, capabilities); err != nil { return Installed{}, err } } @@ -344,23 +541,25 @@ func upsertInstallation(ctx context.Context, tx *sqlx.Tx, in Installed) (uuid.UU 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) + (id, package_id, scope, org_id, person_id, name, settings, egress, env, credentials, args, url, tools, enabled, + package_version_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) ON CONFLICT (scope, org_id, person_id, name) DO UPDATE - SET package_id = EXCLUDED.package_id, settings = EXCLUDED.settings, egress = EXCLUDED.egress, + SET package_id = EXCLUDED.package_id, package_version_id = EXCLUDED.package_version_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) + orDefault(in.Credentials, "{}"), in.Args, in.URL, orDefault(in.Tools, "[]"), in.Enabled, in.PinnedVersion) if err != nil { 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 { +func setCapabilities(ctx context.Context, tx *sqlx.Tx, versionID uuid.UUID, capabilities jsontext.Value) error { + if _, err := tx.ExecContext(ctx, `UPDATE connectors.package_versions SET capabilities = $2 WHERE id = $1`, versionID, []byte(capabilities)); err != nil { return fmt.Errorf("store capabilities: %w", err) } return nil @@ -380,9 +579,9 @@ func nilIfEmpty(b []byte) []byte { 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 { +// SetCapabilities records what a connector version declared when it loaded. +func (s *Store) SetCapabilities(ctx context.Context, versionID uuid.UUID, capabilities jsontext.Value) error { + if _, err := s.db.ExecContext(ctx, `UPDATE connectors.package_versions SET capabilities = $2 WHERE id = $1`, versionID, []byte(capabilities)); err != nil { return fmt.Errorf("store capabilities: %w", err) } return nil diff --git a/modules/connectors/list.go b/modules/connectors/list.go index 69c7421dc..d367cc130 100644 --- a/modules/connectors/list.go +++ b/modules/connectors/list.go @@ -61,21 +61,19 @@ type ExtensionView struct { // Capabilities is what a connector declared when it last loaded. It is // absent for other packages and for a connector that has never loaded. Capabilities *Capabilities `json:"capabilities,omitempty"` - // Enabled says whether an accepted package runs. A package accepted by path - // runs while its digest matches; one installed from the catalogue runs once - // its grants are accepted and it is enabled. + // Enabled says whether the installation runs. Enabled bool `json:"enabled"` + // VersionPinned says the installation runs Version whatever its package's + // default version is. + VersionPinned bool `json:"version_pinned"` // Managed says the package was installed from the catalogue. - Managed bool `json:"managed"` - DisplayName string `json:"display_name,omitempty"` - Description string `json:"description,omitempty"` - Declared *catalogue.Grants `json:"declared,omitempty"` - Accepted *catalogue.Grants `json:"accepted,omitempty"` - // Pending is an update waiting for approval, with what it adds to the - // accepted grants. - Pending *PendingView `json:"pending,omitempty"` - CanRollback bool `json:"can_rollback"` - UpdatePolicy string `json:"update_policy,omitempty"` + Managed bool `json:"managed"` + DisplayName string `json:"display_name,omitempty"` + Description string `json:"description,omitempty"` + // Declared and Accepted are the grants the version declared and the grants + // the instance accepted for it, for a package from the catalogue. + Declared *catalogue.Grants `json:"declared,omitempty"` + Accepted *catalogue.Grants `json:"accepted,omitempty"` } // list returns the installations of one contract the caller can see, in name @@ -155,25 +153,53 @@ func (m *Module) viewOf(a store.Installed, editable bool) (ExtensionView, error) return ExtensionView{}, fmt.Errorf("capabilities: %w", err) } } - 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 { + state, reason, _, schema := m.stateOf(a) + schema, err := formSchema(a, schema, editable) + if err != nil { return ExtensionView{}, err - } else if ok { - managed := managedView(rec) - view.Managed = true - view.DisplayName, view.Description = managed.DisplayName, managed.Description - view.Declared, view.Accepted = &managed.Declared, managed.Accepted - view.Pending, view.CanRollback, view.UpdatePolicy = managed.Pending, managed.CanRollback, managed.UpdatePolicy - view.Version = rec.State.Current.Version + } + view.State, view.Error, view.Version, view.SettingsSchema = state, reason, a.Version, schema + view.Enabled, view.VersionPinned = a.Enabled, a.PinnedVersion.Valid + view.Managed, view.DisplayName, view.Description = a.Managed, a.DisplayName, a.Description + if a.Managed { + if view.Declared, view.Accepted, err = versionGrants(a); err != nil { + return ExtensionView{}, err + } } return view, nil } +// formSchema is the settings form an installation shows. A stopped extension's +// form comes from what its version declared in the catalogue, and a running +// one's own declaration replaces it. A caller who may not change the +// installation gets none. +func formSchema(a store.Installed, running []Setting, editable bool) ([]Setting, error) { + switch { + case !editable: + return []Setting{}, nil + case running != nil: + return running, nil + } + return settingsOf(a.DeclaredSettings) +} + +// versionGrants returns what an installation's version declared and what the +// instance accepted for it, nil until accepted. +func versionGrants(a store.Installed) (declared, accepted *catalogue.Grants, err error) { + d, _, err := grantsOf(a.Declared) + if err != nil { + return nil, nil, err + } + held, ok, err := grantsOf(a.Accepted) + if err != nil { + return nil, nil, err + } + if ok { + accepted = &held + } + return &d, accepted, nil +} + // stateOf reports whether a package is running, and what it declared. func (m *Module) stateOf(a store.Installed) (state, reason, version string, schema []Setting) { id := a.ID.String() diff --git a/modules/connectors/mcpaccept.go b/modules/connectors/mcpaccept.go index ad5ba0c2e..b1307a5a9 100644 --- a/modules/connectors/mcpaccept.go +++ b/modules/connectors/mcpaccept.go @@ -1,6 +1,7 @@ package connectors import ( + "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" @@ -215,7 +216,7 @@ func (r mcpRequest) accepted(name string) (store.Installed, error) { } 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, + Version: localVersion(cmp.Or(r.SHA256, r.URL)), 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, }, nil diff --git a/modules/connectors/module.go b/modules/connectors/module.go index 45de7c10b..4ee8b3d12 100644 --- a/modules/connectors/module.go +++ b/modules/connectors/module.go @@ -37,7 +37,7 @@ type Module struct { sealer *seal.Sealer log *slog.Logger // sources and fetcher read the catalogue and its artifacts, and pkgMu - // serialises changes to an installed package's lifecycle. + // serialises changes to a package's versions. sources sourceStore fetcher *catalogue.Fetcher pkgMu sync.Mutex @@ -85,7 +85,7 @@ 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 + SetCapabilities(ctx context.Context, versionID 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) } @@ -97,6 +97,16 @@ type packageStore interface { DeletePackage(ctx context.Context, name string) (bool, error) } +// versionStore is where the versions of those packages are kept. +type versionStore interface { + Versions(ctx context.Context) ([]store.Version, error) + RegisterVersion(ctx context.Context, p store.Package, v store.Version, by string) (store.Package, store.Version, error) + AcceptVersion(ctx context.Context, versionID uuid.UUID, accepted []byte, by string) error + SetDefaultVersion(ctx context.Context, packageID, versionID uuid.UUID) error + SetUpdatePolicy(ctx context.Context, packageID uuid.UUID, policy string) error + DeleteVersion(ctx context.Context, versionID uuid.UUID) error +} + // credentialStore is where sealed credentials are kept. type credentialStore interface { Credentials(ctx context.Context) ([]store.Credential, error) @@ -107,6 +117,7 @@ type credentialStore interface { type registry interface { installationStore packageStore + versionStore credentialStore } @@ -594,7 +605,7 @@ func (m *Module) storeCapabilities(ctx context.Context, a store.Installed, c *Co if save != nil { return save(ctx, raw) } - return m.store.SetCapabilities(ctx, a.PackageID, raw) + return m.store.SetCapabilities(ctx, a.VersionID, raw) } // refSuffix marks a setting that names a secret rather than holding one. The diff --git a/modules/connectors/packages.go b/modules/connectors/packages.go index 0c3060d52..4b5bb3e05 100644 --- a/modules/connectors/packages.go +++ b/modules/connectors/packages.go @@ -1,13 +1,12 @@ package connectors import ( - "bytes" + "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" - "maps" "net/http" "slices" "time" @@ -21,59 +20,172 @@ import ( "github.com/samcharles93/archie-core/modules/governance" ) -// packageRecord is the lifecycle of an extension installed from the catalogue, -// as it is stored on its accepted row. -type packageRecord struct { - DisplayName string `json:"display_name"` - Description string `json:"description"` - State catalogue.State `json:"state"` +// grantsOf decodes stored grants; ok is false when none are stored. +func grantsOf(raw []byte) (g catalogue.Grants, ok bool, err error) { + if len(raw) == 0 { + return catalogue.Grants{}, false, nil + } + if err := json.Unmarshal(raw, &g); err != nil { + return catalogue.Grants{}, false, fmt.Errorf("grants: %w", err) + } + return g.Normalised(), true, nil } -// packageOf reads a row's lifecycle; ok is false for a package accepted by -// path. -func packageOf(a store.Installed) (rec packageRecord, ok bool, err error) { - if len(a.Manifest) == 0 { - return packageRecord{}, false, nil +// settingsOf decodes the settings a version declared in the catalogue. +func settingsOf(raw []byte) ([]Setting, error) { + out := []Setting{} + if len(raw) == 0 { + return out, nil } - if err := json.Unmarshal(a.Manifest, &rec); err != nil { - return packageRecord{}, false, fmt.Errorf("package %q: %w", a.Name, err) + if err := json.Unmarshal(raw, &out); err != nil { + return nil, fmt.Errorf("declared settings: %w", err) } - return rec, true, nil + return out, nil } -// 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.Installed, rec packageRecord, enabled bool) (store.Installed, error) { - raw, err := json.Marshal(rec) - if err != nil { - return store.Installed{}, err - } - slots, err := decodeSlots(base.Credentials) - if err != nil { - return store.Installed{}, err - } - granted := catalogue.Grants{} - if g := rec.State.Accepted; g != nil { - granted = *g - } - 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.Installed{}, err - } - base.Path, base.SHA256 = rec.State.Current.Path, rec.State.Current.Digest - base.Egress, base.Env = granted.Egress, granted.Env - base.Manifest = raw - base.Enabled = enabled && rec.State.Accepted != nil - return base, nil +// packageVersions is one package with its versions, as the store holds them. +type packageVersions struct { + pkg store.Package + versions []store.Version } -// restarts reports whether a change to the row needs the process restarted. -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) +// version returns the named version of the package. +func (p packageVersions) version(name string) (store.Version, bool) { + i := slices.IndexFunc(p.versions, func(v store.Version) bool { return v.Version == name }) + if i < 0 { + return store.Version{}, false + } + return p.versions[i], true +} + +// defaultVersion returns the version installations run unless they pin one. +func (p packageVersions) defaultVersion() (store.Version, bool) { + i := slices.IndexFunc(p.versions, func(v store.Version) bool { return v.ID == p.pkg.DefaultVersion.UUID }) + if i < 0 { + return store.Version{}, false + } + return p.versions[i], true +} + +// packageNamed reads a package and its versions; a missing package is a 404. +func (m *Module) packageNamed(ctx context.Context, name string) (packageVersions, error) { + pkgs, err := m.store.Packages(ctx) + if err != nil { + m.log.ErrorContext(ctx, "list packages", "error", err) + return packageVersions{}, huma.NewError(http.StatusInternalServerError, "couldn't read the packages") + } + i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == name }) + if i < 0 { + return packageVersions{}, errNoPackage(name) + } + all, err := m.store.Versions(ctx) + if err != nil { + m.log.ErrorContext(ctx, "list package versions", "error", err) + return packageVersions{}, huma.NewError(http.StatusInternalServerError, "couldn't read the package versions") + } + out := packageVersions{pkg: pkgs[i]} + for _, v := range all { + if v.PackageID == pkgs[i].ID { + out.versions = append(out.versions, v) + } + } + return out, nil +} + +// withVersion points a at version v of its package: an installation runs the +// binary of the version it pins, or of its package's default. +func withVersion(a store.Installed, v store.Version, pinned bool) store.Installed { + a.VersionID, a.Version, a.Path, a.SHA256 = v.ID, v.Version, v.Path, v.SHA256 + a.Declared, a.Accepted, a.DeclaredSettings = v.Declared, v.Accepted, v.Settings + a.Capabilities, a.Effects = v.Capabilities, v.Effects + a.PinnedVersion = uuid.NullUUID{} + if pinned { + a.PinnedVersion = uuid.NullUUID{UUID: v.ID, Valid: true} + } + return a +} + +// register fetches a version the catalogue offers and records it, not yet +// accepted. +func (m *Module) register(ctx context.Context, location string, entry catalogue.Entry, v catalogue.Version) (store.Package, store.Version, error) { + if !slices.Contains(catalogueContracts, entry.Contract) { + return store.Package{}, store.Version{}, huma.NewError(http.StatusUnprocessableEntity, + fmt.Sprintf("%s serves contract %q, which a catalogue doesn't install", entry.Name, entry.Contract)) + } + ref, err := catalogue.Resolve(location, v.Artifact) + if err != nil { + return store.Package{}, store.Version{}, err + } + path, err := m.fetcher.Fetch(ctx, entry.Name, ref, v.Digest) + if err != nil { + return store.Package{}, store.Version{}, fmt.Errorf("%s %s: %w", entry.Name, v.Version, err) + } + declared, err := json.Marshal(v.Grants.Normalised()) + if err != nil { + return store.Package{}, store.Version{}, err + } + settings, err := json.Marshal(v.Settings, json.FormatNilSliceAsNull(false)) + if err != nil { + return store.Package{}, store.Version{}, err + } + pkg, ver, err := m.store.RegisterVersion(ctx, + store.Package{Name: entry.Name, Contract: entry.Contract, DisplayName: entry.DisplayName, Description: entry.Description, Managed: true}, + store.Version{Version: v.Version, Path: path, SHA256: v.Digest, Declared: declared, Settings: settings}, + governance.CallerID(ctx)) + if err != nil { + return store.Package{}, store.Version{}, err + } + m.log.InfoContext(ctx, "package version registered", "audit", true, "action", "package.register", + "package", entry.Name, "version", v.Version, "digest", v.Digest) + return pkg, ver, nil +} + +// accept records the grants the instance accepts for a version: the declared +// grants narrowed to want, where a nil list keeps what was declared. +func (m *Module) acceptGrants(ctx context.Context, v store.Version, want *grantsRequest) (catalogue.Grants, error) { + declared, _, err := grantsOf(v.Declared) + if err != nil { + return catalogue.Grants{}, err + } + grants := declared + if want != nil { + if want.Egress != nil { + grants.Egress = want.Egress + } + if want.Env != nil { + grants.Env = want.Env + } + } + accepted, err := catalogue.Accept(declared, grants) + if err != nil { + return catalogue.Grants{}, err + } + raw, err := json.Marshal(accepted) + if err != nil { + return catalogue.Grants{}, err + } + if err := m.store.AcceptVersion(ctx, v.ID, raw, governance.CallerID(ctx)); err != nil { + return catalogue.Grants{}, err + } + m.log.InfoContext(ctx, "package version accepted", "audit", true, "action", "package.accept", + "version_id", v.ID.String(), "version", v.Version) + return accepted, nil +} + +// relaunchFollowers restarts the installations of a package that run its +// default version, so they run the version it now names. skip is one already +// restarted. +func (m *Module) relaunchFollowers(ctx context.Context, packageID uuid.UUID, skip ...uuid.UUID) { + installed, err := m.refresh(ctx) + if err != nil { + m.log.ErrorContext(ctx, "read installations to restart", "package_id", packageID.String(), "error", err) + return + } + for _, a := range ordered(installed) { + if a.PackageID == packageID && !a.PinnedVersion.Valid && !slices.Contains(skip, a.ID) { + _ = m.launch(ctx, a) + } + } } // instanceRow returns the instance installation of name; ok is false when @@ -90,8 +202,8 @@ func (m *Module) instanceRow(ctx context.Context, name string) (a store.Installe return installed[i], true, nil } -// persistInstance stores an instance installation together with its package, -// accepted by the caller. +// persistInstance stores an instance installation together with the package +// version it runs, 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) { @@ -99,365 +211,322 @@ func (m *Module) persistInstance(ctx context.Context) persistFunc { } } -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.Installed, packageRecord, error) { - accepted, err := m.store.List(ctx) - if err != nil { - return store.Installed{}, packageRecord{}, err - } - i := slices.IndexFunc(accepted, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == name }) - if i < 0 { - return store.Installed{}, packageRecord{}, fmt.Errorf("no extension named %s: %w", name, errNotManaged) - } - rec, ok, err := packageOf(accepted[i]) - if err != nil { - return store.Installed{}, packageRecord{}, err - } - if !ok { - return store.Installed{}, packageRecord{}, fmt.Errorf("%s is accepted by path: %w", name, errNotManaged) - } - return accepted[i], rec, nil -} - -// lifecycleError maps what a lifecycle change returns to an HTTP status. -func (m *Module) lifecycleError(ctx context.Context, err error) error { +// packageError maps what a version change returns to an HTTP status. +func (m *Module) packageError(ctx context.Context, err error) error { var status *huma.ErrorModel switch { case errors.As(err, &status): return err - case errors.Is(err, errNotManaged): - return huma.NewError(http.StatusNotFound, err.Error()) - case errors.Is(err, catalogue.ErrBeyondDeclared), errors.Is(err, catalogue.ErrDigestMismatch): + case errors.Is(err, catalogue.ErrBeyondDeclared), errors.Is(err, catalogue.ErrDigestMismatch), + errors.Is(err, store.ErrVersionExists), errors.Is(err, store.ErrContractChanged): return huma.NewError(http.StatusUnprocessableEntity, err.Error()) - case errors.Is(err, catalogue.ErrNoPending), errors.Is(err, catalogue.ErrNoPrevious): + case errors.Is(err, store.ErrDefaultVersion), errors.Is(err, store.ErrVersionPinned): return huma.NewError(http.StatusConflict, err.Error()) case errors.Is(err, catalogue.ErrInvalidPolicy): return huma.NewError(http.StatusBadRequest, err.Error()) case errors.Is(err, errNoSource), errors.Is(err, catalogue.ErrBadSignature), errors.Is(err, catalogue.ErrStale): return catalogueError(err) } - m.log.ErrorContext(ctx, "extension lifecycle", "error", err) - return huma.NewError(http.StatusInternalServerError, "couldn't change the extension") + m.log.ErrorContext(ctx, "change package", "error", err) + return huma.NewError(http.StatusInternalServerError, "couldn't change the package") } -// 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.Installed) error { - persist := m.persistInstance(ctx) - if !restarts(old, next) { - 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, 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 +// grantsRequest is what an operator accepts for a version and gives an +// installation. A nil Egress or Env keeps what the version declared. +type grantsRequest struct { + Egress []string `json:"egress,omitempty" doc:"Every host the extension may reach. Omitted: the hosts the version declares"` + Env []string `json:"env,omitempty" doc:"Host environment variables the extension may see. Omitted: those the version declares"` } -// 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) { +// installInput installs an extension from the catalogue in one step: fetch the +// version, accept its grants, and create and start an installation. +type installInput struct { + Name string `path:"name"` + Body struct { + Version string `json:"version,omitzero" doc:"The catalogue version to install. Default: the latest"` + Scope string `json:"scope,omitzero" enum:"instance,org,person" doc:"Who owns the installation. Default: the instance"` + // Installation is what a binding calls the installation; the + // default is the package's name. + Installation string `json:"installation,omitzero"` + grantsRequest + Settings map[string]string `json:"settings,omitzero"` + Credentials map[string]string `json:"credentials,omitzero" doc:"Each credential slot and the credential, by name, that fills it"` + Enabled bool `json:"enabled"` + } +} + +func (m *Module) install(ctx context.Context, in *installInput) (*httpapi.Reply[ExtensionView], error) { + m.pkgMu.Lock() + defer m.pkgMu.Unlock() + req := in.Body + 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 + } installed, err := m.store.List(ctx) if err != nil { - m.log.ErrorContext(ctx, "read installations to restart", "package", changed.PackageName, "error", err) - return + return nil, m.packageError(ctx, err) } - for _, a := range ordered(installed) { - if a.PackageID != changed.PackageID || a.ID == changed.ID { - continue - } - _ = m.launch(ctx, a) + name := cmp.Or(req.Installation, in.Name) + if !validName.MatchString(name) { + return nil, huma.NewError(http.StatusBadRequest, "an installation needs a lowercase name") } -} - -// extensionName is the path of an operation on one installed extension. -type extensionName struct { - Name string `path:"name"` -} - -// Lifecycle is the result of a change to an installed extension. -type Lifecycle struct { - Name string `json:"name"` - Version string `json:"version"` - Digest string `json:"digest"` - // Pending is set when an update asks for more than was accepted and waits - // for approval. - Pending bool `json:"pending"` - Enabled bool `json:"enabled"` -} - -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, - }) -} - -// change applies one lifecycle step to an installed extension. -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) + 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)) + } + pkg, ver, accepted, err := m.fetchAccepted(ctx, in.Name, req.Version, &req.grantsRequest) if err != nil { - return nil, m.lifecycleError(ctx, err) + return nil, m.packageError(ctx, err) } - next, nextRec, err := step(old, rec) - if err != nil { - return nil, m.lifecycleError(ctx, err) + a := withVersion(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, Managed: true, DisplayName: pkg.DisplayName, Description: pkg.Description, + }, ver, pkg.DefaultVersion.UUID != ver.ID) + egress, env := req.Egress, req.Env + if egress == nil { + egress = accepted.Egress } - if err := m.replace(ctx, old, next); err != nil { - return nil, m.lifecycleError(ctx, err) + if env == nil { + env = accepted.Env } - m.log.InfoContext(ctx, "extension changed", "audit", true, "action", "extension."+action, "package", name, - "digest", nextRec.State.Current.Digest) - return lifecycleOf(next, nextRec), nil + return m.saveInstallation(ctx, auth, a, installationRequest{ + Settings: req.Settings, Egress: egress, Env: env, Credentials: req.Credentials, Enabled: req.Enabled, + }, installed, false, store.Installed{}) } -func (m *Module) install(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) { - m.pkgMu.Lock() - defer m.pkgMu.Unlock() +// fetchAccepted fetches a catalogue version of name and accepts it with want +// narrowing what it declared. A version already accepted keeps its grants, so +// installing it again can't narrow what its other installations were given. +func (m *Module) fetchAccepted(ctx context.Context, name, version string, want *grantsRequest) (store.Package, store.Version, catalogue.Grants, error) { doc, location, err := m.readCatalogue(ctx) if err != nil { - return nil, m.lifecycleError(ctx, err) + return store.Package{}, store.Version{}, catalogue.Grants{}, err } - entry, ok := doc.Entry(in.Name) - if !ok { - return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s", in.Name)) - } - 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) - if err != nil { - return nil, m.lifecycleError(ctx, err) - } - 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) - if err != nil { - return nil, m.lifecycleError(ctx, err) - } - rec := packageRecord{DisplayName: entry.DisplayName, Description: entry.Description, State: catalogue.Install(pin)} - 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 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) - return lifecycleOf(row, rec), nil -} - -// fetchPin downloads the artifact an entry names and keeps it only if it -// hashes to the digest the entry pins. -func (m *Module) fetchPin(ctx context.Context, location string, entry catalogue.Entry) (catalogue.Pin, error) { - ref, err := catalogue.Resolve(location, entry.Artifact) - if err != nil { - return catalogue.Pin{}, err - } - path, err := m.fetcher.Fetch(ctx, entry.Name, ref, entry.Digest) - if err != nil { - return catalogue.Pin{}, fmt.Errorf("%s: %w", entry.Name, err) - } - return catalogue.Pin{Version: entry.Version, Digest: entry.Digest, Path: path, Declared: entry.Grants}, nil -} - -// grantsRequest is what an operator accepts for an installed extension. -type grantsRequest struct { - Egress []string `json:"egress,omitzero" doc:"Every host the extension may reach; empty leaves it unconfined, which only an extension that declares no hosts may be given"` - Env []string `json:"env,omitzero" doc:"Host environment variables the extension may see"` - // Credentials maps each credential slot to a credential by name. - Credentials map[string]string `json:"credentials,omitzero"` - Settings map[string]string `json:"settings,omitzero"` -} - -// acceptGrants records what an operator grants an installed extension. A -// request with no body accepts exactly what the extension declared; a body may -// narrow those grants and names the credential each slot resolves through. -type acceptGrantsInput struct { - Name string `path:"name"` - Body *grantsRequest -} - -func (m *Module) acceptGrants(ctx context.Context, in *acceptGrantsInput) (*httpapi.Reply[Lifecycle], 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.Installed{}, rec, err - } - slots, err := json.Marshal(in.Body.Credentials, json.FormatNilMapAsNull(false)) - if err != nil { - return store.Installed{}, rec, err - } - a.Settings, a.Credentials = settings, slots - } - state, err := rec.State.Accept(grants) - if err != nil { - return store.Installed{}, rec, err - } - rec.State = state - row, err := rowOf(a, rec, a.Enabled) - return row, rec, err - }) -} - -// putExtensionSettings changes an installed extension's settings and restarts -// it with them. A setting whose name ends in _ref names a secret engine and -// key; its value is never stored here. -type extensionSettingsInput struct { - Name string `path:"name"` - - Body struct { - Settings map[string]string `json:"settings,omitzero"` - } -} - -func (m *Module) putExtensionSettings(ctx context.Context, in *extensionSettingsInput) (*httpapi.Reply[Lifecycle], error) { - settings, err := json.Marshal(in.Body.Settings, json.FormatNilMapAsNull(false)) - if err != nil { - return nil, huma.NewError(http.StatusBadRequest, err.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 - }) -} - -func (m *Module) updateExtension(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) { - doc, location, err := m.readCatalogue(ctx) - if err != nil { - return nil, m.lifecycleError(ctx, err) - } - return m.updateFrom(ctx, doc, location, in.Name) -} - -// updateFrom moves name to the digest doc pins for it. An update that asks for -// no more than was accepted applies; one that asks for more waits for approval -// and changes nothing that runs. -func (m *Module) updateFrom(ctx context.Context, doc catalogue.Document, location, name string) (*httpapi.Reply[Lifecycle], error) { entry, ok := doc.Entry(name) if !ok { - return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s", name)) + return store.Package{}, store.Version{}, catalogue.Grants{}, huma.NewError(http.StatusNotFound, "the catalogue doesn't list "+name) } - 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.Installed{}, rec, err - } - rec.State, _ = rec.State.Offer(pin) - rec.DisplayName, rec.Description = entry.DisplayName, entry.Description - row, err := rowOf(a, rec, a.Enabled) - return row, rec, err - }) + cv, ok := entry.Version(version) + if !ok { + return store.Package{}, store.Version{}, catalogue.Grants{}, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s %s", name, version)) + } + pkg, ver, err := m.register(ctx, location, entry, cv) + if err != nil { + return store.Package{}, store.Version{}, catalogue.Grants{}, err + } + accepted, ok, err := grantsOf(ver.Accepted) + if err != nil || ok { + return pkg, ver, accepted, err + } + if accepted, err = m.acceptGrants(ctx, ver, want); err != nil { + return store.Package{}, store.Version{}, catalogue.Grants{}, err + } + ver.Accepted, err = json.Marshal(accepted) + return pkg, ver, accepted, err } -func (m *Module) approveUpdate(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], 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.Installed{}, rec, err - } - rec.State = state - row, err := rowOf(a, rec, a.Enabled) - return row, rec, err - }) -} - -func (m *Module) rollback(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], 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.Installed{}, rec, err - } - rec.State = state - row, err := rowOf(a, rec, a.Enabled) - return row, rec, err - }) -} - -type extensionPolicyInput struct { +type packageNameInput struct { Name string `path:"name"` +} +type registerVersionInput struct { + Name string `path:"name"` + Body struct { + Version string `json:"version,omitzero" doc:"The catalogue version to fetch. Default: the latest"` + } +} + +// registerVersion fetches another version of an installed package from the +// catalogue. A version that asks for no more than the default version was +// granted is accepted with the same grants; one that asks for more waits for +// an operator to accept it. +func (m *Module) registerVersion(ctx context.Context, in *registerVersionInput) (*httpapi.Reply[VersionView], error) { + m.pkgMu.Lock() + defer m.pkgMu.Unlock() + pv, err := m.packageNamed(ctx, in.Name) + if err != nil { + return nil, err + } + if !pv.pkg.Managed { + return nil, huma.NewError(http.StatusConflict, in.Name+" is accepted by path, not installed from the catalogue") + } + doc, location, err := m.readCatalogue(ctx) + if err != nil { + return nil, m.packageError(ctx, err) + } + ver, err := m.offer(ctx, doc, location, pv, in.Body.Version) + if err != nil { + return nil, m.packageError(ctx, err) + } + return httpapi.OK(versionView(ver, pv.pkg, nil)), nil +} + +// offer registers a version of pv from the catalogue and accepts it when the +// default version's grants cover what it declares. +func (m *Module) offer(ctx context.Context, doc catalogue.Document, location string, pv packageVersions, version string) (store.Version, error) { + entry, ok := doc.Entry(pv.pkg.Name) + if !ok { + return store.Version{}, huma.NewError(http.StatusNotFound, "the catalogue doesn't list "+pv.pkg.Name) + } + cv, ok := entry.Version(version) + if !ok { + return store.Version{}, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s %s", pv.pkg.Name, version)) + } + _, ver, err := m.register(ctx, location, entry, cv) + if err != nil || len(ver.Accepted) > 0 { + return ver, err + } + def, ok := pv.defaultVersion() + if !ok { + return ver, nil + } + held, ok, err := grantsOf(def.Accepted) + if err != nil || !ok || !held.Covers(cv.Grants.Normalised()) { + return ver, err + } + accepted, err := m.acceptGrants(ctx, ver, nil) + if err != nil { + return store.Version{}, err + } + ver.Accepted, err = json.Marshal(accepted) + return ver, err +} + +type versionInput struct { + Name string `path:"name"` + Version string `path:"version"` +} + +type acceptVersionInput struct { + Name string `path:"name"` + Version string `path:"version"` + Body *grantsRequest +} + +// acceptVersion records the grants the instance accepts for a version. With no +// body it accepts what the version declared. +func (m *Module) acceptVersion(ctx context.Context, in *acceptVersionInput) (*httpapi.Reply[VersionView], error) { + m.pkgMu.Lock() + defer m.pkgMu.Unlock() + pv, err := m.packageNamed(ctx, in.Name) + if err != nil { + return nil, err + } + ver, ok := pv.version(in.Version) + if !ok { + return nil, errNoVersion(in.Name, in.Version) + } + accepted, err := m.acceptGrants(ctx, ver, in.Body) + if err != nil { + return nil, m.packageError(ctx, err) + } + if ver.Accepted, err = json.Marshal(accepted); err != nil { + return nil, m.packageError(ctx, err) + } + if ver.ID == pv.pkg.DefaultVersion.UUID { + m.relaunchFollowers(context.WithoutCancel(ctx), pv.pkg.ID) + } + return httpapi.OK(versionView(ver, pv.pkg, nil)), nil +} + +type defaultVersionInput struct { + Name string `path:"name"` + Body struct { + Version string `json:"version" doc:"An accepted version of the package"` + } +} + +// setDefaultVersion moves every installation that follows the package to an +// accepted version: an update, or a rollback to an earlier one. +func (m *Module) setDefaultVersion(ctx context.Context, in *defaultVersionInput) (*httpapi.Reply[VersionView], error) { + m.pkgMu.Lock() + defer m.pkgMu.Unlock() + pv, err := m.packageNamed(ctx, in.Name) + if err != nil { + return nil, err + } + ver, ok := pv.version(in.Body.Version) + if !ok { + return nil, errNoVersion(in.Name, in.Body.Version) + } + if len(ver.Accepted) == 0 { + return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("accept %s %s before running it", in.Name, ver.Version)) + } + if err := m.store.SetDefaultVersion(ctx, pv.pkg.ID, ver.ID); err != nil { + return nil, m.packageError(ctx, err) + } + m.log.InfoContext(ctx, "package default version set", "audit", true, "action", "package.default", + "package", in.Name, "version", ver.Version) + m.relaunchFollowers(context.WithoutCancel(ctx), pv.pkg.ID) + pv.pkg.DefaultVersion = uuid.NullUUID{UUID: ver.ID, Valid: true} + return httpapi.OK(versionView(ver, pv.pkg, nil)), nil +} + +type updatePolicyInput struct { + Name string `path:"name"` Body struct { Policy string `json:"policy" enum:"manual,auto"` } } -func (m *Module) setPolicy(ctx context.Context, in *extensionPolicyInput) (*httpapi.Reply[Lifecycle], 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.Installed{}, rec, err - } - rec.State = state - row, err := rowOf(a, rec, a.Enabled) - return row, rec, err - }) -} - -type extensionEnabledInput struct { - Name string `path:"name"` - - Body struct { - Enabled bool `json:"enabled"` +func (m *Module) setUpdatePolicy(ctx context.Context, in *updatePolicyInput) (*httpapi.Reply[packageState], error) { + if err := catalogue.CheckPolicy(in.Body.Policy); err != nil { + return nil, huma.NewError(http.StatusBadRequest, err.Error()) } + pv, err := m.packageNamed(ctx, in.Name) + if err != nil { + return nil, err + } + if err := m.store.SetUpdatePolicy(ctx, pv.pkg.ID, in.Body.Policy); err != nil { + return nil, m.packageError(ctx, err) + } + m.log.InfoContext(ctx, "package update policy set", "audit", true, "action", "package.update_policy", + "package", in.Name, "policy", in.Body.Policy) + return httpapi.OK(packageState{Name: in.Name, State: "running"}), nil } -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.Installed, rec packageRecord) (store.Installed, packageRecord, error) { - if enabled && rec.State.Accepted == nil { - 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 - }) +// removeVersion deletes a version no installation runs. +func (m *Module) removeVersion(ctx context.Context, in *versionInput) (*httpapi.Reply[packageState], error) { + m.pkgMu.Lock() + defer m.pkgMu.Unlock() + pv, err := m.packageNamed(ctx, in.Name) + if err != nil { + return nil, err + } + ver, ok := pv.version(in.Version) + if !ok { + return nil, errNoVersion(in.Name, in.Version) + } + if err := m.store.DeleteVersion(ctx, ver.ID); err != nil { + return nil, m.packageError(ctx, err) + } + m.log.InfoContext(ctx, "package version removed", "audit", true, "action", "package.remove_version", + "package", in.Name, "version", ver.Version) + return httpapi.OK(packageState{Name: in.Name, State: "removed"}), nil } -// UpdateAuto updates every extension whose policy is auto to the digest the -// catalogue pins. One that fails doesn't stop the rest. It does nothing when no -// catalogue source is set. +func errNoVersion(name, version string) error { + return huma.NewError(http.StatusNotFound, fmt.Sprintf("%s has no version %s", name, version)) +} + +// UpdateAuto fetches the newest catalogue version of every package whose +// policy is auto. One whose grants the default version's cover becomes the +// default; one that asks for more waits for an operator. One package 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) + pkgs, err := m.store.Packages(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) + for _, p := range pkgs { + if p.Managed && p.UpdatePolicy == catalogue.PolicyAuto { + auto = append(auto, p.Name) } } if len(auto) == 0 { @@ -469,13 +538,41 @@ func (m *Module) UpdateAuto(ctx context.Context) error { } var errs []error for _, name := range auto { - if _, err := m.updateFrom(ctx, doc, location, name); err != nil { + if err := m.updateOne(ctx, doc, location, name); err != nil { errs = append(errs, fmt.Errorf("update %s: %w", name, err)) } } return errors.Join(errs...) } +func (m *Module) updateOne(ctx context.Context, doc catalogue.Document, location, name string) error { + m.pkgMu.Lock() + defer m.pkgMu.Unlock() + pv, err := m.packageNamed(ctx, name) + if err != nil { + return err + } + entry, ok := doc.Entry(name) + if !ok { + return nil + } + latest, ok := entry.Latest() + def, hasDefault := pv.defaultVersion() + if !ok || (hasDefault && !catalogue.Newer(latest.Version, def.Version)) { + return nil + } + ver, err := m.offer(ctx, doc, location, pv, latest.Version) + if err != nil || len(ver.Accepted) == 0 { + return err + } + if err := m.store.SetDefaultVersion(ctx, pv.pkg.ID, ver.ID); err != nil { + return err + } + m.log.InfoContext(ctx, "package updated", "audit", true, "action", "package.default", "package", name, "version", ver.Version) + m.relaunchFollowers(ctx, pv.pkg.ID) + return nil +} + // WatchUpdates runs UpdateAuto every interval until ctx ends. func (m *Module) WatchUpdates(ctx context.Context, interval time.Duration) { ticker := time.NewTicker(interval) @@ -492,43 +589,63 @@ func (m *Module) WatchUpdates(ctx context.Context, interval time.Duration) { } } -// ManagedView is what the dashboard shows of an extension installed from the -// catalogue: what each version declared next to what the operator accepted. -type ManagedView struct { - DisplayName string `json:"display_name"` - Description string `json:"description"` - Declared catalogue.Grants `json:"declared"` - // Accepted is nil until the operator accepts grants. +// VersionView is one version of a package. +type VersionView struct { + Version string `json:"version"` + Digest string `json:"digest"` + Declared catalogue.Grants `json:"declared"` + // Accepted is nil until the instance accepts the version. Accepted *catalogue.Grants `json:"accepted"` - // Pending is an update waiting for approval, with what it adds to the - // accepted grants. - Pending *PendingView `json:"pending"` - CanRollback bool `json:"can_rollback"` - UpdatePolicy string `json:"update_policy" enum:"manual,auto"` + Settings []Setting `json:"settings"` + Default bool `json:"default"` + // Installations counts the installations that run this version. + Installations int `json:"installations"` + CreatedAt time.Time `json:"created_at"` } -// PendingView is an update that asks for more than was accepted. -type PendingView struct { - Version string `json:"version"` - Digest string `json:"digest"` - Added catalogue.Grants `json:"added"` -} - -func managedView(rec packageRecord) *ManagedView { - s := rec.State - view := &ManagedView{ - DisplayName: rec.DisplayName, Description: rec.Description, - Declared: s.Current.Declared.Normalised(), CanRollback: s.Previous != nil, UpdatePolicy: s.Policy, +// versionView shows a version. running counts the installations on each +// version ID; nil leaves the count at zero. +func versionView(v store.Version, p store.Package, running map[uuid.UUID]int) VersionView { + view := VersionView{ + Version: v.Version, Digest: v.SHA256, Default: v.ID == p.DefaultVersion.UUID, + Installations: running[v.ID], CreatedAt: v.CreatedAt, Settings: []Setting{}, } - var held catalogue.Grants - if s.Accepted != nil { - held = s.Accepted.Normalised() + view.Declared, _, _ = grantsOf(v.Declared) + view.Declared = view.Declared.Normalised() + if held, ok, err := grantsOf(v.Accepted); err == nil && ok { view.Accepted = &held } - if s.Pending != nil { - view.Pending = &PendingView{ - Version: s.Pending.Version, Digest: s.Pending.Digest, Added: held.Added(s.Pending.Declared.Normalised()), - } + if s, err := settingsOf(v.Settings); err == nil { + view.Settings = s } return view } + +func (m *Module) registerPackages(api huma.API) { + tags := []string{"Packages"} + write := httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindConnector) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindConnector), huma.Operation{ + OperationID: "register-package-version", Method: http.MethodPost, Path: "/api/packages/{name}/versions", + Summary: "Fetch another catalogue version of an installed package", Tags: tags, + }, m.registerVersion) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionApprove, governance.KindConnector), huma.Operation{ + OperationID: "accept-package-version", Method: http.MethodPost, Path: "/api/packages/{name}/versions/{version}/accept", + Summary: "Accept the grants a package version may use", Tags: tags, + }, m.acceptVersion) + httpapi.Register(api, write, huma.Operation{ + OperationID: "put-package-default-version", Method: http.MethodPut, Path: "/api/packages/{name}/default-version", + Summary: "Run an accepted version in every installation that follows the package", Tags: tags, + }, m.setDefaultVersion) + httpapi.Register(api, write, huma.Operation{ + OperationID: "put-package-update-policy", Method: http.MethodPut, Path: "/api/packages/{name}/update-policy", + Summary: "Set whether a package follows the catalogue on its own", Tags: tags, + }, m.setUpdatePolicy) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{ + OperationID: "remove-package-version", Method: http.MethodDelete, Path: "/api/packages/{name}/versions/{version}", + Summary: "Remove a version no installation runs", Tags: tags, + }, m.removeVersion) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{ + OperationID: "remove-package", Method: http.MethodDelete, Path: "/api/packages/{name}", + Summary: "Remove a package, its versions and its instance installations", Tags: tags, + }, m.removePackage) +} diff --git a/modules/connectors/remove_test.go b/modules/connectors/remove_test.go index 8dfe9fd79..4095235f6 100644 --- a/modules/connectors/remove_test.go +++ b/modules/connectors/remove_test.go @@ -36,6 +36,20 @@ func (f *fakeRegistry) Overrides(context.Context) ([]store.Override, error) { re func (f *fakeRegistry) Packages(context.Context) ([]store.Package, error) { return nil, nil } +func (f *fakeRegistry) Versions(context.Context) ([]store.Version, error) { return nil, nil } + +func (f *fakeRegistry) RegisterVersion(_ context.Context, p store.Package, v store.Version, _ string) (store.Package, store.Version, error) { + return p, v, nil +} + +func (f *fakeRegistry) AcceptVersion(context.Context, uuid.UUID, []byte, string) error { return nil } + +func (f *fakeRegistry) SetDefaultVersion(context.Context, uuid.UUID, uuid.UUID) error { return nil } + +func (f *fakeRegistry) SetUpdatePolicy(context.Context, uuid.UUID, string) error { return nil } + +func (f *fakeRegistry) DeleteVersion(context.Context, uuid.UUID) error { return nil } + func (f *fakeRegistry) DeletePackage(_ context.Context, name string) (bool, error) { _, ok := f.installed[name] delete(f.installed, name) diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 1692b4b84..a41665290 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -290,25 +290,21 @@ export const api = { 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" }), + removePackage: (name: string) => + request<{ name: string; state: string }>(`/api/packages/${encodeURIComponent(name)}`, { method: "DELETE" }), + registerPackageVersion: (name: string, version?: string) => + request(`/api/packages/${encodeURIComponent(name)}/versions`, { method: "POST", body: { version }, timeoutMs: 120_000 }), + acceptPackageVersion: (name: string, version: string, body?: GrantsInput) => + request(`/api/packages/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/accept`, { method: "POST", body: body ?? {}, timeoutMs: 120_000 }), + setPackageDefaultVersion: (name: string, version: string) => + request(`/api/packages/${encodeURIComponent(name)}/default-version`, { method: "PUT", body: { version }, timeoutMs: 120_000 }), + setPackageUpdatePolicy: (name: string, policy: "manual" | "auto") => + request<{ name: string; state: string }>(`/api/packages/${encodeURIComponent(name)}/update-policy`, { method: "PUT", body: { policy } }), + removePackageVersion: (name: string, version: string) => + request<{ name: string; state: string }>(`/api/packages/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}`, { method: "DELETE" }), catalogue: () => request("/api/extensions/catalogue"), - installCatalogue: (name: string) => - request(`/api/extensions/catalogue/${encodeURIComponent(name)}/install`, { method: "POST", timeoutMs: 120_000 }), - acceptGrants: (name: string, body?: ExtensionGrantsInput) => - request(`/api/extensions/${encodeURIComponent(name)}/accept`, { method: "POST", body: body ?? {} }), - updateExtension: (name: string) => - request(`/api/extensions/${encodeURIComponent(name)}/update`, { method: "POST", timeoutMs: 120_000 }), - approveExtensionUpdate: (name: string) => - request(`/api/extensions/${encodeURIComponent(name)}/approve-update`, { method: "POST" }), - rollbackExtension: (name: string) => - request(`/api/extensions/${encodeURIComponent(name)}/rollback`, { method: "POST" }), - setExtensionPolicy: (name: string, policy: "manual" | "auto") => - request(`/api/extensions/${encodeURIComponent(name)}/update-policy`, { method: "PUT", body: { policy } }), - setExtensionEnabled: (name: string, enabled: boolean) => - request(`/api/extensions/${encodeURIComponent(name)}/enabled`, { method: "PUT", body: { enabled } }), - putExtensionSettings: (name: string, settings: Record) => - request(`/api/extensions/${encodeURIComponent(name)}/settings`, { method: "PUT", body: { settings }, timeoutMs: 60_000 }), + installCatalogue: (name: string, body: CatalogueInstallInput) => + request(`/api/extensions/catalogue/${encodeURIComponent(name)}/install`, { method: "POST", body, timeoutMs: 120_000 }), catalogueSource: () => request("/api/extensions/catalogue-source"), putCatalogueSource: (source: CatalogueSourceInput) => request("/api/extensions/catalogue-source", { method: "PUT", body: source }), @@ -1296,20 +1292,19 @@ export interface Extension { effects?: ServerEffects; /** A connector's declarations; absent until it has loaded. */ capabilities?: Capabilities; - /** Whether an accepted package runs. */ + /** Whether the installation runs. */ enabled?: boolean; + /** The installation runs `version` whatever its package's default version is. */ + version_pinned?: boolean; /** Installed from the catalogue rather than accepted by path. */ managed?: boolean; display_name?: string; description?: string; declared?: Grants | null; accepted?: Grants | null; - pending?: PendingUpdate | null; - can_rollback?: boolean; - update_policy?: "manual" | "auto"; } -/** One package the instance accepted: the binary and manifest, without the +/** One package the instance accepted, with its versions, without the * configuration an installation gives it. */ export interface PackageView { id: string; @@ -1318,15 +1313,29 @@ export interface PackageView { group: ExtensionGroup; display_name?: string; description?: string; - version?: string; - digest: string; + /** The version installations run unless they pin one. */ + default_version: 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; + update_policy: "manual" | "auto"; + versions: PackageVersion[]; accepted_at: string; } +/** One version of a package. */ +export interface PackageVersion { + version: string; + digest: string; + declared: Grants; + /** Null until the instance accepts the version. */ + accepted: Grants | null; + settings: SettingField[]; + default: boolean; + /** How many installations run this version. */ + installations: number; + created_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. */ @@ -1342,6 +1351,8 @@ export interface InstallationInput { url?: string; tools?: unknown; enabled: boolean; + /** An accepted version to pin; omitted runs the package's default version. */ + version?: string; } export type InstallationUpdate = Omit; @@ -1354,39 +1365,44 @@ export interface Grants { credentials: string[]; } -export interface PendingUpdate { - version: string; - digest: string; - added: Grants; +/** The grants an operator accepts for a version; an omitted list keeps what it declared. */ +export interface GrantsInput { + egress?: string[]; + env?: string[]; } -export interface ExtensionLifecycle { - name: string; - version: string; - digest: string; - pending: boolean; +/** Installs a catalogue version in one step: fetch, accept, create and start. */ +export interface CatalogueInstallInput extends GrantsInput { + version?: string; + scope?: ExtensionScope; + installation?: string; + settings?: Record; + credentials?: Record; enabled: boolean; } -export interface ExtensionGrantsInput { - egress?: string[]; - env?: string[]; - credentials?: Record; - settings?: Record; +/** One version a catalogue offers. */ +export interface CatalogueVersion { + version: string; + digest: string; + grants: Grants; + settings: SettingField[]; + /** Whether the instance has fetched this version. */ + registered: boolean; } -/** One extension a signed catalogue offers. */ +/** One extension a signed catalogue offers, with every version it offers. */ export interface CatalogueEntry { name: string; display_name: string; description: string; contract: string; group: ExtensionGroup; - version: string; - digest: string; - grants: Grants; + latest: string; + versions: CatalogueVersion[]; installed: boolean; - installed_version?: string; + /** The version installations run unless they pin one. */ + default_version?: string; update_available: boolean; } diff --git a/ui/src/settings/CatalogueInstallDialog.vue b/ui/src/settings/CatalogueInstallDialog.vue new file mode 100644 index 000000000..21f3cb718 --- /dev/null +++ b/ui/src/settings/CatalogueInstallDialog.vue @@ -0,0 +1,119 @@ + + + diff --git a/ui/src/settings/ExtensionChannelSettings.vue b/ui/src/settings/ExtensionChannelSettings.vue index da2628767..654e7cfc4 100644 --- a/ui/src/settings/ExtensionChannelSettings.vue +++ b/ui/src/settings/ExtensionChannelSettings.vue @@ -39,7 +39,7 @@ const missing = computed(() => ); function save(): void { - void store.saveSettings(props.extension.name, draft.value); + void store.saveSettings(props.extension, draft.value); } function setValue(key: string, value: string): void { draft.value = { ...draft.value, [key]: value }; diff --git a/ui/src/settings/ExtensionsMarketplace.vue b/ui/src/settings/ExtensionsMarketplace.vue index 069149ac7..5e9d0f5a7 100644 --- a/ui/src/settings/ExtensionsMarketplace.vue +++ b/ui/src/settings/ExtensionsMarketplace.vue @@ -11,10 +11,10 @@ import { useExtensionsStore, type CatalogueEntry } from "@/stores/extensions"; /** * The catalogue, grouped by the group each extension belongs to. Installed - * packages stay listed so the catalogue reads whole; they offer an update when - * one exists. + * packages stay listed so the catalogue reads whole; they open their versions + * when a newer one exists. */ -const props = defineProps<{ updates: Map }>(); +const emit = defineEmits<{ install: [entry: CatalogueEntry]; versions: [name: string] }>(); const store = useExtensionsStore(); // The server names each extension's group; these are its icons. @@ -63,18 +63,13 @@ const groups = computed(() => { {{ entry.display_name || entry.name }} - {{ entry.version }} + {{ entry.default_version || entry.latest }} {{ entry.description }} - Update to {{ entry.latest }} Installed diff --git a/ui/src/settings/ExtensionsPage.vue b/ui/src/settings/ExtensionsPage.vue index ed34286fc..47feb58aa 100644 --- a/ui/src/settings/ExtensionsPage.vue +++ b/ui/src/settings/ExtensionsPage.vue @@ -19,7 +19,6 @@ import { } from "@/components/ui/alert-dialog"; 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"; @@ -32,7 +31,7 @@ import { Switch } from "@/components/ui/switch"; 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 { grants, stage, useExtensionsStore, type CatalogueEntry } from "@/stores/extensions"; import { useOrgStore } from "@/stores/org"; import { api, type Extension, type ExtensionScope, type SettingField } from "@/lib/api"; import { useRead } from "@/lib/use-read"; @@ -41,6 +40,8 @@ import { stateTone } from "@/runs/state"; import InstallationDialog from "./InstallationDialog.vue"; import PackageList from "./PackageList.vue"; import ExtensionsMarketplace from "./ExtensionsMarketplace.vue"; +import CatalogueInstallDialog from "./CatalogueInstallDialog.vue"; +import PackageVersionsDialog from "./PackageVersionsDialog.vue"; const store = useExtensionsStore(); const org = useOrgStore(); @@ -50,10 +51,6 @@ onMounted(async () => { loading.value = false; }); -// The catalogue entry an installed package would move to on Update, when the -// 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(() => { @@ -82,35 +79,22 @@ async function saveSource(): Promise { } } -// Credentials a declared slot may resolve through at the instance scope. -const credentials = useRead(() => api.credentials()); -onMounted(credentials.reload); -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. -const accepting = ref(null); -const acceptOpen = ref(false); -const acceptKeys = ref>({}); -function openAccept(extension: Extension): void { - accepting.value = extension; - acceptKeys.value = {}; - acceptOpen.value = true; -} -async function accept(): Promise { - const extension = accepting.value; - if (!extension) return; - const declared = extension.declared; - await store.accept(extension.name, { - egress: declared?.egress ?? [], - env: declared?.env ?? [], - credentials: acceptKeys.value, - }); +const installing = ref(null); +const installOpen = ref(false); +function openInstall(entry: CatalogueEntry): void { + installing.value = entry; + installOpen.value = true; } -// 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 versionsOf = ref(""); +const versionsOpen = ref(false); +function openVersions(name: string): void { + versionsOf.value = name; + versionsOpen.value = true; +} +// Versions belong to the package, which only an instance administrator +// changes. +const managesVersions = (extension: Extension) => org.instanceAdmin && extension.managed === true; const installation = ref(null); const installationOpen = ref(false); @@ -122,19 +106,6 @@ async function reload(): Promise { await store.load(); } -async function setEnabled(extension: Extension, enabled: boolean): Promise { - 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 { await store.overrideInstallation(extension.id, scope, off); } @@ -162,7 +133,7 @@ async function saveSettings(): Promise { ...fromLines(other.value), ...Object.fromEntries(Object.entries(values.value).filter(([, value]) => value !== "")), }; - if (await store.saveSettings(editing.value.name, settings)) settingsOpen.value = false; + if (await store.saveSettings(editing.value, settings)) settingsOpen.value = false; } const removing = ref(null); @@ -225,6 +196,7 @@ const active = computed(() => (kinds.data.value ?? []).find((kind) => kind.kind

{{ extension.display_name || extension.name }} {{ extension.version }} + Pinned

{{ extension.package }}

{{ extension.description }}

@@ -260,53 +232,21 @@ const active = computed(() => (kinds.data.value ?? []).find((kind) => kind.kind Switched off {{ tones[stage(extension)].label }} {{ extension.state }} - -

Update awaiting approval. It adds:

-
    -
  • {{ line }}
  • -
- -
- - - - - + + + + + Settings + - {{ managedInstance(extension) ? "Settings" : "Edit" }} + Edit -