package connectors import ( "cmp" "context" "encoding/json/jsontext" json "encoding/json/v2" "fmt" "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/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. 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"` Version string `json:"version,omitempty"` Digest string `json:"digest"` // Managed says the package was installed from the catalogue. A managed // package can be installed below the instance only once its grants are // accepted. Managed bool `json:"managed"` Installed bool `json:"installed" doc:"Whether the instance accepted the package's grants, so an organisation or a person can install it"` AcceptedAt time.Time `json:"accepted_at"` } func (m *Module) listPackages(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]PackageView], error) { pkgs, err := m.store.Packages(ctx) if err != nil { m.log.ErrorContext(ctx, "list packages", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the packages") } 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)), Digest: p.SHA256, Installed: true, AcceptedAt: p.AcceptedAt, } if rec, ok, err := packageOf(store.Installed{Manifest: p.Manifest, Name: p.Name}); err != nil { return nil, huma.NewError(http.StatusInternalServerError, err.Error()) } else if ok { view.Managed = true view.DisplayName, view.Description, view.Version = rec.DisplayName, rec.Description, rec.State.Current.Version view.Installed = rec.State.Accepted != nil } 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 installation below the instance must name them, unless the package runs unconfined"` 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"` } 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) { 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 } i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == req.Package }) if i < 0 { return nil, errNoPackage(req.Package) } pkg := pkgs[i] 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 := 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, Path: pkg.Path, SHA256: pkg.SHA256, Manifest: pkg.Manifest, Effects: pkg.Effects, Capabilities: pkg.Capabilities, } 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) { previous, auth, err := m.installationFor(ctx, in.ID, true) if err != nil { return nil, err } if previous.Scope == store.ScopeInstance && len(previous.Manifest) > 0 { return nil, huma.NewError(http.StatusConflict, previous.Name+" is installed from the catalogue; change it through its extension page") } installed, err := m.store.List(ctx) if err != nil { return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the installations") } return m.saveInstallation(ctx, auth, previous, in.Body, installed, true, previous) } // 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 rec, managed, err := packageOf(a); err != nil { return nil, huma.NewError(http.StatusInternalServerError, err.Error()) } else if managed && rec.State.Accepted == nil { return nil, huma.NewError(http.StatusConflict, "the instance hasn't accepted the grants of "+a.PackageName) } 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 } // checkGrants bounds what an organisation or a person may grant an extension. // The instance's installations of a package are what an administrator // accepted, so an installation below them may see only the environment // variables those pass on, and must name the hosts it reaches unless an // administrator ran the package unconfined. A host is the installer's own to // name, since each installation reaches a different system. func checkGrants(a store.Installed, req installationRequest, installed []store.Installed) error { if a.Scope == store.ScopeInstance { return nil } var passed map[string]bool unconfined := false 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 } unconfined = unconfined || len(other.Egress) == 0 } 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) } } if len(req.Egress) == 0 && !unconfined && a.Contract != store.ContractMCP { return fmt.Errorf("name the hosts %s reaches", 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) { 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") } 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 }