// Package store holds the connectors module's SQL: the packages the instance // accepted and their versions, the installations that configure them at a // scope, and the sealed credentials those installations use. package store import ( "cmp" "context" "database/sql" "database/sql/driver" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" ) // Source is where the instance's catalogue is read from. type Source struct { Location string `db:"location"` PublicKey string `db:"public_key"` // Newest is the issue time of the newest catalogue accepted from it. Newest sql.NullTime `db:"newest_issued_at"` Generation int64 `db:"generation"` } // CatalogueSource returns the configured override and the newest issue time // accepted from the active source. An empty location means there's no override. func (s *Store) CatalogueSource(ctx context.Context) (Source, error) { var out Source err := s.db.GetContext(ctx, &out, ` SELECT location, public_key, generation, CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END AS newest_issued_at FROM connectors.catalogue_source`) if errors.Is(err, sql.ErrNoRows) { return Source{}, nil } if err != nil { return Source{}, fmt.Errorf("read catalogue source: %w", err) } return out, nil } // PutCatalogueSource records the source. A different source starts a new // timeline, so the newest issue time is cleared when the location or key // changes. func (s *Store) PutCatalogueSource(ctx context.Context, src Source) error { if _, err := s.db.ExecContext(ctx, ` INSERT INTO connectors.catalogue_source (location, public_key, generation) VALUES ($1, $2, 1) ON CONFLICT (singleton) DO UPDATE SET newest_issued_at = CASE WHEN connectors.catalogue_source.location = EXCLUDED.location AND connectors.catalogue_source.public_key = EXCLUDED.public_key THEN connectors.catalogue_source.newest_issued_at END, location = EXCLUDED.location, public_key = EXCLUDED.public_key, updated_at = now(), generation = connectors.catalogue_source.generation + 1`, src.Location, src.PublicKey); err != nil { return fmt.Errorf("put catalogue source: %w", err) } return nil } // AdvanceCatalogue rejects reads from an earlier source generation and never // lowers the issue time. An override doesn't reset Archipelago's issue time. func (s *Store) AdvanceCatalogue(ctx context.Context, generation int64, issuedAt time.Time) (bool, error) { if generation == 0 { if _, err := s.db.ExecContext(ctx, `INSERT INTO connectors.catalogue_source (location, public_key) VALUES ('', '') ON CONFLICT (singleton) DO NOTHING`); err != nil { return false, fmt.Errorf("initialise catalogue state: %w", err) } } res, err := s.db.ExecContext(ctx, ` UPDATE connectors.catalogue_source SET newest_issued_at = CASE WHEN location = '' THEN newest_issued_at ELSE $2 END, default_newest_issued_at = CASE WHEN location = '' THEN $2 ELSE default_newest_issued_at END WHERE generation = $1 AND (CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END IS NULL OR CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END <= $2)`, generation, issuedAt) if err != nil { return false, fmt.Errorf("record catalogue freshness: %w", err) } n, err := res.RowsAffected() return n > 0, err } // Scopes an installation or a credential can be owned by. const ( ScopeInstance = "instance" ScopeOrg = "org" ScopePerson = "person" ) // Owner is the scope that owns an installation or a credential. OrgID is set // for an organisation and PersonID for a person; both are empty for the // instance. type Owner struct { Scope string OrgID string PersonID string } // Installed is one installation with the package it configures. Name is the // installation's own name, which a binding uses; PackageName is the package's // immutable identifier. type Installed struct { ID uuid.UUID `db:"id"` PackageID uuid.UUID `db:"package_id"` Scope string `db:"scope"` OrgID string `db:"org_id"` PersonID string `db:"person_id"` Name string `db:"name"` PackageName string `db:"package_name"` // Contract is ContractConnector, ContractSecretEngine, ContractMCP or // ContractGuard. Contract string `db:"contract"` // 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 // endpoint. Which one is set picks the transport. Args Strings `db:"args"` URL string `db:"url"` // Tools are the lookups and actions an MCP server declares, as a JSON // array. Tools jsontext.Value `db:"tools"` // Effects is an MCP server's declared privileged effects, as a JSON // object. It is nil until declared. A []byte because database/sql scans // NULL into []byte but not into a named byte slice such as jsontext.Value. Effects []byte `db:"effects"` // Capabilities is what a connector declared when it last loaded, as a JSON // object. It is nil until then. Capabilities []byte `db:"capabilities"` // Enabled says whether the installation runs. One that is not enabled is // kept but never launched. Enabled bool `db:"enabled"` // 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, 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 JOIN connectors.package_versions v ON v.id = COALESCE(i.package_version_id, p.default_version_id)` // Contracts a package can serve. const ( ContractConnector = "connector" ContractSecretEngine = "secretengine" ContractMCP = "mcp" ContractGuard = "guard" ) // Group says what an extension is for, so the dashboard can list the // extensions an operator sets up together. type Group string // Groups of extensions. Workflows and playbooks are content and have none. const ( GroupPlatform Group = "platform" GroupIntegration Group = "integration" GroupAgent Group = "agent" ) // Contracts lists every known contract with its group. Saving refuses any // contract not in this table, so every stored package has a group. func Contracts() []ContractGroup { return []ContractGroup{ {ContractConnector, GroupIntegration}, {ContractSecretEngine, GroupPlatform}, {ContractGuard, GroupPlatform}, {ContractMCP, GroupAgent}, } } // ContractGroup pairs a contract with its group. type ContractGroup struct { Contract string Group Group } // GroupOf returns the group of a contract in Contracts, or "" for an unknown one. func GroupOf(contract string) Group { for _, c := range Contracts() { if c.Contract == contract { return c.Group } } return "" } // Credential is a credential's sealed fields and the scope that owns it. type Credential struct { ID uuid.UUID `db:"id"` Scope string `db:"scope"` OrgID string `db:"org_id"` PersonID string `db:"person_id"` Name string `db:"name"` Kind string `db:"kind"` Sealed []byte `db:"sealed"` } // Owner returns the scope that owns the credential. func (c Credential) Owner() Owner { return Owner{Scope: c.Scope, OrgID: c.OrgID, PersonID: c.PersonID} } // Package is an extension the instance accepted. Name is the immutable // package identifier from the catalogue or acceptance request: a package is // never renamed, and a name is never given to a different package. type Package struct { ID uuid.UUID `db:"id"` Name string `db:"name"` 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"` CatalogueDigest string `db:"catalogue_digest"` 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"` CreatedAt time.Time `db:"created_at"` } // Override records that an organisation or a person switched off an // installation it would otherwise inherit. type Override struct { InstallationID uuid.UUID `db:"installation_id"` Scope string `db:"scope"` OrgID string `db:"org_id"` PersonID string `db:"person_id"` } // Store is the connectors module's Postgres store. type Store struct { db *sqlx.DB } // New returns a store on db. func New(db *sqlx.DB) *Store { return &Store{db: db} } // List returns every installation with its package, whatever its scope. func (s *Store) List(ctx context.Context) ([]Installed, error) { var out []Installed if err := s.db.SelectContext(ctx, &out, `SELECT `+installedColumns+installedFrom+` ORDER BY i.name, i.scope, i.org_id, i.person_id`); err != nil { return nil, fmt.Errorf("list installations: %w", err) } return out, nil } // Packages returns every accepted package in name order. func (s *Store) Packages(ctx context.Context) ([]Package, error) { var out []Package if err := s.db.SelectContext(ctx, &out, ` SELECT id, name, contract, 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, catalogue_digest, 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") // ErrCatalogueChanged means the source changed or a newer catalogue was accepted during the fetch. ErrCatalogueChanged = errors.New("the catalogue changed while the package was being fetched") ) // 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, generation int64, issuedAt time.Time) (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() }() var current int64 err = tx.GetContext(ctx, ¤t, `SELECT generation FROM connectors.catalogue_source WHERE generation = $1 AND CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END = $2 FOR UPDATE`, generation, issuedAt) if errors.Is(err, sql.ErrNoRows) { return Package{}, Version{}, ErrCatalogueChanged } if err != nil { return Package{}, Version{}, fmt.Errorf("check catalogue state: %w", err) } 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, catalogue_digest, declared, settings, accepted, accepted_by_id, effects) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (package_id, version) DO NOTHING`, uuid.New(), stored.ID, v.Version, v.Path, v.SHA256, v.CatalogueDigest, 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 || got.CatalogueDigest != v.CatalogueDigest { 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 if err := s.db.SelectContext(ctx, &out, `SELECT installation_id, scope, org_id, person_id FROM connectors.installation_overrides`); err != nil { return nil, fmt.Errorf("list installation overrides: %w", err) } return out, nil } // SetOverride switches an inherited installation off for an organisation or a // person, or back on when off is false. func (s *Store) SetOverride(ctx context.Context, o Override, off bool, by string) error { var err error if off { _, err = s.db.ExecContext(ctx, ` INSERT INTO connectors.installation_overrides (installation_id, scope, org_id, person_id, disabled_by_id) VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING`, o.InstallationID, o.Scope, o.OrgID, o.PersonID, by) } else { _, err = s.db.ExecContext(ctx, ` DELETE FROM connectors.installation_overrides WHERE installation_id = $1 AND scope = $2 AND org_id = $3 AND person_id = $4`, o.InstallationID, o.Scope, o.OrgID, o.PersonID) } if err != nil { return fmt.Errorf("set installation override: %w", err) } return nil } // SaveInstalled records a package 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) { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return Installed{}, fmt.Errorf("save %q: %w", in.Name, err) } defer func() { _ = tx.Rollback() }() 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.VersionID, capabilities); err != nil { return Installed{}, err } } if err := tx.Commit(); err != nil { return Installed{}, fmt.Errorf("save %q: %w", in.Name, err) } return in, nil } // SaveInstallation records an installation of an accepted package, replacing // the earlier installation of that name at the same owner. Nil capabilities // leave the package's stored declarations unchanged. It returns the stored // row, with its ID. func (s *Store) SaveInstallation(ctx context.Context, in Installed, capabilities jsontext.Value) (Installed, error) { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return Installed{}, fmt.Errorf("save %q: %w", in.Name, err) } defer func() { _ = tx.Rollback() }() if in.ID, err = upsertInstallation(ctx, tx, in); err != nil { return Installed{}, err } if capabilities != nil { if err := setCapabilities(ctx, tx, in.VersionID, capabilities); err != nil { return Installed{}, err } } if err := tx.Commit(); err != nil { return Installed{}, fmt.Errorf("save %q: %w", in.Name, err) } return in, nil } func upsertInstallation(ctx context.Context, tx *sqlx.Tx, in Installed) (uuid.UUID, error) { var id uuid.UUID err := tx.GetContext(ctx, &id, ` INSERT INTO connectors.installations (id, package_id, scope, org_id, person_id, name, settings, egress, env, credentials, args, url, tools, enabled, 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, 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, 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, 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 } func orDefault(v jsontext.Value, empty string) []byte { if len(v) == 0 { return []byte(empty) } return v } func nilIfEmpty(b []byte) []byte { if len(b) == 0 { return nil } return b } // SetCapabilities records what a connector 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 } // DeleteInstallation removes one installation and reports whether there was // one. Its overrides go with it. func (s *Store) DeleteInstallation(ctx context.Context, id uuid.UUID) (bool, error) { res, err := s.db.ExecContext(ctx, `DELETE FROM connectors.installations WHERE id = $1`, id) if err != nil { return false, fmt.Errorf("remove installation: %w", err) } n, err := res.RowsAffected() return n > 0, err } // ErrInstalled means an organisation or a person still has an installation of // the package. var ErrInstalled = errors.New("the package is still installed by an organisation or a person") // DeletePackage removes a package and its instance installations, and reports // whether there was one. It fails while an organisation or a person still has // an installation of it. func (s *Store) DeletePackage(ctx context.Context, name string) (bool, error) { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return false, fmt.Errorf("remove package %q: %w", name, err) } defer func() { _ = tx.Rollback() }() var id uuid.UUID err = tx.GetContext(ctx, &id, `SELECT id FROM connectors.packages WHERE name = $1`, name) if errors.Is(err, sql.ErrNoRows) { return false, nil } if err != nil { return false, fmt.Errorf("remove package %q: %w", name, err) } var others int if err := tx.GetContext(ctx, &others, `SELECT count(*) FROM connectors.installations WHERE package_id = $1 AND scope <> 'instance'`, id); err != nil { return false, fmt.Errorf("remove package %q: %w", name, err) } if others > 0 { return false, ErrInstalled } if _, err := tx.ExecContext(ctx, `DELETE FROM connectors.installations WHERE package_id = $1`, id); err != nil { return false, fmt.Errorf("remove package %q: %w", name, err) } if _, err := tx.ExecContext(ctx, `DELETE FROM connectors.packages WHERE id = $1`, id); err != nil { return false, fmt.Errorf("remove package %q: %w", name, err) } if err := tx.Commit(); err != nil { return false, fmt.Errorf("remove package %q: %w", name, err) } return true, nil } // Credentials returns every credential, whatever its scope, in name order. func (s *Store) Credentials(ctx context.Context) ([]Credential, error) { var out []Credential if err := s.db.SelectContext(ctx, &out, ` SELECT id, scope, org_id, person_id, name, kind, sealed FROM connectors.credentials ORDER BY name, scope, org_id, person_id`); err != nil { return nil, fmt.Errorf("list credentials: %w", err) } return out, nil } // PutCredential records a credential, replacing an earlier one of that name at // the same owner, and returns its id. func (s *Store) PutCredential(ctx context.Context, c Credential) (uuid.UUID, error) { var id uuid.UUID if err := s.db.GetContext(ctx, &id, ` INSERT INTO connectors.credentials (id, scope, org_id, person_id, name, kind, sealed) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (scope, org_id, person_id, name) DO UPDATE SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now() RETURNING id`, cmp.Or(c.ID, uuid.New()), c.Scope, c.OrgID, c.PersonID, c.Name, c.Kind, c.Sealed); err != nil { return uuid.Nil, fmt.Errorf("put credential %q: %w", c.Name, err) } return id, nil } // Strings is a string list stored as a JSON array. Value has a value receiver // so database/sql finds it on a struct field; Scan needs a pointer. type Strings []string //nolint:recvcheck // database/sql's Valuer and Scanner idiom // Value encodes the list as JSON. func (s Strings) Value() (driver.Value, error) { if s == nil { return []byte("[]"), nil } return json.Marshal([]string(s)) } // Scan decodes a JSON array. func (s *Strings) Scan(src any) error { var raw []byte switch v := src.(type) { case []byte: raw = v case string: raw = []byte(v) case nil: *s = nil return nil default: return errors.New("strings: unsupported column type") } return json.Unmarshal(raw, (*[]string)(s)) }