package connectors import ( "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" "fmt" "net/http" "github.com/danielgtaylor/huma/v2" "github.com/google/uuid" "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" ) // ExtensionView is one accepted package as the dashboard shows it: what it is, // whether it is running, and the settings and credential slots it was given. // It never carries a secret: a credential is named, and a secret setting is // the reference the extension resolves. type ExtensionView struct { // ID is the installation's ID, which a decision records. ID uuid.UUID `json:"id"` // Name is the installation's name, which a binding uses; Package is the // package it installs. Name string `json:"name"` Package string `json:"package"` // Scope is who owns the installation. OwnerID is the organisation or the // person, and is empty for the instance. Scope string `json:"scope" enum:"instance,org,person"` OwnerID string `json:"owner_id,omitempty"` // Editable says whether the caller may change the installation. Overridden // says the caller's organisation or person switched an inherited // installation off, and OverriddenBy names the scopes that did. CanOverride // lists the scopes the caller may switch it off at, and is empty when the // caller owns it or inherits nothing. Editable bool `json:"editable"` Overridden bool `json:"overridden"` OverriddenBy []string `json:"overridden_by,omitempty" enum:"org,person"` CanOverride []string `json:"can_override,omitempty" enum:"org,person"` Contract string `json:"contract"` Group string `json:"group" enum:"platform,integration,agent"` State string `json:"state"` Error string `json:"error,omitempty"` Version string `json:"version,omitempty"` Digest string `json:"digest"` Path string `json:"path,omitempty"` URL string `json:"url,omitempty"` Args []string `json:"args,omitempty"` Egress []string `json:"egress"` Env []string `json:"env"` Settings map[string]string `json:"settings"` SettingsSchema []Setting `json:"settings_schema"` Credentials map[string]string `json:"credentials"` Tools jsontext.Value `json:"tools,omitempty"` // Effects is an MCP server's declaration of its privileged effects; absent // until declared. Effects *ServerEffects `json:"effects,omitempty"` // Capabilities is what a connector declared when it last loaded. It is // absent for other packages and for a connector that has never loaded. Capabilities *Capabilities `json:"capabilities,omitempty"` // Enabled says whether an accepted package runs. A package accepted by path // runs while its digest matches; one installed from the catalogue runs once // its grants are accepted and it is enabled. Enabled bool `json:"enabled"` // Managed says the package was installed from the catalogue. Managed bool `json:"managed"` DisplayName string `json:"display_name,omitempty"` Description string `json:"description,omitempty"` Declared *catalogue.Grants `json:"declared,omitempty"` Accepted *catalogue.Grants `json:"accepted,omitempty"` // Pending is an update waiting for approval, with what it adds to the // accepted grants. Pending *PendingView `json:"pending,omitempty"` CanRollback bool `json:"can_rollback"` UpdatePolicy string `json:"update_policy,omitempty"` } // list returns the installations of one contract the caller can see, in name // order. func (m *Module) list(contract string) func(context.Context, *struct{}) (*httpapi.Reply[[]ExtensionView], error) { return func(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ExtensionView], error) { return m.listViews(ctx, func(a store.Installed) bool { return a.Contract == contract }) } } // listViews returns the installations the caller can see that keep accepts. func (m *Module) listViews(ctx context.Context, keep func(store.Installed) bool) (*httpapi.Reply[[]ExtensionView], error) { auth, err := authorityOf(ctx) if err != nil { return nil, err } installed, err := m.refresh(ctx) if err != nil { m.log.ErrorContext(ctx, "list installations", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations") } scope := ScopeFromContext(ctx) views := make([]ExtensionView, 0, len(installed)) for _, a := range installed { if !keep(a) || !auth.sees(a.Owner()) { continue } view, err := m.viewOf(a, auth.manages(a.Owner())) if err != nil { m.log.ErrorContext(ctx, "read installation", "installation", a.Name, "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't read "+a.Name) } m.mu.RLock() mem := m.idx.members[a.ID.String()] view.Overridden = m.idx.hidden(scope, mem) view.OverriddenBy = m.idx.overriddenBy(scope, mem) m.mu.RUnlock() if !view.Editable { view.CanOverride = overrideScopes(auth, a.Owner()) } views = append(views, view) } return httpapi.OK(views), nil } // viewOf shows an installation. A caller who may not change it sees what it is // and whether it runs, and none of its configuration. func (m *Module) viewOf(a store.Installed, editable bool) (ExtensionView, error) { view := ExtensionView{ ID: a.ID, Name: a.Name, Package: a.PackageName, Scope: a.Scope, OwnerID: cmp.Or(a.OrgID, a.PersonID), Editable: editable, Contract: a.Contract, Group: string(store.GroupOf(a.Contract)), Digest: a.SHA256, Tools: a.Tools, Egress: []string{}, Env: []string{}, Settings: map[string]string{}, Credentials: map[string]string{}, SettingsSchema: []Setting{}, } if editable { view.Path, view.URL, view.Args, view.Egress, view.Env = a.Path, a.URL, a.Args, a.Egress, a.Env } if len(a.Settings) > 0 && editable { if err := json.Unmarshal(a.Settings, &view.Settings); err != nil { return ExtensionView{}, fmt.Errorf("settings: %w", err) } } if len(a.Credentials) > 0 && editable { if err := json.Unmarshal(a.Credentials, &view.Credentials); err != nil { return ExtensionView{}, fmt.Errorf("credentials: %w", err) } } if len(a.Effects) > 0 { view.Effects = new(ServerEffects) if err := json.Unmarshal(a.Effects, view.Effects); err != nil { return ExtensionView{}, fmt.Errorf("effects: %w", err) } } if len(a.Capabilities) > 0 { view.Capabilities = new(Capabilities) if err := json.Unmarshal(a.Capabilities, view.Capabilities); err != nil { return ExtensionView{}, fmt.Errorf("capabilities: %w", err) } } state, reason, version, schema := m.stateOf(a) if !editable { schema = []Setting{} } view.State, view.Error, view.Version, view.SettingsSchema = state, reason, version, schema view.Enabled = a.Enabled if rec, ok, err := packageOf(a); err != nil { return ExtensionView{}, err } else if ok { managed := managedView(rec) view.Managed = true view.DisplayName, view.Description = managed.DisplayName, managed.Description view.Declared, view.Accepted = &managed.Declared, managed.Accepted view.Pending, view.CanRollback, view.UpdatePolicy = managed.Pending, managed.CanRollback, managed.UpdatePolicy view.Version = rec.State.Current.Version } return view, nil } // stateOf reports whether a package is running, and what it declared. func (m *Module) stateOf(a store.Installed) (state, reason, version string, schema []Setting) { id := a.ID.String() m.mu.RLock() reason = m.failed[id] connector, running := m.running[id] engine, isEngine := m.engines[id] guard, isGuard := m.guards[id] server, isServer := m.servers[id] m.mu.RUnlock() switch { case reason != "": return "failed", reason, "", nil case running: return "running", "", connector.Version(), connector.SettingsSchema() case isEngine: return "running", "", engine.Version(), engine.SettingsSchema() case isGuard: return "running", "", guard.Version(), guard.SettingsSchema() case isServer: if err := server.Ready(); err != nil { return "failed", err.Error(), "", server.SettingsSchema() } return "running", "", "", server.SettingsSchema() } return "stopped", "", "", nil } // schemaOf returns the settings schema of an installation that is running now. func (m *Module) schemaOf(id string) ([]Setting, bool) { m.mu.RLock() defer m.mu.RUnlock() switch { case m.running[id] != nil: return m.running[id].SettingsSchema(), true case m.engines[id] != nil: return m.engines[id].SettingsSchema(), true case m.guards[id] != nil: return m.guards[id].SettingsSchema(), true case m.servers[id] != nil: return m.servers[id].SettingsSchema(), true } return nil, false } // checkInstalled checks an installation's settings against the schema the // package declared, once it is known. func (m *Module) checkInstalled(a store.Installed) error { schema, ok := m.schemaOf(a.ID.String()) if !ok || len(schema) == 0 { return nil } return checkSettingValues(schema, a.Settings) } // checkSettingValues checks stored settings against a declared schema. func checkSettingValues(schema []Setting, stored []byte) error { var values map[string]string if len(stored) > 0 { if err := json.Unmarshal(stored, &values); err != nil { return fmt.Errorf("settings: %w", err) } } _, err := checkSettings(schema, values) return err }