// Package store holds the connectors module's SQL: the accepted extensions the // host starts at boot and the sealed credentials they are configured with. package store import ( "context" "database/sql" "database/sql/driver" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "github.com/jmoiron/sqlx" ) // Accepted is one package an operator accepted, with the authority it // declared. type Accepted struct { OrgID string `db:"org_id"` Name string `db:"name"` Path string `db:"path"` SHA256 string `db:"sha256"` Egress Strings `db:"egress"` Env Strings `db:"env"` Settings jsontext.Value `db:"settings"` // Contract is ContractConnector, ContractSecretEngine, ContractMCP or // ContractGuard. Contract string `db:"contract"` // Credentials maps a slot to a credential name, as a JSON object. Credentials jsontext.Value `db:"credentials"` // Args are a stdio MCP server's arguments; URL is an HTTP server's // endpoint. Which one the acceptance set is what picks the transport. Args Strings `db:"args"` URL string `db:"url"` // Tools are the lookups and actions an MCP server's acceptance declares, // as a JSON array. Tools jsontext.Value `db:"tools"` // Effects is an MCP server's declared privileged effects, as a JSON // object. It is nil until the operator declares them. A []byte for the // same reason as Capabilities. Effects []byte `db:"effects"` // Capabilities is what a connector declared when it last loaded, as a JSON // object. It is nil until then, and acceptance never changes it. It is a // []byte because database/sql scans NULL into []byte but not into a named // byte slice such as jsontext.Value. Capabilities []byte `db:"capabilities"` } // Contracts an accepted 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. Upsert 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. type Credential struct { OrgID string `db:"org_id"` Name string `db:"name"` Kind string `db:"kind"` Sealed []byte `db:"sealed"` } // 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 an organisation's accepted connectors. func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) { var out []Accepted if err := s.db.SelectContext(ctx, &out, ` SELECT org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools, effects, capabilities FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil { return nil, fmt.Errorf("list connectors: %w", err) } return out, nil } // Upsert records an accepted connector, replacing an earlier acceptance. func (s *Store) Upsert(ctx context.Context, a Accepted) error { if GroupOf(a.Contract) == "" { return fmt.Errorf("accept %q: unknown contract %q", a.Name, a.Contract) } if _, err := s.db.NamedExecContext(ctx, ` INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools, effects) VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings, :contract, :credentials, :args, :url, :tools, :effects) ON CONFLICT (org_id, name) DO UPDATE SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress, env = EXCLUDED.env, settings = EXCLUDED.settings, contract = EXCLUDED.contract, credentials = EXCLUDED.credentials, args = EXCLUDED.args, url = EXCLUDED.url, tools = EXCLUDED.tools, effects = EXCLUDED.effects, updated_at = now()`, a); err != nil { return fmt.Errorf("accept connector: %w", err) } return nil } // SetCapabilities records what an accepted connector declared when it loaded. func (s *Store) SetCapabilities(ctx context.Context, orgID, name string, capabilities jsontext.Value) error { if _, err := s.db.ExecContext(ctx, ` UPDATE connectors.accepted SET capabilities = $3 WHERE org_id = $1 AND name = $2`, orgID, name, []byte(capabilities)); err != nil { return fmt.Errorf("store capabilities of %q: %w", name, err) } return nil } // Capabilities returns what the named connector declared when it last loaded. // ok is false when it isn't accepted or has never loaded. func (s *Store) Capabilities(ctx context.Context, orgID, name string) (raw jsontext.Value, ok bool, err error) { err = s.db.GetContext(ctx, &raw, ` SELECT capabilities FROM connectors.accepted WHERE org_id = $1 AND name = $2 AND capabilities IS NOT NULL`, orgID, name) if errors.Is(err, sql.ErrNoRows) { return nil, false, nil } if err != nil { return nil, false, fmt.Errorf("read capabilities of %q: %w", name, err) } return raw, true, nil } // Delete removes an accepted package and reports whether there was one. Its // credential slots live on the row, so they go with it. func (s *Store) Delete(ctx context.Context, orgID, name string) (bool, error) { res, err := s.db.ExecContext(ctx, `DELETE FROM connectors.accepted WHERE org_id = $1 AND name = $2`, orgID, name) if err != nil { return false, fmt.Errorf("remove connector %q: %w", name, err) } n, err := res.RowsAffected() if err != nil { return false, fmt.Errorf("remove connector %q: %w", name, err) } return n > 0, nil } // Credential returns the named credential; ok is false when there is none. func (s *Store) Credential(ctx context.Context, orgID, name string) (Credential, bool, error) { var c Credential err := s.db.GetContext(ctx, &c, ` SELECT org_id, name, kind, sealed FROM connectors.credentials WHERE org_id = $1 AND name = $2`, orgID, name) if errors.Is(err, sql.ErrNoRows) { return Credential{}, false, nil } if err != nil { return Credential{}, false, fmt.Errorf("read credential %q: %w", name, err) } return c, true, nil } // Credentials returns an organisation's credentials in name order. func (s *Store) Credentials(ctx context.Context, orgID string) ([]Credential, error) { var out []Credential if err := s.db.SelectContext(ctx, &out, ` SELECT org_id, name, kind, sealed FROM connectors.credentials WHERE org_id = $1 ORDER BY name`, orgID); err != nil { return nil, fmt.Errorf("list credentials: %w", err) } return out, nil } // PutCredential records a credential, replacing an earlier one of that name. func (s *Store) PutCredential(ctx context.Context, c Credential) error { if _, err := s.db.NamedExecContext(ctx, ` INSERT INTO connectors.credentials (org_id, name, kind, sealed) VALUES (:org_id, :name, :kind, :sealed) ON CONFLICT (org_id, name) DO UPDATE SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now()`, c); err != nil { 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)) }