- store trigger dispatches as started or skipped, with a JSON reason surfaced in the API and UI - persist the answering account's identity id beside its display name for approvals and judgements - save connector acceptances and their declarations in one transaction so a refused change stores nothing
491 lines
17 KiB
Go
491 lines
17 KiB
Go
package connectors
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
json "encoding/json/v2"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"net/http"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/danielgtaylor/huma/v2"
|
|
|
|
"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"
|
|
)
|
|
|
|
// packageRecord is the lifecycle of an extension installed from the catalogue,
|
|
// as it is stored on its accepted row.
|
|
type packageRecord struct {
|
|
DisplayName string `json:"display_name"`
|
|
Description string `json:"description"`
|
|
State catalogue.State `json:"state"`
|
|
}
|
|
|
|
// packageOf reads a row's lifecycle; ok is false for a package accepted by
|
|
// path.
|
|
func packageOf(a store.Accepted) (rec packageRecord, ok bool, err error) {
|
|
if len(a.Package) == 0 {
|
|
return packageRecord{}, false, nil
|
|
}
|
|
if err := json.Unmarshal(a.Package, &rec); err != nil {
|
|
return packageRecord{}, false, fmt.Errorf("package %q: %w", a.Name, err)
|
|
}
|
|
return rec, true, nil
|
|
}
|
|
|
|
// rowOf derives the row a lifecycle stores: the live pin is what runs and the
|
|
// accepted grants are what it runs with. Nothing is enabled before an
|
|
// operator has accepted grants, and a slot the grants don't name is dropped.
|
|
func rowOf(base store.Accepted, rec packageRecord, enabled bool) (store.Accepted, error) {
|
|
raw, err := json.Marshal(rec)
|
|
if err != nil {
|
|
return store.Accepted{}, err
|
|
}
|
|
slots, err := decodeSlots(base.Credentials)
|
|
if err != nil {
|
|
return store.Accepted{}, err
|
|
}
|
|
granted := catalogue.Grants{}
|
|
if g := rec.State.Accepted; g != nil {
|
|
granted = *g
|
|
}
|
|
maps.DeleteFunc(slots, func(slot, _ string) bool { return !slices.Contains(granted.Credentials, slot) })
|
|
base.Credentials, err = json.Marshal(slots, json.FormatNilMapAsNull(false))
|
|
if err != nil {
|
|
return store.Accepted{}, err
|
|
}
|
|
base.Path, base.SHA256 = rec.State.Current.Path, rec.State.Current.Digest
|
|
base.Egress, base.Env = granted.Egress, granted.Env
|
|
base.Package = raw
|
|
base.Enabled = enabled && rec.State.Accepted != nil
|
|
return base, nil
|
|
}
|
|
|
|
// restarts reports whether a change to the row needs the process restarted.
|
|
func restarts(old, next store.Accepted) bool {
|
|
return old.Path != next.Path || old.SHA256 != next.SHA256 || old.Enabled != next.Enabled ||
|
|
!slices.Equal(old.Egress, next.Egress) || !slices.Equal(old.Env, next.Env) ||
|
|
!bytes.Equal(old.Credentials, next.Credentials) || !bytes.Equal(old.Settings, next.Settings)
|
|
}
|
|
|
|
// acceptedRow returns the stored acceptance of name; ok is false when there is
|
|
// none.
|
|
func (m *Module) acceptedRow(ctx context.Context, name string) (a store.Accepted, ok bool, err error) {
|
|
accepted, err := m.store.List(ctx, m.orgID)
|
|
if err != nil {
|
|
return store.Accepted{}, false, err
|
|
}
|
|
i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == name })
|
|
if i < 0 {
|
|
return store.Accepted{}, false, nil
|
|
}
|
|
return accepted[i], true, nil
|
|
}
|
|
|
|
var errNotManaged = errors.New("not installed from the catalogue")
|
|
|
|
// find returns the installed package name.
|
|
func (m *Module) find(ctx context.Context, name string) (store.Accepted, packageRecord, error) {
|
|
accepted, err := m.store.List(ctx, m.orgID)
|
|
if err != nil {
|
|
return store.Accepted{}, packageRecord{}, err
|
|
}
|
|
i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == name })
|
|
if i < 0 {
|
|
return store.Accepted{}, packageRecord{}, fmt.Errorf("no extension named %s: %w", name, errNotManaged)
|
|
}
|
|
rec, ok, err := packageOf(accepted[i])
|
|
if err != nil {
|
|
return store.Accepted{}, packageRecord{}, err
|
|
}
|
|
if !ok {
|
|
return store.Accepted{}, packageRecord{}, fmt.Errorf("%s is accepted by path: %w", name, errNotManaged)
|
|
}
|
|
return accepted[i], rec, nil
|
|
}
|
|
|
|
// lifecycleError maps what a lifecycle change returns to an HTTP status.
|
|
func (m *Module) lifecycleError(ctx context.Context, err error) error {
|
|
var status *huma.ErrorModel
|
|
switch {
|
|
case errors.As(err, &status):
|
|
return err
|
|
case errors.Is(err, errNotManaged):
|
|
return huma.NewError(http.StatusNotFound, err.Error())
|
|
case errors.Is(err, catalogue.ErrBeyondDeclared), errors.Is(err, catalogue.ErrDigestMismatch):
|
|
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
|
|
case errors.Is(err, catalogue.ErrNoPending), errors.Is(err, catalogue.ErrNoPrevious):
|
|
return huma.NewError(http.StatusConflict, err.Error())
|
|
case errors.Is(err, catalogue.ErrInvalidPolicy):
|
|
return huma.NewError(http.StatusBadRequest, err.Error())
|
|
case errors.Is(err, errNoSource), errors.Is(err, catalogue.ErrBadSignature), errors.Is(err, catalogue.ErrStale):
|
|
return catalogueError(err)
|
|
}
|
|
m.log.ErrorContext(ctx, "extension lifecycle", "error", err)
|
|
return huma.NewError(http.StatusInternalServerError, "couldn't change the extension")
|
|
}
|
|
|
|
// replace stores next and restarts what changed. next is stored only once it
|
|
// has started and its settings are accepted, so a refused change leaves the
|
|
// extension, its stored settings and its declarations as they were.
|
|
func (m *Module) replace(ctx context.Context, old, next store.Accepted) error {
|
|
if !restarts(old, next) {
|
|
return m.store.Save(ctx, next, nil)
|
|
}
|
|
if err := m.commit(context.WithoutCancel(ctx), next, true, old); err != nil {
|
|
if errors.As(err, new(persistError)) {
|
|
return err
|
|
}
|
|
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// extensionName is the path of an operation on one installed extension.
|
|
type extensionName struct {
|
|
Name string `path:"name"`
|
|
}
|
|
|
|
// Lifecycle is the result of a change to an installed extension.
|
|
type Lifecycle struct {
|
|
Name string `json:"name"`
|
|
Version string `json:"version"`
|
|
Digest string `json:"digest"`
|
|
// Pending is set when an update asks for more than was accepted and waits
|
|
// for approval.
|
|
Pending bool `json:"pending"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
func lifecycleOf(a store.Accepted, rec packageRecord) *httpapi.Reply[Lifecycle] {
|
|
return httpapi.OK(Lifecycle{
|
|
Name: a.Name, Version: rec.State.Current.Version, Digest: rec.State.Current.Digest,
|
|
Pending: rec.State.Pending != nil, Enabled: a.Enabled,
|
|
})
|
|
}
|
|
|
|
// change applies one lifecycle step to an installed extension.
|
|
func (m *Module) change(ctx context.Context, name, action string, step func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error)) (*httpapi.Reply[Lifecycle], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
old, rec, err := m.find(ctx, name)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
next, nextRec, err := step(old, rec)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
if err := m.replace(ctx, old, next); err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
m.log.InfoContext(ctx, "extension changed", "audit", true, "action", "extension."+action, "package", name,
|
|
"digest", nextRec.State.Current.Digest)
|
|
return lifecycleOf(next, nextRec), nil
|
|
}
|
|
|
|
func (m *Module) install(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
doc, location, err := m.readCatalogue(ctx)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
entry, ok := doc.Entry(in.Name)
|
|
if !ok {
|
|
return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s", in.Name))
|
|
}
|
|
if !slices.Contains(catalogueContracts, entry.Contract) {
|
|
return nil, huma.NewError(http.StatusUnprocessableEntity, fmt.Sprintf("%s serves contract %q, which a catalogue doesn't install", entry.Name, entry.Contract))
|
|
}
|
|
accepted, err := m.store.List(ctx, m.orgID)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
if slices.ContainsFunc(accepted, func(a store.Accepted) bool { return a.Name == entry.Name }) {
|
|
return nil, huma.NewError(http.StatusConflict, entry.Name+" is already installed")
|
|
}
|
|
pin, err := m.fetchPin(ctx, location, entry)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
rec := packageRecord{DisplayName: entry.DisplayName, Description: entry.Description, State: catalogue.Install(pin)}
|
|
row, err := rowOf(store.Accepted{
|
|
OrgID: m.orgID, Name: entry.Name, Contract: entry.Contract,
|
|
Settings: []byte(`{}`), Credentials: []byte(`{}`), Tools: []byte(`[]`),
|
|
}, rec, false)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
if err := m.store.Save(ctx, row, nil); err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
m.log.InfoContext(ctx, "extension installed", "audit", true, "action", "extension.install", "package", entry.Name, "digest", pin.Digest)
|
|
return lifecycleOf(row, rec), nil
|
|
}
|
|
|
|
// fetchPin downloads the artifact an entry names and keeps it only if it
|
|
// hashes to the digest the entry pins.
|
|
func (m *Module) fetchPin(ctx context.Context, location string, entry catalogue.Entry) (catalogue.Pin, error) {
|
|
ref, err := catalogue.Resolve(location, entry.Artifact)
|
|
if err != nil {
|
|
return catalogue.Pin{}, err
|
|
}
|
|
path, err := m.fetcher.Fetch(ctx, entry.Name, ref, entry.Digest)
|
|
if err != nil {
|
|
return catalogue.Pin{}, fmt.Errorf("%s: %w", entry.Name, err)
|
|
}
|
|
return catalogue.Pin{Version: entry.Version, Digest: entry.Digest, Path: path, Declared: entry.Grants}, nil
|
|
}
|
|
|
|
// grantsRequest is what an operator accepts for an installed extension.
|
|
type grantsRequest struct {
|
|
Egress []string `json:"egress,omitzero" doc:"Every host the extension may reach; empty leaves it unconfined, which only an extension that declares no hosts may be given"`
|
|
Env []string `json:"env,omitzero" doc:"Host environment variables the extension may see"`
|
|
// Credentials maps each credential slot to a credential by name.
|
|
Credentials map[string]string `json:"credentials,omitzero"`
|
|
Settings map[string]string `json:"settings,omitzero"`
|
|
}
|
|
|
|
// acceptGrants records what an operator grants an installed extension. A
|
|
// request with no body accepts exactly what the extension declared; a body may
|
|
// narrow those grants and names the credential each slot resolves through.
|
|
type acceptGrantsInput struct {
|
|
Name string `path:"name"`
|
|
Body *grantsRequest
|
|
}
|
|
|
|
func (m *Module) acceptGrants(ctx context.Context, in *acceptGrantsInput) (*httpapi.Reply[Lifecycle], error) {
|
|
return m.change(ctx, in.Name, "accept", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
grants := rec.State.Current.Declared
|
|
if in.Body != nil {
|
|
grants = catalogue.Grants{Egress: in.Body.Egress, Env: in.Body.Env, Credentials: slices.Collect(maps.Keys(in.Body.Credentials))}
|
|
settings, err := json.Marshal(in.Body.Settings, json.FormatNilMapAsNull(false))
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
slots, err := json.Marshal(in.Body.Credentials, json.FormatNilMapAsNull(false))
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
a.Settings, a.Credentials = settings, slots
|
|
}
|
|
state, err := rec.State.Accept(grants)
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
rec.State = state
|
|
row, err := rowOf(a, rec, a.Enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
// putExtensionSettings changes an installed extension's settings and restarts
|
|
// it with them. A setting whose name ends in _ref names a secret engine and
|
|
// key; its value is never stored here.
|
|
type extensionSettingsInput struct {
|
|
Name string `path:"name"`
|
|
|
|
Body struct {
|
|
Settings map[string]string `json:"settings,omitzero"`
|
|
}
|
|
}
|
|
|
|
func (m *Module) putExtensionSettings(ctx context.Context, in *extensionSettingsInput) (*httpapi.Reply[Lifecycle], error) {
|
|
settings, err := json.Marshal(in.Body.Settings, json.FormatNilMapAsNull(false))
|
|
if err != nil {
|
|
return nil, huma.NewError(http.StatusBadRequest, err.Error())
|
|
}
|
|
return m.change(ctx, in.Name, "settings", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
a.Settings = settings
|
|
row, err := rowOf(a, rec, a.Enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
func (m *Module) updateExtension(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) {
|
|
doc, location, err := m.readCatalogue(ctx)
|
|
if err != nil {
|
|
return nil, m.lifecycleError(ctx, err)
|
|
}
|
|
return m.updateFrom(ctx, doc, location, in.Name)
|
|
}
|
|
|
|
// updateFrom moves name to the digest doc pins for it. An update that asks for
|
|
// no more than was accepted applies; one that asks for more waits for approval
|
|
// and changes nothing that runs.
|
|
func (m *Module) updateFrom(ctx context.Context, doc catalogue.Document, location, name string) (*httpapi.Reply[Lifecycle], error) {
|
|
entry, ok := doc.Entry(name)
|
|
if !ok {
|
|
return nil, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s", name))
|
|
}
|
|
return m.change(ctx, name, "update", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
if entry.Digest == rec.State.Current.Digest || (rec.State.Pending != nil && rec.State.Pending.Digest == entry.Digest) {
|
|
return a, rec, nil
|
|
}
|
|
pin, err := m.fetchPin(ctx, location, entry)
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
rec.State, _ = rec.State.Offer(pin)
|
|
rec.DisplayName, rec.Description = entry.DisplayName, entry.Description
|
|
row, err := rowOf(a, rec, a.Enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
func (m *Module) approveUpdate(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) {
|
|
return m.change(ctx, in.Name, "approve_update", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
state, err := rec.State.Approve()
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
rec.State = state
|
|
row, err := rowOf(a, rec, a.Enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
func (m *Module) rollback(ctx context.Context, in *extensionName) (*httpapi.Reply[Lifecycle], error) {
|
|
return m.change(ctx, in.Name, "rollback", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
state, err := rec.State.Rollback()
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
rec.State = state
|
|
row, err := rowOf(a, rec, a.Enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
type extensionPolicyInput struct {
|
|
Name string `path:"name"`
|
|
|
|
Body struct {
|
|
Policy string `json:"policy" enum:"manual,auto"`
|
|
}
|
|
}
|
|
|
|
func (m *Module) setPolicy(ctx context.Context, in *extensionPolicyInput) (*httpapi.Reply[Lifecycle], error) {
|
|
return m.change(ctx, in.Name, "update_policy", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
state, err := rec.State.SetPolicy(in.Body.Policy)
|
|
if err != nil {
|
|
return store.Accepted{}, rec, err
|
|
}
|
|
rec.State = state
|
|
row, err := rowOf(a, rec, a.Enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
type extensionEnabledInput struct {
|
|
Name string `path:"name"`
|
|
|
|
Body struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
}
|
|
|
|
func (m *Module) setEnabled(ctx context.Context, in *extensionEnabledInput) (*httpapi.Reply[Lifecycle], error) {
|
|
enabled := in.Body.Enabled
|
|
return m.change(ctx, in.Name, "enable", func(a store.Accepted, rec packageRecord) (store.Accepted, packageRecord, error) {
|
|
if enabled && rec.State.Accepted == nil {
|
|
return store.Accepted{}, rec, huma.NewError(http.StatusConflict, "accept the extension's grants before enabling it")
|
|
}
|
|
row, err := rowOf(a, rec, enabled)
|
|
return row, rec, err
|
|
})
|
|
}
|
|
|
|
// UpdateAuto updates every extension whose policy is auto to the digest the
|
|
// catalogue pins. One that fails doesn't stop the rest. It does nothing when no
|
|
// catalogue source is set.
|
|
func (m *Module) UpdateAuto(ctx context.Context) error {
|
|
accepted, err := m.store.List(ctx, m.orgID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var auto []string
|
|
for _, a := range accepted {
|
|
if rec, ok, err := packageOf(a); err == nil && ok && rec.State.Policy == catalogue.PolicyAuto {
|
|
auto = append(auto, a.Name)
|
|
}
|
|
}
|
|
if len(auto) == 0 {
|
|
return nil
|
|
}
|
|
doc, location, err := m.readCatalogue(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var errs []error
|
|
for _, name := range auto {
|
|
if _, err := m.updateFrom(ctx, doc, location, name); err != nil {
|
|
errs = append(errs, fmt.Errorf("update %s: %w", name, err))
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// WatchUpdates runs UpdateAuto every interval until ctx ends.
|
|
func (m *Module) WatchUpdates(ctx context.Context, interval time.Duration) {
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
if err := m.UpdateAuto(ctx); err != nil {
|
|
m.log.WarnContext(ctx, "update extensions from the catalogue", "error", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ManagedView is what the dashboard shows of an extension installed from the
|
|
// catalogue: what each version declared next to what the operator accepted.
|
|
type ManagedView struct {
|
|
DisplayName string `json:"display_name"`
|
|
Description string `json:"description"`
|
|
Declared catalogue.Grants `json:"declared"`
|
|
// Accepted is nil until the operator accepts grants.
|
|
Accepted *catalogue.Grants `json:"accepted"`
|
|
// Pending is an update waiting for approval, with what it adds to the
|
|
// accepted grants.
|
|
Pending *PendingView `json:"pending"`
|
|
CanRollback bool `json:"can_rollback"`
|
|
UpdatePolicy string `json:"update_policy" enum:"manual,auto"`
|
|
}
|
|
|
|
// PendingView is an update that asks for more than was accepted.
|
|
type PendingView struct {
|
|
Version string `json:"version"`
|
|
Digest string `json:"digest"`
|
|
Added catalogue.Grants `json:"added"`
|
|
}
|
|
|
|
func managedView(rec packageRecord) *ManagedView {
|
|
s := rec.State
|
|
view := &ManagedView{
|
|
DisplayName: rec.DisplayName, Description: rec.Description,
|
|
Declared: s.Current.Declared.Normalised(), CanRollback: s.Previous != nil, UpdatePolicy: s.Policy,
|
|
}
|
|
var held catalogue.Grants
|
|
if s.Accepted != nil {
|
|
held = s.Accepted.Normalised()
|
|
view.Accepted = &held
|
|
}
|
|
if s.Pending != nil {
|
|
view.Pending = &PendingView{
|
|
Version: s.Pending.Version, Digest: s.Pending.Digest, Added: held.Added(s.Pending.Declared.Normalised()),
|
|
}
|
|
}
|
|
return view
|
|
}
|