package connectors import ( "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" "fmt" "maps" "net/http" "slices" "time" "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" "github.com/samcharles93/archie-core/modules/governance" ) func (m *Module) registerInstallations(api huma.API) { tags := []string{"Installations"} read := httpapi.Authorized(governance.ActionRead, governance.KindConnector) write := httpapi.Authorized(governance.ActionUpdate, governance.KindConnector) httpapi.Register(api, read, huma.Operation{ OperationID: "list-packages", Method: http.MethodGet, Path: "/api/packages", Summary: "List the packages the instance accepted", Tags: tags, }, m.listPackages) httpapi.Register(api, write, huma.Operation{ OperationID: "create-installation", Method: http.MethodPost, Path: "/api/installations", Summary: "Install an accepted package at the instance, the caller's organisation or the caller", Tags: tags, }, m.createInstallation) httpapi.Register(api, write, huma.Operation{ OperationID: "update-installation", Method: http.MethodPut, Path: "/api/installations/{id}", Summary: "Change an installation's configuration and restart it", Tags: tags, }, m.updateInstallation) httpapi.Register(api, httpapi.Authorized(governance.ActionDelete, governance.KindConnector), huma.Operation{ OperationID: "remove-installation", Method: http.MethodDelete, Path: "/api/installations/{id}", Summary: "Remove an installation; its package stays accepted", Tags: tags, }, m.removeInstallation) httpapi.Register(api, write, huma.Operation{ OperationID: "put-installation-override", Method: http.MethodPut, Path: "/api/installations/{id}/override", Summary: "Switch an inherited installation off or on for the caller's organisation or the caller", Tags: tags, }, m.putOverride) } // PackageView is one package the instance accepted, with its versions. type PackageView struct { ID uuid.UUID `json:"id"` Name string `json:"name"` Contract string `json:"contract"` Group string `json:"group" enum:"platform,integration,agent"` DisplayName string `json:"display_name,omitempty"` Description string `json:"description,omitempty"` // DefaultVersion is the version installations run unless they pin one. DefaultVersion string `json:"default_version"` // Managed says the package was installed from the catalogue. Managed bool `json:"managed"` UpdatePolicy string `json:"update_policy" enum:"manual,auto"` Versions []VersionView `json:"versions"` AcceptedAt time.Time `json:"accepted_at"` } func (m *Module) listPackages(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]PackageView], error) { pkgs, installed, err := m.packagesAndInstallations(ctx) if err != nil { return nil, err } versions, err := m.store.Versions(ctx) if err != nil { m.log.ErrorContext(ctx, "list package versions", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the package versions") } running := map[uuid.UUID]int{} for _, a := range installed { running[a.VersionID]++ } out := make([]PackageView, 0, len(pkgs)) for _, p := range pkgs { view := PackageView{ ID: p.ID, Name: p.Name, Contract: p.Contract, Group: string(store.GroupOf(p.Contract)), DisplayName: p.DisplayName, Description: p.Description, Managed: p.Managed, UpdatePolicy: p.UpdatePolicy, AcceptedAt: p.AcceptedAt, Versions: []VersionView{}, } for _, v := range versions { if v.PackageID != p.ID { continue } vv := versionView(v, p, running) if vv.Default { view.DefaultVersion = v.Version } view.Versions = append(view.Versions, vv) } out = append(out, view) } return httpapi.OK(out), nil } // installationRequest is the configuration of one installation. type installationRequest struct { Settings map[string]string `json:"settings,omitzero"` Egress []string `json:"egress,omitzero" doc:"Every host the extension may reach. An empty list grants no egress"` Env []string `json:"env,omitzero" doc:"Host environment variables the extension may see; the instance's installations of the package bound them"` Credentials map[string]string `json:"credentials,omitzero" doc:"Each credential slot and the credential, by name, that fills it"` // Args, URL and Tools configure an MCP server. Args []string `json:"args,omitzero"` URL string `json:"url,omitzero"` Tools []ToolDecl `json:"tools,omitzero"` Enabled bool `json:"enabled"` // Version pins the installation to one accepted version of its package; // empty runs the package's default version. Version string `json:"version,omitzero" doc:"An accepted version of the package to run. Default: the package's default version"` } type createInstallationInput struct { Body struct { Package string `json:"package" doc:"The accepted package to install"` Name string `json:"name,omitzero" doc:"What a binding calls the installation. Default: the package's name"` Scope string `json:"scope" enum:"instance,org,person" doc:"Who owns the installation: the instance, the caller's organisation or the caller"` installationRequest } } type updateInstallationInput struct { ID uuid.UUID `path:"id"` Body installationRequest } func (m *Module) createInstallation(ctx context.Context, in *createInstallationInput) (*httpapi.Reply[ExtensionView], error) { m.pkgMu.Lock() defer m.pkgMu.Unlock() req := in.Body auth, err := authorityOf(ctx) if err != nil { return nil, err } owner, err := auth.ownerAt(req.Scope) if err != nil { return nil, err } pkgs, installed, err := m.packagesAndInstallations(ctx) if err != nil { return nil, err } if !slices.ContainsFunc(pkgs, func(p store.Package) bool { return p.Name == req.Package }) { return nil, errNoPackage(req.Package) } pv, err := m.packageNamed(ctx, req.Package) if err != nil { return nil, err } pkg := pv.pkg def, ok := pv.defaultVersion() if !ok { return nil, huma.NewError(http.StatusConflict, pkg.Name+" has no default version") } name := cmp.Or(req.Name, pkg.Name) if !validName.MatchString(name) { return nil, huma.NewError(http.StatusBadRequest, "an installation needs a lowercase name") } if slices.ContainsFunc(installed, func(a store.Installed) bool { return a.Owner() == owner && a.Name == name }) { return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("%s already has an installation named %s", owner.Scope, name)) } a := withVersion(store.Installed{ ID: uuid.New(), PackageID: pkg.ID, Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID, Name: name, PackageName: pkg.Name, Contract: pkg.Contract, Managed: pkg.Managed, DisplayName: pkg.DisplayName, Description: pkg.Description, }, def, false) if a, err = pinVersion(a, pv, req.Version); err != nil { return nil, err } return m.saveInstallation(ctx, auth, a, req.installationRequest, installed, false, store.Installed{}) } func (m *Module) updateInstallation(ctx context.Context, in *updateInstallationInput) (*httpapi.Reply[ExtensionView], error) { m.pkgMu.Lock() defer m.pkgMu.Unlock() previous, auth, err := m.installationFor(ctx, in.ID, true) if err != nil { return nil, err } installed, err := m.store.List(ctx) if err != nil { return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations") } pv, err := m.packageNamed(ctx, previous.PackageName) if err != nil { return nil, err } def, ok := pv.defaultVersion() if !ok { return nil, huma.NewError(http.StatusConflict, previous.PackageName+" has no default version") } next, err := pinVersion(withVersion(previous, def, false), pv, in.Body.Version) if err != nil { return nil, err } return m.saveInstallation(ctx, auth, next, in.Body, installed, true, previous) } // pinVersion points a at the named version of its package, or leaves it on the // default version when version is empty. func pinVersion(a store.Installed, pv packageVersions, version string) (store.Installed, error) { if version == "" { return a, nil } v, ok := pv.version(version) if !ok { return store.Installed{}, errNoVersion(pv.pkg.Name, version) } return withVersion(a, v, true), nil } // saveInstallation applies req to a, checks it, starts it and stores it. func (m *Module) saveInstallation(ctx context.Context, auth authority, a store.Installed, req installationRequest, installed []store.Installed, hadPrevious bool, previous store.Installed) (*httpapi.Reply[ExtensionView], error) { if err := checkAccepted(a, req); err != nil { return nil, err } settings, err := json.Marshal(req.Settings, json.FormatNilMapAsNull(false)) if err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } slots, err := json.Marshal(req.Credentials, json.FormatNilMapAsNull(false)) if err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } tools := jsontext.Value(`[]`) if a.Contract == store.ContractMCP { check := mcpRequest{URL: req.URL, Path: a.Path, SHA256: a.SHA256, Args: req.Args, Settings: req.Settings, Tools: req.Tools} if err := check.check(); err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } if tools, err = json.Marshal(req.Tools); err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } } else if req.URL != "" || len(req.Args) > 0 || len(req.Tools) > 0 { return nil, huma.NewError(http.StatusBadRequest, "only an MCP server takes a url, arguments or tools") } if err := checkGrants(a, req, installed); err != nil { return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error()) } a.Settings, a.Credentials, a.Tools = settings, slots, tools a.Egress, a.Env, a.Args, a.URL, a.Enabled = req.Egress, req.Env, req.Args, req.URL, req.Enabled persist := func(ctx context.Context, in store.Installed, caps jsontext.Value) (store.Installed, error) { return m.store.SaveInstallation(ctx, in, caps) } if err := m.commit(context.WithoutCancel(ctx), a, hadPrevious, previous, persist); err != nil { return nil, acceptError(err) } m.log.InfoContext(ctx, "installation saved", "audit", true, "action", "installation.save", "installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName) view, err := m.viewOf(a, auth.manages(a.Owner())) if err != nil { return nil, huma.NewError(http.StatusInternalServerError, err.Error()) } return httpapi.OK(view), nil } func (m *Module) packagesAndInstallations(ctx context.Context) ([]store.Package, []store.Installed, error) { pkgs, err := m.store.Packages(ctx) if err != nil { m.log.ErrorContext(ctx, "list packages", "error", err) return nil, nil, huma.NewError(http.StatusInternalServerError, "couldn't read the packages") } installed, err := m.store.List(ctx) if err != nil { m.log.ErrorContext(ctx, "list installations", "error", err) return nil, nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations") } return pkgs, installed, nil } // checkAccepted bounds an installation of a catalogue version by what the // instance accepted for that version: the version must be accepted, and the // installation may reach only accepted hosts, see only accepted environment // variables and fill only accepted credential slots. func checkAccepted(a store.Installed, req installationRequest) error { if !a.Managed { return nil } held, ok, err := grantsOf(a.Accepted) if err != nil { return huma.NewError(http.StatusInternalServerError, err.Error()) } if !ok { return huma.NewError(http.StatusConflict, fmt.Sprintf("the instance hasn't accepted %s %s", a.PackageName, a.Version)) } want := catalogue.Grants{Egress: req.Egress, Env: req.Env, Credentials: slices.Collect(maps.Keys(req.Credentials))}.Normalised() if !held.Covers(want) { return huma.NewError(http.StatusUnprocessableEntity, fmt.Sprintf("%s %s isn't granted %v", a.PackageName, a.Version, held.Added(want))) } return nil } // checkGrants limits organisation and personal installations to environment // variables granted to the package at instance scope. Only an instance // installation can request unrestricted egress. func checkGrants(a store.Installed, req installationRequest, installed []store.Installed) error { if a.Scope == store.ScopeInstance { return nil } if slices.Contains(req.Egress, "*") || slices.Contains(req.Egress, "**") { return fmt.Errorf("only the instance can grant unrestricted egress") } var passed map[string]bool for _, other := range installed { if other.PackageID != a.PackageID || other.Scope != store.ScopeInstance { continue } if passed == nil { passed = map[string]bool{} } for _, name := range other.Env { passed[name] = true } } for _, name := range req.Env { if !passed[name] { return fmt.Errorf("environment variable %s isn't passed on by an instance installation of %s", name, a.PackageName) } } return nil } type overrideInput struct { ID uuid.UUID `path:"id"` Body struct { Scope string `json:"scope" enum:"org,person" doc:"Switch it off for the caller's organisation or for the caller"` Off bool `json:"off" doc:"True switches the inherited installation off; false restores it"` } } // putOverride switches an installation the caller inherits off or on. It never // changes the installation: it is the caller's organisation or the caller that // stops using it. func (m *Module) putOverride(ctx context.Context, in *overrideInput) (*httpapi.Reply[packageState], error) { m.pkgMu.Lock() defer m.pkgMu.Unlock() auth, err := authorityOf(ctx) if err != nil { return nil, err } a, _, err := m.installationFor(ctx, in.ID, false) if err != nil { return nil, err } owner, err := auth.ownerAt(in.Body.Scope) if err != nil { return nil, err } if owner.Scope == store.ScopeInstance || !inherits(owner, a.Owner()) { return nil, huma.NewError(http.StatusUnprocessableEntity, "only an installation owned by a broader scope can be switched off") } if in.Body.Off && a.Contract == store.ContractGuard && !m.advisoryGuard(a.ID.String()) { return nil, huma.NewError(http.StatusForbidden, "an inherited enforcing guard can't be switched off") } o := store.Override{InstallationID: a.ID, Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID} if err := m.store.SetOverride(ctx, o, in.Body.Off, governance.CallerID(ctx)); err != nil { m.log.ErrorContext(ctx, "set installation override", "installation", a.Name, "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't change the installation") } if _, err := m.refresh(ctx); err != nil { m.log.ErrorContext(ctx, "read installations", "error", err) } state := "running" if in.Body.Off { state = "removed" } return httpapi.OK(packageState{Name: a.Name, State: state}), nil } // inherits reports whether a scope owning by inheritor reaches installations // that owner owns from a broader scope: an organisation reaches the instance's, // and a person the instance's and their organisation's. func inherits(inheritor, owner store.Owner) bool { switch inheritor.Scope { case store.ScopeOrg: return owner.Scope == store.ScopeInstance case store.ScopePerson: return owner.Scope == store.ScopeInstance || owner.Scope == store.ScopeOrg } return false }