Files
archie/modules/connectors/catalogue.go
T
sam c538017523 fix(connectors): verify the default catalogue and roll back failed updates (#2119)
Adapt OCI reads from internal/infrastructure/signedoci and internal/infrastructure/storepkg. Keep the legacy readers while their callers still use them.
2026-11-27 02:19:21 +11:00

250 lines
10 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"
)
const (
archipelagoLocation = "git.catlow.cloud/sam/archipelago/catalogue"
archipelagoKey = "PLouShOzvRqy1QbYaJplaM41/ulgKFN8ZQ7g1rI02Fc=" //nolint:gosec // public Ed25519 trust root
)
// sourceStore is where the catalogue source and its freshness mark are kept.
type sourceStore interface {
CatalogueSource(ctx context.Context) (store.Source, error)
PutCatalogueSource(ctx context.Context, src store.Source) error
AdvanceCatalogue(ctx context.Context, generation int64, issuedAt time.Time) (bool, error)
}
type catalogueSnapshot struct {
location string
generation int64
issuedAt time.Time
}
func effectiveSource(src store.Source) store.Source {
if src.Location == "" {
src.Location, src.PublicKey = archipelagoLocation, archipelagoKey
}
return src
}
// 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 OCI repository, an HTTPS URL or an absolute path. URL and file sources use a detached .sig file."`
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"`
Default bool `json:"default"`
Source *CatalogueSource `json:"source,omitempty"`
}
func (m *Module) getCatalogueSource(ctx context.Context, _ *struct{}) (*httpapi.Reply[SourceView], error) {
src, err := m.sources.CatalogueSource(ctx)
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")
}
isDefault := src.Location == ""
src = effectiveSource(src)
view := CatalogueSource{Location: src.Location, PublicKey: src.PublicKey}
if src.Newest.Valid {
view.Newest = &src.Newest.Time
}
return httpapi.OK(SourceView{Configured: true, Default: isDefault, Source: &view}), nil
}
func (m *Module) putCatalogueSource(ctx context.Context, in *struct{ Body CatalogueSource }) (*httpapi.Reply[SourceView], error) {
req := in.Body
if err := catalogue.CheckSource(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 req.Location == archipelagoLocation && req.PublicKey == archipelagoKey {
return m.resetCatalogueSource(ctx, nil)
}
return m.saveCatalogueSource(ctx, store.Source{Location: req.Location, PublicKey: req.PublicKey})
}
func (m *Module) resetCatalogueSource(ctx context.Context, _ *struct{}) (*httpapi.Reply[SourceView], error) {
return m.saveCatalogueSource(ctx, store.Source{})
}
func (m *Module) saveCatalogueSource(ctx context.Context, src store.Source) (*httpapi.Reply[SourceView], error) {
if err := m.sources.PutCatalogueSource(ctx, src); 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, catalogueSnapshot, error) {
src, err := m.sources.CatalogueSource(ctx)
if err != nil {
return catalogue.Document{}, catalogueSnapshot{}, err
}
src = effectiveSource(src)
key, err := catalogue.ParseKey(src.PublicKey)
if err != nil {
return catalogue.Document{}, catalogueSnapshot{}, err
}
doc, err := m.fetcher.Read(ctx, src.Location, key)
if err != nil {
return catalogue.Document{}, catalogueSnapshot{}, err
}
if fresh, err := m.sources.AdvanceCatalogue(ctx, src.Generation, doc.IssuedAt); err != nil {
return catalogue.Document{}, catalogueSnapshot{}, err
} else if !fresh {
return catalogue.Document{}, catalogueSnapshot{}, catalogue.ErrStale
}
return doc, catalogueSnapshot{src.Location, src.Generation, doc.IssuedAt}, nil
}
// CatalogueEntry is one extension the catalogue offers, with its versions and
// the version the instance runs by default when 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"`
Latest string `json:"latest"`
Versions []CatalogueVersion `json:"versions"`
Installed bool `json:"installed"`
// DefaultVersion is the version installations run unless they pin one;
// UpdateAvailable says the catalogue offers a newer one.
DefaultVersion string `json:"default_version,omitempty"`
UpdateAvailable bool `json:"update_available"`
}
// CatalogueVersion is one version the catalogue offers.
type CatalogueVersion struct {
Version string `json:"version"`
Digest string `json:"digest"`
Grants catalogue.Grants `json:"grants"`
Settings []Setting `json:"settings"`
// Registered says the instance has fetched this version.
Registered bool `json:"registered"`
}
func (m *Module) listCatalogue(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]CatalogueEntry], error) {
doc, _, err := m.readCatalogue(ctx)
if err != nil {
return nil, catalogueError(err)
}
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")
}
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")
}
out := make([]CatalogueEntry, 0, len(doc.Extensions))
for _, e := range doc.Extensions {
latest, _ := e.Latest()
entry := CatalogueEntry{
Name: e.Name, DisplayName: e.DisplayName, Description: e.Description, Contract: e.Contract,
Group: string(store.GroupOf(e.Contract)), Latest: latest.Version, Versions: make([]CatalogueVersion, 0, len(e.Versions)),
}
var registered map[string]bool
if i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == e.Name }); i >= 0 {
entry.Installed = true
registered = map[string]bool{}
for _, v := range versions {
if v.PackageID != pkgs[i].ID {
continue
}
registered[v.Version] = true
if v.ID == pkgs[i].DefaultVersion.UUID {
entry.DefaultVersion = v.Version
}
}
entry.UpdateAvailable = entry.DefaultVersion != "" && catalogue.Newer(latest.Version, entry.DefaultVersion)
}
for _, v := range e.Versions {
entry.Versions = append(entry.Versions, CatalogueVersion{
Version: v.Version, Digest: v.Digest, Grants: v.Grants, Settings: catalogueSettings(v.Settings),
Registered: registered[v.Version],
})
}
out = append(out, entry)
}
return httpapi.OK(out), nil
}
// catalogueSettings converts the settings a catalogue version declares.
func catalogueSettings(in []catalogue.Setting) []Setting {
out := make([]Setting, 0, len(in))
for _, s := range in {
out = append(out, Setting(s))
}
return out
}
// 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, 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, write, huma.Operation{
OperationID: "reset-catalogue-source", Method: http.MethodDelete, Path: "/api/extensions/catalogue-source",
Summary: "Reset the extension catalogue to Archipelago", Tags: tags,
}, m.resetCatalogueSource)
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 a catalogue version, accept its grants, and create and start an installation", Tags: tags,
}, m.install)
}