Packages are accepted once by the instance. Installations configure them at the instance, an organisation or a person; bindings and credentials resolve the person's, then their organisation's, then the instance's. Decisions, approval requests and held chat actions record the installation and scope that acted. The dashboard lists packages separately from installations, shows every installation's scope, and creates, edits and disables installations at their scope.
492 lines
18 KiB
Go
492 lines
18 KiB
Go
// Package store holds the connectors module's SQL: the packages the instance
|
|
// accepted, the installations that configure them at a scope, and the sealed
|
|
// credentials those installations use.
|
|
package store
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"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"`
|
|
}
|
|
|
|
// CatalogueSource returns the catalogue source; ok is false when none is set.
|
|
func (s *Store) CatalogueSource(ctx context.Context) (Source, bool, error) {
|
|
var out Source
|
|
err := s.db.GetContext(ctx, &out, `SELECT location, public_key, newest_issued_at FROM connectors.catalogue_source`)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return Source{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return Source{}, false, fmt.Errorf("read catalogue source: %w", err)
|
|
}
|
|
return out, true, 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) VALUES ($1, $2)
|
|
ON CONFLICT (singleton) DO UPDATE
|
|
SET newest_issued_at = CASE WHEN connectors.catalogue_source.location = EXCLUDED.location
|
|
AND connectors.catalogue_source.public_key = EXCLUDED.public_key
|
|
THEN connectors.catalogue_source.newest_issued_at END,
|
|
location = EXCLUDED.location, public_key = EXCLUDED.public_key, updated_at = now()`,
|
|
src.Location, src.PublicKey); err != nil {
|
|
return fmt.Errorf("put catalogue source: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AdvanceCatalogue records a catalogue issued at issuedAt as accepted and
|
|
// reports false when a newer one was accepted already. It never lowers the mark.
|
|
func (s *Store) AdvanceCatalogue(ctx context.Context, issuedAt time.Time) (bool, error) {
|
|
res, err := s.db.ExecContext(ctx, `
|
|
UPDATE connectors.catalogue_source SET newest_issued_at = $1
|
|
WHERE newest_issued_at IS NULL OR newest_issued_at <= $1`, issuedAt)
|
|
if err != nil {
|
|
return false, fmt.Errorf("record catalogue freshness: %w", err)
|
|
}
|
|
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.
|
|
type Installed struct {
|
|
ID uuid.UUID `db:"id"`
|
|
PackageID uuid.UUID `db:"package_id"`
|
|
Scope string `db:"scope"`
|
|
OrgID string `db:"org_id"`
|
|
PersonID string `db:"person_id"`
|
|
Name string `db:"name"`
|
|
PackageName string `db:"package_name"`
|
|
// Contract is ContractConnector, ContractSecretEngine, ContractMCP or
|
|
// ContractGuard.
|
|
Contract string `db:"contract"`
|
|
Path string `db:"path"`
|
|
SHA256 string `db:"sha256"`
|
|
Egress Strings `db:"egress"`
|
|
Env Strings `db:"env"`
|
|
Settings jsontext.Value `db:"settings"`
|
|
// 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"`
|
|
// 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"`
|
|
}
|
|
|
|
// Owner returns the scope that owns the installation.
|
|
func (i Installed) Owner() Owner { return Owner{Scope: i.Scope, OrgID: i.OrgID, PersonID: i.PersonID} }
|
|
|
|
const installedColumns = `i.id, i.package_id, i.scope, i.org_id, i.person_id, i.name, p.name AS package_name,
|
|
p.contract, p.path, p.sha256, i.egress, i.env, i.settings, i.credentials, i.args, i.url, i.tools,
|
|
p.effects, p.capabilities, i.enabled, p.manifest`
|
|
|
|
const installedFrom = ` FROM connectors.installations i JOIN connectors.packages p ON p.id = i.package_id`
|
|
|
|
// Contracts a package can serve.
|
|
const (
|
|
ContractConnector = "connector"
|
|
ContractSecretEngine = "secretengine"
|
|
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.
|
|
type Package struct {
|
|
ID uuid.UUID `db:"id"`
|
|
Name string `db:"name"`
|
|
Contract string `db:"contract"`
|
|
Path string `db:"path"`
|
|
SHA256 string `db:"sha256"`
|
|
Manifest []byte `db:"manifest"`
|
|
Capabilities []byte `db:"capabilities"`
|
|
Effects []byte `db:"effects"`
|
|
AcceptedByID string `db:"accepted_by_id"`
|
|
AcceptedAt time.Time `db:"accepted_at"`
|
|
}
|
|
|
|
// Override records that an organisation or a person switched off an
|
|
// installation it would otherwise inherit.
|
|
type Override struct {
|
|
InstallationID uuid.UUID `db:"installation_id"`
|
|
Scope string `db:"scope"`
|
|
OrgID string `db:"org_id"`
|
|
PersonID string `db:"person_id"`
|
|
}
|
|
|
|
// Store is the connectors module's Postgres store.
|
|
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, path, sha256, manifest, capabilities, effects, accepted_by_id, accepted_at
|
|
FROM connectors.packages ORDER BY name`); err != nil {
|
|
return nil, fmt.Errorf("list packages: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// 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 and one installation of it in one
|
|
// transaction, replacing the earlier package of that name and the earlier
|
|
// installation of that name at the same owner. Nil capabilities leave the
|
|
// stored declarations unchanged. It returns the stored row, with its IDs.
|
|
func (s *Store) SaveInstalled(ctx context.Context, in Installed, by string, capabilities jsontext.Value) (Installed, error) {
|
|
if GroupOf(in.Contract) == "" {
|
|
return Installed{}, fmt.Errorf("accept %q: unknown contract %q", in.Name, in.Contract)
|
|
}
|
|
tx, err := s.db.BeginTxx(ctx, nil)
|
|
if err != nil {
|
|
return 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)
|
|
}
|
|
if in.ID, err = upsertInstallation(ctx, tx, in); err != nil {
|
|
return Installed{}, err
|
|
}
|
|
if capabilities != nil {
|
|
if err := setCapabilities(ctx, tx, in.PackageID, capabilities); err != nil {
|
|
return Installed{}, err
|
|
}
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return Installed{}, fmt.Errorf("save %q: %w", in.Name, err)
|
|
}
|
|
return in, nil
|
|
}
|
|
|
|
// 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.PackageID, capabilities); err != nil {
|
|
return Installed{}, err
|
|
}
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return Installed{}, fmt.Errorf("save %q: %w", in.Name, err)
|
|
}
|
|
return in, nil
|
|
}
|
|
|
|
func upsertInstallation(ctx context.Context, tx *sqlx.Tx, in Installed) (uuid.UUID, error) {
|
|
var id uuid.UUID
|
|
err := tx.GetContext(ctx, &id, `
|
|
INSERT INTO connectors.installations
|
|
(id, package_id, scope, org_id, person_id, name, settings, egress, env, credentials, args, url, tools, enabled)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
|
ON CONFLICT (scope, org_id, person_id, name) DO UPDATE
|
|
SET package_id = EXCLUDED.package_id, settings = EXCLUDED.settings, egress = EXCLUDED.egress,
|
|
env = EXCLUDED.env, credentials = EXCLUDED.credentials, args = EXCLUDED.args, url = EXCLUDED.url,
|
|
tools = EXCLUDED.tools, enabled = EXCLUDED.enabled, updated_at = now()
|
|
RETURNING id`,
|
|
cmp.Or(in.ID, uuid.New()), in.PackageID, in.Scope, in.OrgID, in.PersonID, in.Name, orDefault(in.Settings, "{}"), in.Egress, in.Env,
|
|
orDefault(in.Credentials, "{}"), in.Args, in.URL, orDefault(in.Tools, "[]"), in.Enabled)
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("save installation %q: %w", in.Name, err)
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func setCapabilities(ctx context.Context, tx *sqlx.Tx, packageID uuid.UUID, capabilities jsontext.Value) error {
|
|
if _, err := tx.ExecContext(ctx, `UPDATE connectors.packages SET capabilities = $2 WHERE id = $1`, packageID, []byte(capabilities)); err != nil {
|
|
return fmt.Errorf("store capabilities: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func orDefault(v jsontext.Value, empty string) []byte {
|
|
if len(v) == 0 {
|
|
return []byte(empty)
|
|
}
|
|
return v
|
|
}
|
|
|
|
func nilIfEmpty(b []byte) []byte {
|
|
if len(b) == 0 {
|
|
return nil
|
|
}
|
|
return b
|
|
}
|
|
|
|
// SetCapabilities records what a connector declared when it loaded.
|
|
func (s *Store) SetCapabilities(ctx context.Context, packageID uuid.UUID, capabilities jsontext.Value) error {
|
|
if _, err := s.db.ExecContext(ctx, `UPDATE connectors.packages SET capabilities = $2 WHERE id = $1`, packageID, []byte(capabilities)); err != nil {
|
|
return fmt.Errorf("store capabilities: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteInstallation removes one installation and reports whether there was
|
|
// one. Its overrides go with it.
|
|
func (s *Store) DeleteInstallation(ctx context.Context, id uuid.UUID) (bool, error) {
|
|
res, err := s.db.ExecContext(ctx, `DELETE FROM connectors.installations WHERE id = $1`, id)
|
|
if err != nil {
|
|
return false, fmt.Errorf("remove installation: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
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.
|
|
func (s *Store) PutCredential(ctx context.Context, c Credential) error {
|
|
if _, err := s.db.ExecContext(ctx, `
|
|
INSERT INTO connectors.credentials (id, scope, org_id, person_id, name, kind, sealed)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
ON CONFLICT (scope, org_id, person_id, name) DO UPDATE
|
|
SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now()`,
|
|
uuid.New(), c.Scope, c.OrgID, c.PersonID, c.Name, c.Kind, c.Sealed); err != nil {
|
|
return fmt.Errorf("put credential %q: %w", c.Name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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))
|
|
}
|