Files
archie/modules/connectors/catalogue.go
T

218 lines
9.7 KiB
Go

package connectors
import (
"context"
"errors"
"fmt"
"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"
"github.com/samcharles93/archie-core/modules/governance"
)
// errNoSource means no catalogue source is set.
var errNoSource = errors.New("no catalogue source is set")
// sourceStore is where the catalogue source and its freshness mark are kept.
type sourceStore interface {
CatalogueSource(ctx context.Context, orgID string) (store.Source, bool, error)
PutCatalogueSource(ctx context.Context, src store.Source) error
AdvanceCatalogue(ctx context.Context, orgID string, issuedAt time.Time) (bool, error)
}
// catalogueContracts are the contracts a catalogue entry may serve. An MCP
// server is configuration, not a package.
var catalogueContracts = []string{store.ContractConnector, store.ContractSecretEngine, store.ContractGuard}
// CatalogueSource is where the catalogue is read from and the key that signs it.
type CatalogueSource struct {
Location string `json:"location" doc:"An https URL or an absolute path to the catalogue; its signature is beside it with .sig added"`
PublicKey string `json:"public_key" doc:"The base64 Ed25519 public key the catalogue is signed with"`
// Newest is the issue time of the newest catalogue accepted from it.
Newest *time.Time `json:"newest,omitempty" readOnly:"true"`
}
// SourceView is the catalogue source as the dashboard reads it.
type SourceView struct {
Configured bool `json:"configured"`
Source *CatalogueSource `json:"source,omitempty"`
}
func (m *Module) getCatalogueSource(ctx context.Context, _ *struct{}) (*httpapi.Reply[SourceView], error) {
src, ok, err := m.sources.CatalogueSource(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "read the catalogue source", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the catalogue source")
}
if !ok {
return httpapi.OK(SourceView{}), nil
}
view := CatalogueSource{Location: src.Location, PublicKey: src.PublicKey}
if src.Newest.Valid {
view.Newest = &src.Newest.Time
}
return httpapi.OK(SourceView{Configured: true, Source: &view}), nil
}
func (m *Module) putCatalogueSource(ctx context.Context, in *struct{ Body CatalogueSource }) (*httpapi.Reply[SourceView], error) {
req := in.Body
if err := catalogue.CheckLocation(req.Location); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if _, err := catalogue.ParseKey(req.PublicKey); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if err := m.sources.PutCatalogueSource(ctx, store.Source{OrgID: m.orgID, Location: req.Location, PublicKey: req.PublicKey}); err != nil {
m.log.ErrorContext(ctx, "save the catalogue source", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the catalogue source")
}
m.log.InfoContext(ctx, "catalogue source set", "audit", true, "action", "catalogue.source")
return m.getCatalogueSource(ctx, nil)
}
// readCatalogue reads the catalogue from the source and verifies it: the
// signature, then freshness, so an older catalogue is refused only once it is
// known to be genuine.
func (m *Module) readCatalogue(ctx context.Context) (catalogue.Document, string, error) {
src, ok, err := m.sources.CatalogueSource(ctx, m.orgID)
if err != nil {
return catalogue.Document{}, "", err
}
if !ok {
return catalogue.Document{}, "", errNoSource
}
key, err := catalogue.ParseKey(src.PublicKey)
if err != nil {
return catalogue.Document{}, "", err
}
body, sig, err := m.fetcher.Read(ctx, src.Location)
if err != nil {
return catalogue.Document{}, "", err
}
doc, err := catalogue.Verify(body, sig, key)
if err != nil {
return catalogue.Document{}, "", err
}
if fresh, err := m.sources.AdvanceCatalogue(ctx, m.orgID, doc.IssuedAt); err != nil {
return catalogue.Document{}, "", err
} else if !fresh {
return catalogue.Document{}, "", catalogue.ErrStale
}
return doc, src.Location, nil
}
// CatalogueEntry is one extension the catalogue offers and whether it is
// installed.
type CatalogueEntry struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Contract string `json:"contract"`
Group string `json:"group" enum:"platform,integration,agent"`
Version string `json:"version"`
Digest string `json:"digest"`
Grants catalogue.Grants `json:"grants"`
Installed bool `json:"installed"`
// InstalledVersion and UpdateAvailable describe an installed entry: the
// catalogue now pins a different digest than the one installed.
InstalledVersion string `json:"installed_version,omitempty"`
UpdateAvailable bool `json:"update_available"`
}
func (m *Module) listCatalogue(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]CatalogueEntry], error) {
doc, _, err := m.readCatalogue(ctx)
if err != nil {
return nil, catalogueError(err)
}
accepted, err := m.store.List(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list accepted packages", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
}
out := make([]CatalogueEntry, 0, len(doc.Extensions))
for _, e := range doc.Extensions {
entry := CatalogueEntry{
Name: e.Name, DisplayName: e.DisplayName, Description: e.Description, Contract: e.Contract,
Group: string(store.GroupOf(e.Contract)), Version: e.Version, Digest: e.Digest, Grants: e.Grants,
}
if i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == e.Name }); i >= 0 {
entry.Installed = true
if rec, ok, err := packageOf(accepted[i]); err == nil && ok {
entry.InstalledVersion = rec.State.Current.Version
entry.UpdateAvailable = rec.State.Current.Digest != e.Digest
}
}
out = append(out, entry)
}
return httpapi.OK(out), nil
}
// catalogueError reports why the catalogue couldn't be used. A catalogue that
// can't be fetched or verified is a bad gateway, never an empty list.
func catalogueError(err error) error {
switch {
case errors.Is(err, errNoSource):
return huma.NewError(http.StatusNotFound, err.Error())
case errors.Is(err, catalogue.ErrBadSignature), errors.Is(err, catalogue.ErrStale):
return huma.NewError(http.StatusBadGateway, err.Error())
default:
return huma.NewError(http.StatusBadGateway, fmt.Sprintf("catalogue unavailable: %v", err))
}
}
func (m *Module) registerCatalogue(api huma.API) {
tags := []string{"Extension catalogue"}
read := httpapi.AdminAuthorized(governance.ActionRead, governance.KindConnector)
write := httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindConnector)
httpapi.Register(api, read, huma.Operation{
OperationID: "get-catalogue-source", Method: http.MethodGet, Path: "/api/extensions/catalogue-source",
Summary: "Get where the extension catalogue is read from", Tags: tags,
}, m.getCatalogueSource)
httpapi.Register(api, write, huma.Operation{
OperationID: "put-catalogue-source", Method: http.MethodPut, Path: "/api/extensions/catalogue-source",
Summary: "Set where the extension catalogue is read from and the key that signs it", Tags: tags,
}, m.putCatalogueSource)
httpapi.Register(api, read, huma.Operation{
OperationID: "list-catalogue", Method: http.MethodGet, Path: "/api/extensions/catalogue",
Summary: "List the extensions the signed catalogue offers", Tags: tags,
}, m.listCatalogue)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindConnector), huma.Operation{
OperationID: "install-extension", Method: http.MethodPost, Path: "/api/extensions/catalogue/{name}/install",
Summary: "Fetch an extension at the digest the catalogue pins and install it, not yet accepted", Tags: tags,
}, m.install)
httpapi.Register(api, write, huma.Operation{
OperationID: "accept-extension-grants", Method: http.MethodPost, Path: "/api/extensions/{name}/accept",
Summary: "Accept the grants an installed extension may use, and its settings", Tags: tags,
}, m.acceptGrants)
httpapi.Register(api, write, huma.Operation{
OperationID: "update-extension", Method: http.MethodPost, Path: "/api/extensions/{name}/update",
Summary: "Move an extension to the digest the catalogue now pins", Tags: tags,
}, m.updateExtension)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionApprove, governance.KindConnector), huma.Operation{
OperationID: "approve-extension-update", Method: http.MethodPost, Path: "/api/extensions/{name}/approve-update",
Summary: "Apply the pending update and accept the grants it declares", Tags: tags,
}, m.approveUpdate)
httpapi.Register(api, write, huma.Operation{
OperationID: "rollback-extension", Method: http.MethodPost, Path: "/api/extensions/{name}/rollback",
Summary: "Restore the previous version with the grants accepted for it", Tags: tags,
}, m.rollback)
httpapi.Register(api, write, huma.Operation{
OperationID: "put-extension-update-policy", Method: http.MethodPut, Path: "/api/extensions/{name}/update-policy",
Summary: "Set whether an extension follows the catalogue on its own", Tags: tags,
}, m.setPolicy)
httpapi.Register(api, write, huma.Operation{
OperationID: "put-extension-enabled", Method: http.MethodPut, Path: "/api/extensions/{name}/enabled",
Summary: "Start or stop an accepted extension", Tags: tags,
}, m.setEnabled)
httpapi.Register(api, write, huma.Operation{
OperationID: "put-extension-settings", Method: http.MethodPut, Path: "/api/extensions/{name}/settings",
Summary: "Save an installed extension's settings and restart it", Tags: tags,
}, m.putExtensionSettings)
}