package connectors import ( "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "log/slog" "maps" "regexp" "slices" "sort" "strings" "sync" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/samcharles93/archie-core/internal/platform/seal" "github.com/samcharles93/archie-core/modules/connectors/internal/catalogue" "github.com/samcharles93/archie-core/modules/connectors/internal/store" ) // validName is the shape of a connector name: it appears in logs and URLs. var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`) // Module runs the installations of the accepted connectors, secret engines, // guards and MCP servers, keeps the credentials they are configured with, and // serves their administration. Every running extension is one installation, // keyed by its ID; a name resolves to an installation for the scope that asks. type Module struct { host *Host store registry 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. sources sourceStore fetcher *catalogue.Fetcher pkgMu sync.Mutex mu sync.RWMutex idx index // running, engines, guards and servers hold what each installation // launched, keyed by installation ID. stops ends each MCP server's // supervisor. running map[string]*Connector engines map[string]*Engine guards map[string]*Guard servers map[string]*Server stops map[string]context.CancelFunc failed map[string]string // failedAt is when an installation last failed to start, and launched is // what each launched installation is. Both are read only for health, so an // entry that outlives its failure does no harm. failedAt map[string]time.Time launched map[string]launchedInfo // recheck, when set, re-checks saved configuration against a connector's // new declarations; an error refuses them. recheck Recheck } // launchedInfo is what health says about an installation that was launched. type launchedInfo struct { name, contract, scope string } // Recheck re-checks saved configuration against the capabilities a connector // now declares. An error refuses the new declarations. type Recheck func(ctx context.Context, connector string, caps Capabilities) error // Use sets the hook called when a connector's declarations change. func (m *Module) Use(recheck Recheck) { m.mu.Lock() defer m.mu.Unlock() m.recheck = recheck } // installationStore is where installations, their overrides and the // capabilities of the package they configure are kept. 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 SetOverride(ctx context.Context, o store.Override, off bool, by string) error DeleteInstallation(ctx context.Context, id uuid.UUID) (bool, error) } // packageStore is where the packages the instance accepted are kept. type packageStore interface { Packages(ctx context.Context) ([]store.Package, error) SaveInstalled(ctx context.Context, in store.Installed, by string, capabilities jsontext.Value) (store.Installed, error) DeletePackage(ctx context.Context, name string) (bool, error) } // credentialStore is where sealed credentials are kept. type credentialStore interface { Credentials(ctx context.Context) ([]store.Credential, error) PutCredential(ctx context.Context, c store.Credential) error } // registry is the module's persistence, so removal can be tested with a fake. type registry interface { installationStore packageStore credentialStore } // Sealing is the age identity credentials are sealed with, and the backup // recipients that can also open them. type Sealing struct { Identity string Backups []string } // NewModule returns the connectors module. // // Artifacts fetched from the catalogue are kept under artifactDir. func NewModule(db *sqlx.DB, log *slog.Logger, sealing Sealing, artifactDir string) (*Module, error) { sealer, err := seal.New(sealing.Identity, sealing.Backups) if err != nil { return nil, err } st := store.New(db) return &Module{ host: NewHost(log), store: st, sealer: sealer, log: log, sources: st, fetcher: catalogue.NewFetcher(artifactDir), running: map[string]*Connector{}, engines: map[string]*Engine{}, guards: map[string]*Guard{}, failed: map[string]string{}, servers: map[string]*Server{}, stops: map[string]context.CancelFunc{}, }, nil } // refresh reads every installation and override, rebuilds the index that // resolves names, and returns the installations. func (m *Module) refresh(ctx context.Context) ([]store.Installed, error) { installed, err := m.store.List(ctx) if err != nil { return nil, err } overrides, err := m.store.Overrides(ctx) if err != nil { return nil, err } ix := newIndex(installed, overrides) m.mu.Lock() m.idx = ix m.mu.Unlock() return installed, nil } // Start launches every enabled secret engine, then every enabled connector, // since a connector's credentials may be resolved through an engine. One that // fails to start is reported by Ready and logged; the others still run. // // Its only error is the read of the installations, which happens before // anything launches, so a caller may call Start again after a failure without // launching anything twice. func (m *Module) Start(ctx context.Context) error { installed, err := m.refresh(ctx) if err != nil { return err } for _, a := range ordered(installed) { // A failure is recorded for Ready and logged; the rest still start. _ = m.launch(ctx, a) } return nil } // ordered starts secret engines first, then connectors, then MCP servers: a // credential may be resolved through an engine. func ordered(installed []store.Installed) []store.Installed { out := slices.Clone(installed) slices.SortStableFunc(out, func(a, b store.Installed) int { return cmp.Compare(rank(a), rank(b)) }) return out } func rank(a store.Installed) int { switch a.Contract { case store.ContractSecretEngine: return 0 case store.ContractMCP: return 2 } return 1 } // resolve finds the running installation ref names for the scope ctx acts for. func (m *Module) resolve(ctx context.Context, ref string) (member, bool) { s := ScopeFromContext(ctx) m.mu.RLock() defer m.mu.RUnlock() return m.idx.resolve(s, ref) } // visible lists the installations each name resolves to for the scope ctx acts // for. func (m *Module) visible(ctx context.Context) []member { s := ScopeFromContext(ctx) m.mu.RLock() defer m.mu.RUnlock() return m.idx.visible(s) } // Get returns the running connector ref names for the caller: an installation // ID, or a name that resolves to the person's installation, then the // organisation's, then the instance's. An MCP server is reached through Tool, // since it answers lookups and actions rather than events. func (m *Module) Get(ctx context.Context, ref string) (*Connector, bool) { mem, ok := m.resolve(ctx, ref) if !ok { return nil, false } m.mu.RLock() defer m.mu.RUnlock() c, ok := m.running[mem.id] return c, ok } // Tool returns the connector or MCP server ref names for the caller. func (m *Module) Tool(ctx context.Context, ref string) (Tool, bool) { mem, ok := m.resolve(ctx, ref) if !ok { return nil, false } return m.Installed(mem.id) } // Installed returns the connector or MCP server running as installation id, // whoever asks. A decision records the installation it resolved, and executing // that decision runs there, whatever scope the approver acts for. func (m *Module) Installed(id string) (Tool, bool) { m.mu.RLock() defer m.mu.RUnlock() if c, ok := m.running[id]; ok { return c, true } s, ok := m.servers[id] return s, ok } // TargetFacts asks every connector the caller can use that serves target facts // what it knows about t, now, and keeps nothing. Connectors are asked in name // order and the first to supply a fact wins it. func (m *Module) TargetFacts(ctx context.Context, t Target) (TargetFacts, error) { var asked []*Connector for _, c := range m.connectorsFor(ctx) { if c.facts { asked = append(asked, c) } } var out TargetFacts for _, c := range asked { got, err := c.TargetFacts(ctx, t) if err != nil { return TargetFacts{}, err } out.OwnerIdentity = cmp.Or(out.OwnerIdentity, got.OwnerIdentity) out.DataClass = cmp.Or(out.DataClass, got.DataClass) out.Count = cmp.Or(out.Count, got.Count) } return out, nil } // connectorsFor lists the running connectors the caller can use, in name order. func (m *Module) connectorsFor(ctx context.Context) []*Connector { visible := m.visible(ctx) m.mu.RLock() defer m.mu.RUnlock() var out []*Connector for _, mem := range visible { if c, ok := m.running[mem.id]; ok { out = append(out, c) } } return out } // Guards lists the running guard extensions the caller can use, in name order. func (m *Module) Guards(ctx context.Context) []*Guard { visible := m.visible(ctx) m.mu.RLock() defer m.mu.RUnlock() var out []*Guard for _, mem := range visible { if g, ok := m.guards[mem.id]; ok { out = append(out, g) } } return out } // Delivering lists the running connectors the caller can use that send the // named delivery, in name order: the channels a message goes out on. func (m *Module) Delivering(ctx context.Context, delivery string) []*Connector { var out []*Connector for _, c := range m.connectorsFor(ctx) { if c.Delivers(delivery) { out = append(out, c) } } return out } // LinkableChannels lists the running connectors the caller can use that can // link a person's channel identity to their account, in name order. func (m *Module) LinkableChannels(ctx context.Context) ([]string, error) { var out []string for _, c := range m.connectorsFor(ctx) { if c.LinksAccounts() { out = append(out, c.Name()) } } return out, nil } // LinkURL asks the running connector for the URL that delivers a link code. func (m *Module) LinkURL(ctx context.Context, connector, code string) (string, error) { c, ok := m.Get(ctx, connector) if !ok { return "", fmt.Errorf("connector %q isn't running", connector) } return c.LinkURL(ctx, code) } // Declarations lists every lookup and action of the connectors the caller can // use and every tool of the MCP servers it can use, ordered by name and then by // tool name. func (m *Module) Declarations(ctx context.Context) []Declaration { visible := m.visible(ctx) m.mu.RLock() defer m.mu.RUnlock() var out []Declaration for _, mem := range visible { if c, ok := m.running[mem.id]; ok { out = append(out, c.Declarations()...) } if s, ok := m.servers[mem.id]; ok { out = append(out, s.Declarations()...) } } return out } // label names an installation in a problem report. func (m *Module) label(id string) string { info, ok := m.launched[id] switch { case !ok: return id case info.scope == store.ScopeInstance: return info.name } return info.name + " (" + info.scope + ")" } // Ready reports an extension that failed to start or whose process has exited, // and an MCP server that doesn't answer. func (m *Module) Ready(context.Context) error { m.mu.RLock() var problems []string for id, reason := range m.failed { problems = append(problems, m.label(id)+": "+reason) } for _, id := range slices.Concat(slices.Collect(maps.Keys(m.running)), slices.Collect(maps.Keys(m.engines)), slices.Collect(maps.Keys(m.guards))) { if !m.host.Alive(id) { problems = append(problems, m.label(id)+": process exited") } } servers := maps.Clone(m.servers) labels := make(map[string]string, len(servers)) for id := range servers { labels[id] = m.label(id) } m.mu.RUnlock() for _, id := range slices.Sorted(maps.Keys(servers)) { if err := servers[id].Ready(); err != nil { problems = append(problems, labels[id]+": "+err.Error()) } } if len(problems) == 0 { return nil } sort.Strings(problems) return errors.New(strings.Join(problems, "; ")) } // Close stops every connector, secret engine and MCP server. func (m *Module) Close() { m.mu.Lock() stops, servers := m.stops, m.servers m.stops, m.servers = map[string]context.CancelFunc{}, map[string]*Server{} m.mu.Unlock() for _, stop := range stops { stop() } for _, s := range servers { s.Close() } m.host.Close() } // persistFunc stores a launched installation and the declarations its package // made. type persistFunc func(ctx context.Context, in store.Installed, capabilities jsontext.Value) (store.Installed, error) // persistError marks a failure to store an acceptance, as distinct from a // refusal. type persistError struct{ err error } func (e persistError) Error() string { return e.err.Error() } func (e persistError) Unwrap() error { return e.err } // commit starts next and stores it only once it has started and its // declarations and settings are accepted. The installation and the connector's // declarations are written in one transaction, after every check, so a // refusal changes nothing that is stored. The extension that previously ran // as the installation is restarted from its stored row. func (m *Module) commit(ctx context.Context, next store.Installed, hadPrevious bool, previous store.Installed, persist persistFunc) error { saved := false save := func(ctx context.Context, caps jsontext.Value) error { if _, err := persist(ctx, next, caps); err != nil { return persistError{err} } saved = true return nil } err := m.launchWith(ctx, next, save) // A connector validates its settings against its declared schema before // saving. Other contracts are checked after they start. if err == nil && !saved && next.Enabled && next.Contract != store.ContractConnector { err = m.checkInstalled(next) } if err == nil && !saved { err = save(ctx, nil) } if err == nil { if _, rerr := m.refresh(ctx); rerr != nil { return persistError{rerr} } return nil } m.release(next.ID.String()) m.mu.Lock() delete(m.failed, next.ID.String()) m.mu.Unlock() if hadPrevious { _ = m.launch(ctx, previous) } return err } // launch starts or restarts one installation and records the outcome. An // installation runs as one extension: whatever ran as it before is stopped // first. func (m *Module) launch(ctx context.Context, a store.Installed) error { return m.launchWith(ctx, a, nil) } // launchWith launches an installation that is not stored yet. When save is // set, a connector calls it with its declarations once they and its settings // are accepted, and is registered only if it succeeds; the other contracts // leave saving to the caller. Without save, the row is already stored and only // the declarations are recorded. func (m *Module) launchWith(ctx context.Context, a store.Installed, save func(context.Context, jsontext.Value) error) error { id := a.ID.String() m.releaseAs(a) if !a.Enabled { m.markStopped(id) return nil } if a.Contract == store.ContractMCP { return m.startServer(ctx, a) } spec, err := m.processSpec(ctx, a) if err != nil { return m.fail(ctx, id, a.Name, err) } inst := Installation{ID: a.ID, Scope: a.Scope} if a.Contract == store.ContractSecretEngine { e, err := m.host.StartEngine(ctx, spec) if err != nil { return m.fail(ctx, id, a.Name, err) } m.mu.Lock() m.engines[id] = e delete(m.failed, id) m.mu.Unlock() m.log.InfoContext(ctx, "secret engine started", "engine", a.Name, "installation", id, "scope", a.Scope) return nil } if a.Contract == store.ContractGuard { return m.startGuard(ctx, a, spec) } c, err := m.host.Start(ctx, spec) if err != nil { return m.fail(ctx, id, a.Name, err) } c.installation = inst if err := m.checkDeclarations(ctx, a.Name, c.Capabilities()); err != nil { m.host.Stop(id) return m.fail(ctx, id, a.Name, err) } if save != nil { if err := checkSettingValues(c.SettingsSchema(), a.Settings); err != nil { m.host.Stop(id) return m.fail(ctx, id, a.Name, err) } } if err := m.storeCapabilities(ctx, a, c, save); err != nil { m.host.Stop(id) return m.fail(ctx, id, a.Name, err) } m.mu.Lock() m.running[id] = c delete(m.failed, id) m.mu.Unlock() m.log.InfoContext(ctx, "connector started", "connector", a.Name, "installation", id, "scope", a.Scope) return nil } // processSpec is what a connector, guard or secret engine runs with: its // settings with secret references resolved, and the secrets its credential // slots name. func (m *Module) processSpec(ctx context.Context, a store.Installed) (Spec, error) { var settings map[string]string if len(a.Settings) > 0 { if err := json.Unmarshal(a.Settings, &settings); err != nil { return Spec{}, fmt.Errorf("settings: %w", err) } } settings, secretSettings, err := m.splitSecretSettings(ctx, a, settings) if err != nil { return Spec{}, err } secrets, err := m.secrets(ctx, a) if err != nil { return Spec{}, err } maps.Copy(secrets, secretSettings) return Spec{ Name: a.Name, Key: a.ID.String(), Path: a.Path, SHA256: a.SHA256, Env: a.Env, Egress: a.Egress, Settings: settings, Secrets: secrets, }, nil } // startGuard launches a guard and records it as running. func (m *Module) startGuard(ctx context.Context, a store.Installed, spec Spec) error { id := a.ID.String() g, err := m.host.StartGuard(ctx, spec) if err != nil { return m.fail(ctx, id, a.Name, err) } m.mu.Lock() m.guards[id] = g delete(m.failed, id) m.mu.Unlock() m.log.InfoContext(ctx, "guard started", "guard", a.Name, "installation", id, "scope", a.Scope) return nil } // checkDeclarations refuses declarations core can't work with before they are // stored: a reserved delivery whose schema rejects what core sends, or saved // configuration that the new declarations break. The connector's previous // declarations stay in force. func (m *Module) checkDeclarations(ctx context.Context, name string, caps Capabilities) error { if err := checkCoreDeliveries(caps); err != nil { return err } m.mu.RLock() recheck := m.recheck m.mu.RUnlock() if recheck != nil { if err := recheck(ctx, name, caps); err != nil { return fmt.Errorf("saved configuration doesn't match the new declarations: %w", err) } } return nil } // storeCapabilities records what a connector declared, so workflows and // triggers can be checked against it while the connector is stopped. func (m *Module) storeCapabilities(ctx context.Context, a store.Installed, c *Connector, save func(context.Context, jsontext.Value) error) error { raw, err := json.Marshal(c.Capabilities()) if err != nil { return fmt.Errorf("encode capabilities: %w", err) } if save != nil { return save(ctx, raw) } return m.store.SetCapabilities(ctx, a.PackageID, raw) } // refSuffix marks a setting that names a secret rather than holding one. The // host resolves it through the named engine, so the extension never reads the // reference. const refSuffix = "_ref" // engineAt returns the running secret engine name resolves to for what o // owns: the engine of the same person or organisation, then the instance's. func (m *Module) engineAt(o store.Owner, name string) (*Engine, bool) { m.mu.RLock() defer m.mu.RUnlock() mem, ok := m.idx.resolve(scopeOf(o), name) if !ok || mem.contract != store.ContractSecretEngine { return nil, false } e, ok := m.engines[mem.id] return e, ok } // splitSecretSettings separates an installation's secret settings from the // rest, resolves each reference, and returns the plain settings and the // secrets the extension is configured with. A secret engine's own settings // must hold their values: an engine never waits on another engine. func (m *Module) splitSecretSettings(ctx context.Context, a store.Installed, settings map[string]string) (map[string]string, map[string]string, error) { plain := make(map[string]string, len(settings)) secrets := map[string]string{} for key, value := range settings { name, isRef := strings.CutSuffix(key, refSuffix) if !isRef { plain[key] = value continue } if a.Contract == store.ContractSecretEngine { return nil, nil, fmt.Errorf("setting %q: a secret engine's own settings must hold their values", key) } engineName, ref, ok := strings.Cut(value, ":") if !ok || engineName == "" || ref == "" { return nil, nil, fmt.Errorf("setting %q wants engine:key", key) } engine, running := m.engineAt(a.Owner(), engineName) if !running { return nil, nil, fmt.Errorf("setting %q: secret engine %q isn't running", key, engineName) } secret, err := engine.Resolve(ctx, ref) if err != nil { return nil, nil, fmt.Errorf("setting %q: %w", key, err) } secrets[name] = secret } return plain, secrets, nil } // release stops whatever ran as installation id. func (m *Module) release(id string) { m.mu.Lock() _, running := m.running[id] _, engine := m.engines[id] _, guard := m.guards[id] s, stop := m.servers[id], m.stops[id] delete(m.running, id) delete(m.engines, id) delete(m.guards, id) delete(m.servers, id) delete(m.stops, id) m.mu.Unlock() if running || engine || guard { m.host.Stop(id) } if stop != nil { stop() } if s != nil { s.Close() } } // releaseAs stops whatever ran as a's installation and records what it is // about to be. func (m *Module) releaseAs(a store.Installed) { id := a.ID.String() m.release(id) m.mu.Lock() defer m.mu.Unlock() if m.launched == nil { m.launched = map[string]launchedInfo{} } m.launched[id] = launchedInfo{name: a.Name, contract: a.Contract, scope: a.Scope} } // forget drops what the module knows of a removed installation. func (m *Module) forget(id string) { m.release(id) m.mu.Lock() defer m.mu.Unlock() delete(m.failed, id) delete(m.failedAt, id) delete(m.launched, id) } // markStopped forgets an installation's failure now that it is not meant to run. func (m *Module) markStopped(id string) { m.mu.Lock() defer m.mu.Unlock() delete(m.failed, id) } func (m *Module) fail(ctx context.Context, id, name string, err error) error { m.mu.Lock() delete(m.running, id) delete(m.engines, id) delete(m.guards, id) m.failed[id] = err.Error() if m.failedAt == nil { m.failedAt = map[string]time.Time{} } m.failedAt[id] = time.Now() m.mu.Unlock() m.log.ErrorContext(ctx, "extension failed to start", "extension", name, "installation", id, "error", err) return err }