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.
This commit is contained in:
sam committed 2026-11-25 22:10:06 +11:00
1 parent afdb0a0c97
commit c9ed3b1ae2
26 files changed
+1925 -1265

No files matched your search

+14 -3
View File
@@ -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)) {
+62 -52
View File
@@ -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)
}
+4 -11
View File
@@ -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)
}
+101 -33
View File
@@ -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
@@ -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) {
@@ -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
}
@@ -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
}
+244 -45
View File
@@ -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
+53 -27
View File
@@ -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()
+2 -1
View File
@@ -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
+14 -3
View File
@@ -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
File diff suppressed because it is too large. Load diff
+14
View File
@@ -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)