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.
This commit is contained in:
sam committed 2026-11-27 02:19:21 +11:00
1 parent 2ea0062bef
commit c538017523
26 files changed
+844 -202

No files matched your search

+23 -2
View File
@@ -523,7 +523,7 @@ components:
additionalProperties: false
properties:
location:
description: An https URL or an absolute path to the catalogue; its signature is beside it with .sig added
description: An OCI repository, an HTTPS URL or an absolute path. URL and file sources use a detached .sig file.
type: string
newest:
format: date-time
@@ -920,7 +920,7 @@ components:
description: Each credential slot and the credential, by name, that fills it
type: object
egress:
description: Every host the extension may reach. An installation below the instance must name them, unless the package runs unconfined
description: Every host the extension may reach. An empty list grants no egress
items:
type: string
type:
@@ -1115,10 +1115,13 @@ components:
properties:
configured:
type: boolean
default:
type: boolean
source:
$ref: "#/components/schemas/ConnectorsCatalogueSource"
required:
- configured
- default
type: object
ConnectorsTarget:
additionalProperties: false
@@ -6604,6 +6607,24 @@ paths:
tags:
- Extension catalogue
/api/extensions/catalogue-source:
delete:
operationId: reset-catalogue-source
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/ConnectorsSourceView"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Reset the extension catalogue to Archipelago
tags:
- Extension catalogue
get:
operationId: get-catalogue-source
responses:
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE connectors.catalogue_source
ADD COLUMN generation bigint NOT NULL DEFAULT 0,
ADD COLUMN default_newest_issued_at timestamptz;
ALTER TABLE connectors.package_versions ADD COLUMN catalogue_digest text NOT NULL DEFAULT '';
UPDATE connectors.packages SET update_policy = 'manual' WHERE contract = 'guard';
-- +goose Down
ALTER TABLE connectors.package_versions DROP COLUMN catalogue_digest;
ALTER TABLE connectors.catalogue_source DROP COLUMN default_newest_issued_at, DROP COLUMN generation;
+5 -1
View File
@@ -143,6 +143,8 @@ type packageState struct {
// instance installation of the same name, so the extension runs for every
// organisation.
func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string) (*httpapi.Reply[packageState], error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
name, req := in.Name, in.Body
if !validName.MatchString(name) || req.Path == "" || req.SHA256 == "" {
return nil, huma.NewError(http.StatusBadRequest, "a connector needs a lowercase name, a path and a sha256")
@@ -177,7 +179,9 @@ func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string
return nil, acceptError(err)
}
if found && (previous.Path != a.Path || previous.SHA256 != a.SHA256) {
m.relaunchFollowers(context.WithoutCancel(ctx), a.PackageID, a.ID)
if err := m.relaunchFollowers(context.WithoutCancel(ctx), a.PackageID, a.ID); err != nil {
return nil, m.packageError(ctx, err)
}
}
return httpapi.OK(packageState{Name: name, State: "running"}), nil
}
+53 -31
View File
@@ -16,14 +16,29 @@ import (
"github.com/samcharles93/archie-core/modules/governance"
)
// errNoSource means no catalogue source is set.
var errNoSource = errors.New("no catalogue source is set")
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, bool, error)
CatalogueSource(ctx context.Context) (store.Source, error)
PutCatalogueSource(ctx context.Context, src store.Source) error
AdvanceCatalogue(ctx context.Context, issuedAt time.Time) (bool, 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
@@ -32,7 +47,7 @@ var catalogueContracts = []string{store.ContractConnector, store.ContractSecretE
// 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"`
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"`
@@ -41,34 +56,45 @@ type CatalogueSource struct {
// 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, ok, err := m.sources.CatalogueSource(ctx)
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")
}
if !ok {
return httpapi.OK(SourceView{}), nil
}
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, Source: &view}), nil
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.CheckLocation(req.Location); err != nil {
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 err := m.sources.PutCatalogueSource(ctx, store.Source{Location: req.Location, PublicKey: req.PublicKey}); err != nil {
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")
}
@@ -79,32 +105,26 @@ func (m *Module) putCatalogueSource(ctx context.Context, in *struct{ Body Catalo
// 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)
func (m *Module) readCatalogue(ctx context.Context) (catalogue.Document, catalogueSnapshot, error) {
src, err := m.sources.CatalogueSource(ctx)
if err != nil {
return catalogue.Document{}, "", err
}
if !ok {
return catalogue.Document{}, "", errNoSource
return catalogue.Document{}, catalogueSnapshot{}, err
}
src = effectiveSource(src)
key, err := catalogue.ParseKey(src.PublicKey)
if err != nil {
return catalogue.Document{}, "", err
return catalogue.Document{}, catalogueSnapshot{}, err
}
body, sig, err := m.fetcher.Read(ctx, src.Location)
doc, err := m.fetcher.Read(ctx, src.Location, key)
if err != nil {
return catalogue.Document{}, "", err
return catalogue.Document{}, catalogueSnapshot{}, err
}
doc, err := catalogue.Verify(body, sig, key)
if err != nil {
return catalogue.Document{}, "", err
}
if fresh, err := m.sources.AdvanceCatalogue(ctx, doc.IssuedAt); err != nil {
return catalogue.Document{}, "", 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{}, "", catalogue.ErrStale
return catalogue.Document{}, catalogueSnapshot{}, catalogue.ErrStale
}
return doc, src.Location, nil
return doc, catalogueSnapshot{src.Location, src.Generation, doc.IssuedAt}, nil
}
// CatalogueEntry is one extension the catalogue offers, with its versions and
@@ -195,8 +215,6 @@ func catalogueSettings(in []catalogue.Setting) []Setting {
// 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:
@@ -216,6 +234,10 @@ func (m *Module) registerCatalogue(api huma.API) {
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,
+2
View File
@@ -452,6 +452,8 @@ func uses(installOwner, credOwner store.Owner) bool {
// relaunchUsers restarts every enabled installation that may resolve the
// credential and has a slot naming it, and returns their names.
func (m *Module) relaunchUsers(ctx context.Context, owner store.Owner, credential string) ([]string, error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
accepted, err := m.store.List(ctx)
if err != nil {
return nil, err
+2
View File
@@ -24,6 +24,8 @@ func (m *Module) listExtensions(ctx context.Context, _ *struct{}) (*httpapi.Repl
// first. The contract is read from the package's instance installation and
// handed to the same removal the per-kind routes use.
func (m *Module) removePackage(ctx context.Context, in *packageNameInput) (*httpapi.Reply[packageState], error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
installed, err := m.store.List(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list installations", "error", err)
+3
View File
@@ -126,6 +126,9 @@ func (g *Guard) Settings() map[string]string { return g.values }
// Judge asks the guard about one action. ctx bounds the wait.
func (g *Guard) Judge(ctx context.Context, r GuardRequest) (GuardAnswer, error) {
if g.client == nil {
return GuardAnswer{}, fmt.Errorf("guard %q isn't running", g.name)
}
evidence := make([]*gpb.Evidence, 0, len(r.Evidence))
for _, e := range r.Evidence {
evidence = append(evidence, &gpb.Evidence{Source: e.Source, Text: e.Text})
+14 -9
View File
@@ -102,7 +102,7 @@ func (m *Module) listPackages(ctx context.Context, _ *struct{}) (*httpapi.Reply[
// 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"`
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.
@@ -130,6 +130,8 @@ type updateInstallationInput struct {
}
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 {
@@ -173,6 +175,8 @@ func (m *Module) createInstallation(ctx context.Context, in *createInstallationI
}
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
@@ -294,15 +298,15 @@ func checkAccepted(a store.Installed, req installationRequest) error {
// 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.
// variables those pass on. Each installation names its own egress hosts.
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
unconfined := false
for _, other := range installed {
if other.PackageID != a.PackageID || other.Scope != store.ScopeInstance {
continue
@@ -313,16 +317,12 @@ func checkGrants(a store.Installed, req installationRequest, installed []store.I
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
}
@@ -338,6 +338,8 @@ type overrideInput struct {
// 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
@@ -353,6 +355,9 @@ func (m *Module) putOverride(ctx context.Context, in *overrideInput) (*httpapi.R
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)
@@ -73,7 +73,7 @@ func TestAcceptRefusesGrantsTheExtensionNeverDeclared(t *testing.T) {
{"fewer than declared are accepted", Grants{Egress: []string{"api.example.com"}}, nil},
{"an undeclared host is refused", Grants{Egress: []string{"elsewhere.example.com"}}, ErrBeyondDeclared},
{"an undeclared credential is refused", Grants{Credentials: []string{"other"}}, ErrBeyondDeclared},
{"the whole network is refused when hosts are declared", Grants{}, ErrBeyondDeclared},
{"no egress narrows a host grant", Grants{}, nil},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
@@ -40,6 +40,7 @@ type Version struct {
// the form before the extension first runs. The running extension's own
// declaration is what its settings are checked against.
Settings []Setting `json:"settings,omitzero"`
binary *ociBinary
}
// Setting is one value an operator enters for an extension to run. Its fields
@@ -171,17 +172,28 @@ func (e Entry) Normalised() (Entry, error) {
// base64 Ed25519 signature of exactly body's bytes. A catalogue without an
// issue time is refused: it could not be ordered against a replay.
func Verify(body, signature []byte, key ed25519.PublicKey) (Document, error) {
if len(key) != ed25519.PublicKeySize {
return Document{}, errors.New("no valid signing key")
}
sig, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(signature)))
if err != nil || !ed25519.Verify(key, body, sig) {
return Document{}, ErrBadSignature
if err := verifySignature(body, signature, key); err != nil {
return Document{}, err
}
var doc Document
if err := json.Unmarshal(body, &doc, json.RejectUnknownMembers(true)); err != nil {
return Document{}, fmt.Errorf("catalogue: %w", err)
}
return normaliseDocument(doc)
}
func verifySignature(body, signature []byte, key ed25519.PublicKey) error {
if len(key) != ed25519.PublicKeySize {
return errors.New("no valid signing key")
}
sig, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(signature)))
if err != nil || !ed25519.Verify(key, body, sig) {
return ErrBadSignature
}
return nil
}
func normaliseDocument(doc Document) (Document, error) {
if doc.IssuedAt.IsZero() {
return Document{}, errors.New("catalogue has no issue time")
}
+58 -13
View File
@@ -1,7 +1,9 @@
package catalogue
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/sha256"
"encoding/hex"
"errors"
@@ -40,9 +42,15 @@ func NewFetcher(dir string) *Fetcher {
return &Fetcher{Dir: dir, Client: &http.Client{Timeout: 5 * time.Minute}}
}
// CheckLocation refuses a location that is neither an https URL, a loopback
// http URL nor an absolute path.
func CheckLocation(loc string) error {
// CheckSource validates a catalogue source, which can also be an OCI repository.
func CheckSource(loc string) error {
if isOCI(loc) || checkLocation(loc) == nil {
return nil
}
return errors.New("use an OCI repository, an HTTPS URL or an absolute path")
}
func checkLocation(loc string) error {
if strings.HasPrefix(loc, "/") {
return nil
}
@@ -88,7 +96,7 @@ func Resolve(base, ref string) (string, error) {
}
func (f *Fetcher) open(ctx context.Context, loc string) (io.ReadCloser, error) {
if err := CheckLocation(loc); err != nil {
if err := checkLocation(loc); err != nil {
return nil, fmt.Errorf("%q: %w", loc, err)
}
if strings.HasPrefix(loc, "/") {
@@ -109,16 +117,21 @@ func (f *Fetcher) open(ctx context.Context, loc string) (io.ReadCloser, error) {
return resp.Body, nil
}
// Read returns a catalogue and its detached signature, which sits beside it
// at the same location with ".sig" added.
func (f *Fetcher) Read(ctx context.Context, loc string) (body, signature []byte, err error) {
if body, err = f.readAll(ctx, loc); err != nil {
return nil, nil, err
// Read verifies a catalogue from an OCI repository or a document with a
// detached signature.
func (f *Fetcher) Read(ctx context.Context, loc string, key ed25519.PublicKey) (Document, error) {
if isOCI(loc) {
return f.ReadOCI(ctx, loc, key)
}
if signature, err = f.readAll(ctx, loc+".sig"); err != nil {
return nil, nil, err
body, err := f.readAll(ctx, loc)
if err != nil {
return Document{}, err
}
return body, signature, nil
signature, err := f.readAll(ctx, loc+".sig")
if err != nil {
return Document{}, err
}
return Verify(body, signature, key)
}
func (f *Fetcher) readAll(ctx context.Context, loc string) ([]byte, error) {
@@ -137,6 +150,32 @@ func (f *Fetcher) readAll(ctx context.Context, loc string) ([]byte, error) {
return data, nil
}
// FetchVersion keeps the verified binary and returns its path and SHA-256.
// An OCI version pins the manifest, not the binary, so its binary has a
// separate digest for the host to check at launch.
func (f *Fetcher) FetchVersion(ctx context.Context, name, location string, v Version) (path, digest string, err error) {
if b := v.binary; b != nil {
layer, err := fetchLayer(ctx, b.repository, b.layer, 64<<20)
if err != nil {
return "", "", err
}
binary, err := readBinary(bytes.NewReader(layer), b.layer.MediaType, b.path)
if err != nil {
return "", "", err
}
sum := sha256.Sum256(binary)
digest := hex.EncodeToString(sum[:])
path, err := f.keep(bytes.NewReader(binary), name, digest)
return path, digest, err
}
loc, err := Resolve(location, v.Artifact)
if err != nil {
return "", "", err
}
path, err = f.Fetch(ctx, name, loc, v.Digest)
return path, v.Digest, err
}
// Fetch reads the artifact at loc and keeps it as an executable under Dir,
// named for the extension and its digest. Nothing is kept unless the bytes hash
// to digest, a hex SHA-256. It returns the path of the kept binary.
@@ -155,6 +194,12 @@ func (f *Fetcher) Fetch(ctx context.Context, name, loc, digest string) (string,
return "", err
}
defer func() { _ = src.Close() }()
return f.keep(src, name, want)
}
func (f *Fetcher) keep(src io.Reader, name, want string) (string, error) {
dir := filepath.Join(f.Dir, name, want)
final := filepath.Join(dir, name)
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
@@ -173,7 +218,7 @@ func (f *Fetcher) Fetch(ctx context.Context, name, loc, digest string) (string,
return "", err
}
if n > maxArtifact {
return "", fmt.Errorf("%s exceeds the size limit", loc)
return "", errors.New("artifact exceeds the size limit")
}
if hex.EncodeToString(h.Sum(nil)) != want {
return "", ErrDigestMismatch
@@ -14,8 +14,7 @@ import (
// environment variables it may see and the credential slots it is configured
// with. A catalogue entry declares them and an operator accepts them.
type Grants struct {
// Egress is every host the extension may reach. An empty list means the
// extension is not confined and uses the host's network.
// Egress is every host the extension may reach. An empty list grants no network access.
Egress []string `json:"egress"`
Env []string `json:"env"`
Credentials []string `json:"credentials"`
@@ -38,20 +37,9 @@ func tidy(in []string) []string {
return slices.Compact(out)
}
// Unrestricted reports whether the extension reaches the whole network.
func (g Grants) Unrestricted() bool { return len(g.Egress) == 0 }
// Covers reports whether every grant in want is one g holds. An extension
// that reaches the whole network holds more than any list of hosts, so it is
// covered only by g that also reaches the whole network.
// Covers reports whether every grant in want is one g holds.
func (g Grants) Covers(want Grants) bool {
if want.Unrestricted() && !g.Unrestricted() {
return false
}
if !want.Unrestricted() && !g.Unrestricted() && !subset(want.Egress, g.Egress) {
return false
}
return subset(want.Env, g.Env) && subset(want.Credentials, g.Credentials)
return subset(want.Egress, g.Egress) && subset(want.Env, g.Env) && subset(want.Credentials, g.Credentials)
}
func subset(want, have []string) bool {
@@ -63,22 +51,13 @@ func subset(want, have []string) bool {
return true
}
// Added returns what want asks for beyond g. Reaching the whole network is
// reported as the host "*".
// Added returns what want asks for beyond g.
func (g Grants) Added(want Grants) Grants {
out := Grants{
return Grants{
Egress: missing(want.Egress, g.Egress),
Env: missing(want.Env, g.Env),
Credentials: missing(want.Credentials, g.Credentials),
}
switch {
case want.Unrestricted() && !g.Unrestricted():
out.Egress = []string{"*"}
case want.Unrestricted(), g.Unrestricted():
out.Egress = []string{}
default:
out.Egress = missing(want.Egress, g.Egress)
}
return out
}
func missing(want, have []string) []string {
@@ -0,0 +1,280 @@
package catalogue
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/ed25519"
"crypto/sha256"
"encoding/hex"
json "encoding/json/v2"
"errors"
"fmt"
"io"
"net"
"strings"
"time"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"gopkg.in/yaml.v3"
"oras.land/oras-go/v2/registry"
"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
)
const (
catalogueSignature = "dev.archie.catalogue.signature.v1"
packageDescriptor = "dev.archie.package.v1"
maxManifestBytes = 256 << 10
)
type publishedPackage struct {
Name string `json:"name"`
Surface string `json:"surface"`
Version string `json:"version"`
Description string `json:"description"`
Reference string `json:"reference"`
Digest string `json:"digest"`
}
type packageMetadata struct {
APIVersion string `yaml:"apiVersion"`
DisplayName string `yaml:"displayName"`
Version string `yaml:"version"`
Grants Grants `yaml:"grants"`
Authority struct {
EgressHosts []string `yaml:"egressHosts"`
Env []string `yaml:"env"`
CredentialServices []string `yaml:"credentialServices"`
} `yaml:"authority"`
Settings []Setting `yaml:"settings"`
Contributions struct {
Extensions []struct {
Surface string `yaml:"surface"`
Path string `yaml:"path"`
} `yaml:"extensions"`
} `yaml:"contributes"`
Files []struct {
Path string `yaml:"path"`
Mode uint32 `yaml:"mode"`
} `yaml:"files"`
}
type ociBinary struct {
repository *remote.Repository
layer ocispec.Descriptor
path string
}
func isOCI(loc string) bool {
ref, err := registry.ParseReference(loc)
return err == nil && ref.Reference == "" && !strings.Contains(loc, "://")
}
func (f *Fetcher) repository(loc string) (*remote.Repository, error) {
if !isOCI(loc) {
return nil, fmt.Errorf("%q is not an OCI repository", loc)
}
r, err := remote.NewRepository(loc)
if err != nil {
return nil, err
}
host := r.Reference.Host()
if hostname, _, err := net.SplitHostPort(host); err == nil {
host = hostname
}
r.PlainHTTP = loopback(strings.Trim(host, "[]"))
r.Client = &auth.Client{Client: f.Client, Cache: auth.NewCache()}
return r, nil
}
// ReadOCI verifies the catalogue before fetching any package metadata. Every
// descriptor is then verified against the catalogue's immutable manifest pin.
func (f *Fetcher) ReadOCI(ctx context.Context, loc string, key ed25519.PublicKey) (Document, error) {
r, err := f.repository(loc)
if err != nil {
return Document{}, err
}
manifest, err := fetchManifest(ctx, r, "latest", "")
if err != nil {
return Document{}, err
}
body, err := fetchLayer(ctx, r, manifest.Layers[0], maxDocument)
if err != nil {
return Document{}, err
}
if err := verifySignature(body, []byte(manifest.Annotations[catalogueSignature]), key); err != nil {
return Document{}, err
}
var published struct {
IssuedAt time.Time `json:"issued_at"`
Packages []publishedPackage `json:"packages"`
}
if err := json.Unmarshal(body, &published, json.RejectUnknownMembers(true)); err != nil {
return Document{}, fmt.Errorf("catalogue: %w", err)
}
doc := Document{IssuedAt: published.IssuedAt}
if doc.IssuedAt.IsZero() {
return Document{}, errors.New("catalogue has no issue time")
}
for _, p := range published.Packages {
if contractOf(p.Surface) == "" {
continue
}
entry, err := f.readPackage(ctx, p)
if err != nil {
return Document{}, fmt.Errorf("catalogue package %s: %w", p.Name, err)
}
doc.Extensions = append(doc.Extensions, entry)
}
return normaliseDocument(doc)
}
func contractOf(surface string) string {
switch surface {
case "connectors":
return "connector"
case "guards":
return "guard"
case "secret-engines":
return "secretengine"
default:
return ""
}
}
func (f *Fetcher) readPackage(ctx context.Context, p publishedPackage) (Entry, error) {
if !strings.HasPrefix(p.Digest, "sha256:") {
return Entry{}, errors.New("package pin must be a SHA-256 digest")
}
if _, err := NormalDigest(p.Digest); err != nil {
return Entry{}, err
}
r, err := f.repository(p.Reference)
if err != nil {
return Entry{}, err
}
manifest, err := fetchManifest(ctx, r, p.Digest, p.Digest)
if err != nil {
return Entry{}, err
}
var meta packageMetadata
if err := yaml.Unmarshal([]byte(manifest.Annotations[packageDescriptor]), &meta); err != nil {
return Entry{}, err
}
contract := contractOf(p.Surface)
extensions := meta.Contributions.Extensions
if meta.APIVersion != packageDescriptor || meta.Version != p.Version || len(extensions) != 1 || extensions[0].Surface != contract {
return Entry{}, errors.New("descriptor does not match the published extension")
}
binary := extensions[0].Path
if binary != "bin/"+p.Name || !entryName.MatchString(p.Name) {
return Entry{}, errors.New("descriptor does not name the package binary")
}
for _, file := range meta.Files {
if file.Path == binary && file.Mode&0o100 != 0 {
return packageEntry(p, meta, &ociBinary{repository: r, layer: manifest.Layers[0], path: binary}), nil
}
}
return Entry{}, errors.New("descriptor does not list an executable package binary")
}
func packageEntry(p publishedPackage, meta packageMetadata, binary *ociBinary) Entry {
grants := Grants{
Egress: append(meta.Grants.Egress, meta.Authority.EgressHosts...),
Env: append(meta.Grants.Env, meta.Authority.Env...),
Credentials: append(meta.Grants.Credentials, meta.Authority.CredentialServices...),
}
return Entry{
Name: p.Name, DisplayName: meta.DisplayName, Description: p.Description, Contract: contractOf(p.Surface),
Versions: []Version{{Version: p.Version, Artifact: p.Reference, Digest: p.Digest, Grants: grants, Settings: meta.Settings, binary: binary}},
}
}
// fetchManifest and fetchLayer carry the bounded, digest-checked OCI reads
// used by the signed catalogue and its pinned packages.
func fetchManifest(ctx context.Context, r *remote.Repository, ref, pin string) (ocispec.Manifest, error) {
_, stream, err := r.FetchReference(ctx, ref)
if err != nil {
return ocispec.Manifest{}, fmt.Errorf("fetch %s@%s: %w", r.Reference.Repository, ref, err)
}
raw, err := readBounded(stream, maxManifestBytes)
if err != nil {
return ocispec.Manifest{}, err
}
if pin != "" && contentDigest(raw) != pin {
return ocispec.Manifest{}, errors.New("package manifest digest mismatch")
}
var manifest ocispec.Manifest
if err := json.Unmarshal(raw, &manifest); err != nil {
return ocispec.Manifest{}, err
}
if manifest.SchemaVersion != 2 || len(manifest.Layers) != 1 {
return ocispec.Manifest{}, errors.New("expected an OCI manifest with one layer")
}
return manifest, nil
}
func fetchLayer(ctx context.Context, r *remote.Repository, layer ocispec.Descriptor, limit int64) ([]byte, error) {
if layer.Size < 0 || layer.Size > limit {
return nil, errors.New("OCI layer exceeds the size limit")
}
stream, err := r.Fetch(ctx, layer)
if err != nil {
return nil, err
}
body, err := readBounded(stream, limit)
if err != nil {
return nil, err
}
if int64(len(body)) != layer.Size || contentDigest(body) != layer.Digest.String() {
return nil, errors.New("OCI layer digest or size mismatch")
}
return body, nil
}
func readBounded(stream io.ReadCloser, limit int64) ([]byte, error) {
defer func() { _ = stream.Close() }()
data, err := io.ReadAll(io.LimitReader(stream, limit+1))
if int64(len(data)) > limit {
return nil, errors.New("OCI content exceeds the size limit")
}
return data, err
}
func contentDigest(data []byte) string {
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:])
}
func readBinary(r io.Reader, mediaType, name string) ([]byte, error) {
switch mediaType {
case ocispec.MediaTypeImageLayer:
case ocispec.MediaTypeImageLayerGzip:
gz, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
defer func() { _ = gz.Close() }()
r = gz
default:
return nil, fmt.Errorf("unsupported package layer media type %q", mediaType)
}
tr := tar.NewReader(io.LimitReader(r, maxArtifact+1))
for {
h, err := tr.Next()
if errors.Is(err, io.EOF) {
return nil, errors.New("package layer does not contain its binary")
}
if err != nil {
return nil, err
}
if h.Name != name {
continue
}
if h.Typeflag != tar.TypeReg || h.Mode&0o100 == 0 || h.Size <= 0 || h.Size > maxArtifact {
return nil, errors.New("package layer does not contain a regular executable binary")
}
return io.ReadAll(tr)
}
}
@@ -0,0 +1,115 @@
package catalogue
import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
digest "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
// TestReadOCIChecksSignatureAndPackagePin ensures a registry can't substitute
// a different grants or settings descriptor for a signed catalogue entry.
func TestReadOCIChecksSignatureAndPackagePin(t *testing.T) {
key, signer, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatal(err)
}
const metadata = `apiVersion: dev.archie.package.v1
version: 1.0.0
settings:
- key: timezone
label: Time zone
grants:
egress: [example.test:443]
contributes:
extensions:
- surface: guard
path: bin/hours
files:
- path: bin/hours
mode: 493`
pkg := testManifest(t, []byte("example"), map[string]string{packageDescriptor: metadata})
pin := digest.FromBytes(pkg)
for _, tc := range []struct {
name, signature string
tampered bool
}{
{name: "verified metadata"},
{name: "unsigned catalogue", signature: "invalid"},
{name: "changed package", tampered: true},
} {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body := fmt.Appendf(nil, `{"issued_at":"2026-11-23T00:00:00Z","packages":[{"name":"hours","surface":"guards","version":"1.0.0","reference":"%s/guards-hours","digest":"%s"}]}`, r.Host, pin)
sig := tc.signature
if sig == "" {
sig = base64.StdEncoding.EncodeToString(ed25519.Sign(signer, body))
}
media := ocispec.MediaTypeImageManifest
var result []byte
switch r.URL.Path {
case "/v2/catalogue/manifests/latest":
result = testManifest(t, body, map[string]string{catalogueSignature: sig})
case "/v2/catalogue/blobs/" + digest.FromBytes(body).String():
media, result = "application/octet-stream", body
case "/v2/guards-hours/manifests/" + pin.String():
result = pkg
if tc.tampered {
result = append(append([]byte(nil), pkg...), ' ')
}
default:
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", media)
w.Header().Set("Content-Length", strconv.Itoa(len(result)))
w.Header().Set("Docker-Content-Digest", digest.FromBytes(result).String())
_, _ = w.Write(result)
}))
t.Cleanup(srv.Close)
f := NewFetcher(t.TempDir())
doc, err := f.Read(t.Context(), strings.TrimPrefix(srv.URL, "http://")+"/catalogue", key)
switch {
case tc.tampered:
if err == nil {
t.Fatal("accepted a different package from the digest requested")
}
case tc.signature != "":
if !errors.Is(err, ErrBadSignature) {
t.Fatalf("invalid catalogue signature: got %v, want ErrBadSignature", err)
}
default:
if err != nil {
t.Fatal(err)
}
entry, ok := doc.Entry("hours")
v, offered := entry.Latest()
if !ok || !offered || len(v.Settings) != 1 || v.Settings[0].Key != "timezone" || !v.Grants.Covers(Grants{Egress: []string{"example.test:443"}}) {
t.Fatalf("missing declared settings or grants: %+v", v)
}
}
})
}
}
func testManifest(t *testing.T, layer []byte, annotations map[string]string) []byte {
t.Helper()
data, err := json.Marshal(ocispec.Manifest{
SchemaVersion: 2, MediaType: ocispec.MediaTypeImageManifest,
Layers: []ocispec.Descriptor{{Digest: digest.FromBytes(layer), Size: int64(len(layer))}},
Annotations: annotations,
})
if err != nil {
t.Error(err)
}
return data
}
@@ -58,15 +58,6 @@ func confinedCommand(ctx context.Context, binary *os.File, args []string, socket
return cmd, nil
}
// openCommand runs the verified binary by its open descriptor with the host's
// network, for a package that declares no egress hosts.
func openCommand(ctx context.Context, binary *os.File) *exec.Cmd {
path := fmt.Sprintf("/proc/%d/fd/%d", os.Getpid(), binary.Fd())
cmd := exec.CommandContext(ctx, path) // the host-verified binary, by descriptor
cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
return cmd
}
// launch runs inside the namespace: loopback up, relay listening, then the
// child from descriptor 3 with every capability gone.
func launch(socket string, args []string) int {
@@ -75,12 +66,14 @@ func launch(socket string, args []string) int {
fmt.Fprintln(os.Stderr, "extension egress: loopback:", err)
return 1
}
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", proxyAddr)
if err != nil {
fmt.Fprintln(os.Stderr, "extension egress: relay:", err)
return 1
if socket != "" {
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", proxyAddr)
if err != nil {
fmt.Fprintln(os.Stderr, "extension egress: relay:", err)
return 1
}
go relay(ctx, ln, socket)
}
go relay(ctx, ln, socket)
if err := unix.Prctl(unix.PR_CAP_AMBIENT, unix.PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0); err != nil {
fmt.Fprintln(os.Stderr, "extension egress: drop capabilities:", err)
return 1
@@ -14,7 +14,3 @@ import (
func confinedCommand(context.Context, *os.File, []string, string) (*exec.Cmd, error) {
return nil, errors.New("extensions need Linux network namespaces to confine their egress")
}
func openCommand(ctx context.Context, binary *os.File) *exec.Cmd {
return exec.CommandContext(ctx, binary.Name()) // the host-verified binary
}
+4 -7
View File
@@ -43,9 +43,8 @@ type Spec struct {
// Env names the host environment variables the extension may see. PATH and
// HOME are always passed so a plugin can find the CLI it wraps.
Env []string
// Egress is the accepted egress host list. When it names hosts, the
// extension runs in its own network namespace and reaches only these,
// through a proxy; an empty list runs it on the host's network.
// Egress is the accepted host list. The extension can reach only these
// hosts through its proxy.
Egress []string
}
@@ -72,12 +71,10 @@ func (p *proc) kill() {
}
}
// command confines the extension to egress when the package declares hosts.
// A package that declares none opted out of confinement and gets the host's
// network, with no gate.
func command(ctx context.Context, binary *os.File, egress []string) (*exec.Cmd, *gate, error) {
if len(egress) == 0 {
return openCommand(ctx, binary), nil, nil
cmd, err := confinedCommand(ctx, binary, nil, "")
return cmd, nil, err
}
g, err := openGate(ctx, egress)
if err != nil {
@@ -11,11 +11,6 @@ import (
// Command returns the command that runs a verified stdio MCP server with args,
// in its own user and network namespace.
//
// An extension is confined only when its package names egress hosts; a stdio
// MCP server always is, because there is no contract behind it to hold it: the
// namespace and the allow-list are what limit it, and an acceptance that names
// no host leaves it able to reach nothing.
//
// env is added to the server's environment as given, for the settings and
// credentials its acceptance resolves. The returned release ends the server's
// egress gate and closes the verified binary.
+62 -32
View File
@@ -23,20 +23,25 @@ type Source struct {
Location string `db:"location"`
PublicKey string `db:"public_key"`
// Newest is the issue time of the newest catalogue accepted from it.
Newest sql.NullTime `db:"newest_issued_at"`
Newest sql.NullTime `db:"newest_issued_at"`
Generation int64 `db:"generation"`
}
// CatalogueSource returns the catalogue source; ok is false when none is set.
func (s *Store) CatalogueSource(ctx context.Context) (Source, bool, error) {
// CatalogueSource returns the override and the active source's freshness mark.
// An empty location selects the built-in source.
func (s *Store) CatalogueSource(ctx context.Context) (Source, error) {
var out Source
err := s.db.GetContext(ctx, &out, `SELECT location, public_key, newest_issued_at FROM connectors.catalogue_source`)
err := s.db.GetContext(ctx, &out, `
SELECT location, public_key, generation,
CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END AS newest_issued_at
FROM connectors.catalogue_source`)
if errors.Is(err, sql.ErrNoRows) {
return Source{}, false, nil
return Source{}, nil
}
if err != nil {
return Source{}, false, fmt.Errorf("read catalogue source: %w", err)
return Source{}, fmt.Errorf("read catalogue source: %w", err)
}
return out, true, nil
return out, nil
}
// PutCatalogueSource records the source. A different source starts a new
@@ -44,24 +49,35 @@ func (s *Store) CatalogueSource(ctx context.Context) (Source, bool, error) {
// changes.
func (s *Store) PutCatalogueSource(ctx context.Context, src Source) error {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO connectors.catalogue_source (location, public_key) VALUES ($1, $2)
INSERT INTO connectors.catalogue_source (location, public_key, generation) VALUES ($1, $2, 1)
ON CONFLICT (singleton) DO UPDATE
SET newest_issued_at = CASE WHEN connectors.catalogue_source.location = EXCLUDED.location
AND connectors.catalogue_source.public_key = EXCLUDED.public_key
THEN connectors.catalogue_source.newest_issued_at END,
location = EXCLUDED.location, public_key = EXCLUDED.public_key, updated_at = now()`,
location = EXCLUDED.location, public_key = EXCLUDED.public_key, updated_at = now(),
generation = connectors.catalogue_source.generation + 1`,
src.Location, src.PublicKey); err != nil {
return fmt.Errorf("put catalogue source: %w", err)
}
return nil
}
// AdvanceCatalogue records a catalogue issued at issuedAt as accepted and
// reports false when a newer one was accepted already. It never lowers the mark.
func (s *Store) AdvanceCatalogue(ctx context.Context, issuedAt time.Time) (bool, error) {
// AdvanceCatalogue records freshness only for the source that was read. The
// built-in source keeps its own mark when the operator selects an override.
func (s *Store) AdvanceCatalogue(ctx context.Context, generation int64, issuedAt time.Time) (bool, error) {
if generation == 0 {
if _, err := s.db.ExecContext(ctx, `INSERT INTO connectors.catalogue_source (location, public_key)
VALUES ('', '') ON CONFLICT (singleton) DO NOTHING`); err != nil {
return false, fmt.Errorf("initialise catalogue state: %w", err)
}
}
res, err := s.db.ExecContext(ctx, `
UPDATE connectors.catalogue_source SET newest_issued_at = $1
WHERE newest_issued_at IS NULL OR newest_issued_at <= $1`, issuedAt)
UPDATE connectors.catalogue_source
SET newest_issued_at = CASE WHEN location = '' THEN newest_issued_at ELSE $2 END,
default_newest_issued_at = CASE WHEN location = '' THEN $2 ELSE default_newest_issued_at END
WHERE generation = $1 AND
(CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END IS NULL OR
CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END <= $2)`, generation, issuedAt)
if err != nil {
return false, fmt.Errorf("record catalogue freshness: %w", err)
}
@@ -233,18 +249,19 @@ type Package struct {
// Version is one release of a package. Declared, Settings and Accepted are
// JSON; Accepted is nil until the instance accepts the version.
type Version struct {
ID uuid.UUID `db:"id"`
PackageID uuid.UUID `db:"package_id"`
Version string `db:"version"`
Path string `db:"path"`
SHA256 string `db:"sha256"`
Declared []byte `db:"declared"`
Settings []byte `db:"settings"`
Accepted []byte `db:"accepted"`
AcceptedByID string `db:"accepted_by_id"`
Capabilities []byte `db:"capabilities"`
Effects []byte `db:"effects"`
CreatedAt time.Time `db:"created_at"`
ID uuid.UUID `db:"id"`
PackageID uuid.UUID `db:"package_id"`
Version string `db:"version"`
Path string `db:"path"`
SHA256 string `db:"sha256"`
CatalogueDigest string `db:"catalogue_digest"`
Declared []byte `db:"declared"`
Settings []byte `db:"settings"`
Accepted []byte `db:"accepted"`
AcceptedByID string `db:"accepted_by_id"`
Capabilities []byte `db:"capabilities"`
Effects []byte `db:"effects"`
CreatedAt time.Time `db:"created_at"`
}
// Override records that an organisation or a person switched off an
@@ -285,7 +302,7 @@ func (s *Store) Packages(ctx context.Context) ([]Package, error) {
return out, nil
}
const versionColumns = `id, package_id, version, path, sha256, declared, settings, accepted, accepted_by_id,
const versionColumns = `id, package_id, version, path, sha256, catalogue_digest, declared, settings, accepted, accepted_by_id,
capabilities, effects, created_at`
// Versions returns every version of every package, oldest first.
@@ -308,17 +325,30 @@ var (
ErrDefaultVersion = errors.New("the version is the package's default")
// ErrVersionPinned means an installation pins the version.
ErrVersionPinned = errors.New("an installation pins the version")
// ErrCatalogueChanged means a different source or newer catalogue superseded the fetch.
ErrCatalogueChanged = errors.New("the catalogue changed while the package was being fetched")
)
// RegisterVersion records a version of p, creating p when it is new, and
// returns both as stored. A version already stored with the same digest is
// returned unchanged. The first version of a package becomes its default.
func (s *Store) RegisterVersion(ctx context.Context, p Package, v Version, by string) (Package, Version, error) {
func (s *Store) RegisterVersion(ctx context.Context, p Package, v Version, by string, generation int64, issuedAt time.Time) (Package, Version, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err)
}
defer func() { _ = tx.Rollback() }()
var current int64
err = tx.GetContext(ctx, &current, `SELECT generation FROM connectors.catalogue_source
WHERE generation = $1 AND
CASE WHEN location = '' THEN default_newest_issued_at ELSE newest_issued_at END = $2
FOR UPDATE`, generation, issuedAt)
if errors.Is(err, sql.ErrNoRows) {
return Package{}, Version{}, ErrCatalogueChanged
}
if err != nil {
return Package{}, Version{}, fmt.Errorf("check catalogue state: %w", err)
}
p, v, err = registerVersion(ctx, tx, p, v, by)
if err != nil {
return Package{}, Version{}, err
@@ -351,10 +381,10 @@ func registerVersion(ctx context.Context, tx *sqlx.Tx, p Package, v Version, by
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO connectors.package_versions
(id, package_id, version, path, sha256, declared, settings, accepted, accepted_by_id, effects)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
(id, package_id, version, path, sha256, catalogue_digest, declared, settings, accepted, accepted_by_id, effects)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (package_id, version) DO NOTHING`,
uuid.New(), stored.ID, v.Version, v.Path, v.SHA256, orDefault(v.Declared, "{}"), orDefault(v.Settings, "[]"),
uuid.New(), stored.ID, v.Version, v.Path, v.SHA256, v.CatalogueDigest, orDefault(v.Declared, "{}"), orDefault(v.Settings, "[]"),
nilIfEmpty(v.Accepted), v.AcceptedByID, nilIfEmpty(v.Effects)); err != nil {
return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err)
}
@@ -363,7 +393,7 @@ func registerVersion(ctx context.Context, tx *sqlx.Tx, p Package, v Version, by
WHERE package_id = $1 AND version = $2`, stored.ID, v.Version); err != nil {
return Package{}, Version{}, fmt.Errorf("register %s %s: %w", p.Name, v.Version, err)
}
if got.SHA256 != v.SHA256 {
if got.SHA256 != v.SHA256 || got.CatalogueDigest != v.CatalogueDigest {
return Package{}, Version{}, fmt.Errorf("%s %s: %w", p.Name, v.Version, ErrVersionExists)
}
if !stored.DefaultVersion.Valid {
+9 -7
View File
@@ -123,13 +123,15 @@ func (m *Module) viewsFor(ctx context.Context, keep func(store.Installed) bool)
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())
if a.Contract != store.ContractGuard || m.advisoryGuard(a.ID.String()) {
m.mu.RLock()
mem := m.idx.members[a.ID.String()]
view.OverriddenBy = m.idx.overriddenBy(scope, mem)
m.mu.RUnlock()
view.Overridden = len(view.OverriddenBy) > 0
if !view.Editable {
view.CanOverride = overrideScopes(auth, a.Owner())
}
}
views = append(views, view)
}
+25 -7
View File
@@ -100,7 +100,7 @@ type packageStore interface {
// versionStore is where the versions of those packages are kept.
type versionStore interface {
Versions(ctx context.Context) ([]store.Version, error)
RegisterVersion(ctx context.Context, p store.Package, v store.Version, by string) (store.Package, store.Version, error)
RegisterVersion(ctx context.Context, p store.Package, v store.Version, by string, generation int64, issuedAt time.Time) (store.Package, store.Version, error)
AcceptVersion(ctx context.Context, versionID uuid.UUID, accepted []byte, by string) error
SetDefaultVersion(ctx context.Context, packageID, versionID uuid.UUID) error
SetUpdatePolicy(ctx context.Context, packageID uuid.UUID, policy string) error
@@ -293,20 +293,38 @@ func (m *Module) connectorsFor(ctx context.Context) []*Connector {
return out
}
// Guards lists the running guard extensions the caller can use, in name order.
// Guards lists every enabled guard in scope. A narrower installation can't
// shadow a guard, and an unavailable guard must still contribute a verdict.
func (m *Module) Guards(ctx context.Context) []*Guard {
visible := m.visible(ctx)
scope := ScopeFromContext(ctx)
owners := scope.owners()
m.mu.RLock()
defer m.mu.RUnlock()
var out []*Guard
for _, mem := range visible {
if g, ok := m.guards[mem.id]; ok {
out := make([]*Guard, 0, len(m.guards))
for _, id := range slices.Sorted(maps.Keys(m.idx.members)) {
mem := m.idx.members[id]
if mem.contract != store.ContractGuard || !mem.enabled || !slices.Contains(owners, mem.owner) {
continue
}
g := m.guards[id]
if g == nil {
g = &Guard{name: mem.name, digest: mem.digest}
}
if !g.Advisory() || !m.idx.hidden(scope, mem) {
out = append(out, g)
}
}
slices.SortStableFunc(out, func(a, b *Guard) int { return cmp.Compare(a.Name(), b.Name()) })
return out
}
func (m *Module) advisoryGuard(id string) bool {
m.mu.RLock()
defer m.mu.RUnlock()
g := m.guards[id]
return g != nil && g.Advisory()
}
// Delivering lists the running connectors the caller can use that send the
// named delivery, in name order: the channels a message goes out on.
func (m *Module) Delivering(ctx context.Context, delivery string) []*Connector {
@@ -462,7 +480,7 @@ func (m *Module) commit(ctx context.Context, next store.Installed, hadPrevious b
delete(m.failed, next.ID.String())
m.mu.Unlock()
if hadPrevious {
_ = m.launch(ctx, previous)
return errors.Join(err, m.launch(ctx, previous))
}
return err
}
+114 -34
View File
@@ -107,19 +107,19 @@ func withVersion(a store.Installed, v store.Version, pinned bool) store.Installe
// register fetches a version the catalogue offers and records it, not yet
// accepted.
func (m *Module) register(ctx context.Context, location string, entry catalogue.Entry, v catalogue.Version) (store.Package, store.Version, error) {
func (m *Module) register(ctx context.Context, source catalogueSnapshot, entry catalogue.Entry, v catalogue.Version) (store.Package, store.Version, error) {
if !slices.Contains(catalogueContracts, entry.Contract) {
return store.Package{}, store.Version{}, huma.NewError(http.StatusUnprocessableEntity,
fmt.Sprintf("%s serves contract %q, which a catalogue doesn't install", entry.Name, entry.Contract))
}
ref, err := catalogue.Resolve(location, v.Artifact)
if err != nil {
return store.Package{}, store.Version{}, err
}
path, err := m.fetcher.Fetch(ctx, entry.Name, ref, v.Digest)
path, digest, err := m.fetcher.FetchVersion(ctx, entry.Name, source.location, v)
if err != nil {
return store.Package{}, store.Version{}, fmt.Errorf("%s %s: %w", entry.Name, v.Version, err)
}
var pin string
if digest != v.Digest {
pin = v.Digest
}
declared, err := json.Marshal(v.Grants.Normalised())
if err != nil {
return store.Package{}, store.Version{}, err
@@ -130,8 +130,8 @@ func (m *Module) register(ctx context.Context, location string, entry catalogue.
}
pkg, ver, err := m.store.RegisterVersion(ctx,
store.Package{Name: entry.Name, Contract: entry.Contract, DisplayName: entry.DisplayName, Description: entry.Description, Managed: true},
store.Version{Version: v.Version, Path: path, SHA256: v.Digest, Declared: declared, Settings: settings},
governance.CallerID(ctx))
store.Version{Version: v.Version, Path: path, SHA256: digest, CatalogueDigest: pin, Declared: declared, Settings: settings},
governance.CallerID(ctx), source.generation, source.issuedAt)
if err != nil {
return store.Package{}, store.Version{}, err
}
@@ -164,6 +164,20 @@ func (m *Module) acceptGrants(ctx context.Context, v store.Version, want *grants
if err != nil {
return catalogue.Grants{}, err
}
if len(v.Accepted) > 0 {
installed, err := m.store.List(ctx)
if err != nil {
return catalogue.Grants{}, err
}
for _, a := range installed {
if a.VersionID == v.ID {
a.Accepted = raw
if err := checkVersionGrants(a); err != nil {
return catalogue.Grants{}, err
}
}
}
}
if err := m.store.AcceptVersion(ctx, v.ID, raw, governance.CallerID(ctx)); err != nil {
return catalogue.Grants{}, err
}
@@ -175,17 +189,81 @@ func (m *Module) acceptGrants(ctx context.Context, v store.Version, want *grants
// relaunchFollowers restarts the installations of a package that run its
// default version, so they run the version it now names. skip is one already
// restarted.
func (m *Module) relaunchFollowers(ctx context.Context, packageID uuid.UUID, skip ...uuid.UUID) {
func (m *Module) relaunchFollowers(ctx context.Context, packageID uuid.UUID, skip ...uuid.UUID) error {
installed, err := m.refresh(ctx)
if err != nil {
m.log.ErrorContext(ctx, "read installations to restart", "package_id", packageID.String(), "error", err)
return
return err
}
var errs []error
for _, a := range ordered(installed) {
if a.PackageID == packageID && !a.PinnedVersion.Valid && !slices.Contains(skip, a.ID) {
_ = m.launch(ctx, a)
if err := m.launch(ctx, a); err != nil {
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
// promote launches followers before changing the durable default. A restart
// during promotion still loads the old version. On failure, restore each
// installation that was touched, including the one that failed to start.
func (m *Module) promote(ctx context.Context, pkg store.Package, v store.Version) error {
installed, err := m.store.List(ctx)
if err != nil {
return err
}
var followers []store.Installed
for _, a := range ordered(installed) {
if a.PackageID != pkg.ID || a.PinnedVersion.Valid {
continue
}
if err := checkVersionGrants(withVersion(a, v, false)); err != nil {
return err
}
if a.Enabled {
followers = append(followers, a)
}
}
lifetime := context.WithoutCancel(ctx)
for i, previous := range followers {
next := withVersion(previous, v, false)
if err := m.launchVersion(lifetime, next); err != nil {
return errors.Join(err, m.restoreFollowers(lifetime, followers[:i+1]))
}
}
if err := m.store.SetDefaultVersion(ctx, pkg.ID, v.ID); err != nil {
return errors.Join(err, m.restoreFollowers(lifetime, followers))
}
_, err = m.refresh(lifetime)
return err
}
func checkVersionGrants(a store.Installed) error {
var credentials map[string]string
if len(a.Credentials) > 0 {
if err := json.Unmarshal(a.Credentials, &credentials); err != nil {
return err
}
}
return checkAccepted(a, installationRequest{Egress: a.Egress, Env: a.Env, Credentials: credentials})
}
func (m *Module) launchVersion(ctx context.Context, a store.Installed) error {
if err := m.launch(ctx, a); err != nil {
return err
}
return m.checkInstalled(a)
}
func (m *Module) restoreFollowers(ctx context.Context, installed []store.Installed) error {
var errs []error
for _, a := range installed {
if err := m.launch(ctx, a); err != nil {
errs = append(errs, fmt.Errorf("restore %s %s: %w", a.Name, a.Version, err))
}
}
return errors.Join(errs...)
}
// instanceRow returns the instance installation of name; ok is false when
@@ -220,11 +298,11 @@ func (m *Module) packageError(ctx context.Context, err error) error {
case errors.Is(err, catalogue.ErrBeyondDeclared), errors.Is(err, catalogue.ErrDigestMismatch),
errors.Is(err, store.ErrVersionExists), errors.Is(err, store.ErrContractChanged):
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
case errors.Is(err, store.ErrDefaultVersion), errors.Is(err, store.ErrVersionPinned):
case errors.Is(err, store.ErrDefaultVersion), errors.Is(err, store.ErrVersionPinned), errors.Is(err, store.ErrCatalogueChanged):
return huma.NewError(http.StatusConflict, err.Error())
case errors.Is(err, catalogue.ErrInvalidPolicy):
return huma.NewError(http.StatusBadRequest, err.Error())
case errors.Is(err, errNoSource), errors.Is(err, catalogue.ErrBadSignature), errors.Is(err, catalogue.ErrStale):
case errors.Is(err, catalogue.ErrBadSignature), errors.Is(err, catalogue.ErrStale):
return catalogueError(err)
}
m.log.ErrorContext(ctx, "change package", "error", err)
@@ -302,7 +380,7 @@ func (m *Module) install(ctx context.Context, in *installInput) (*httpapi.Reply[
// narrowing what it declared. A version already accepted keeps its grants, so
// installing it again can't narrow what its other installations were given.
func (m *Module) fetchAccepted(ctx context.Context, name, version string, want *grantsRequest) (store.Package, store.Version, catalogue.Grants, error) {
doc, location, err := m.readCatalogue(ctx)
doc, source, err := m.readCatalogue(ctx)
if err != nil {
return store.Package{}, store.Version{}, catalogue.Grants{}, err
}
@@ -314,7 +392,7 @@ func (m *Module) fetchAccepted(ctx context.Context, name, version string, want *
if !ok {
return store.Package{}, store.Version{}, catalogue.Grants{}, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s %s", name, version))
}
pkg, ver, err := m.register(ctx, location, entry, cv)
pkg, ver, err := m.register(ctx, source, entry, cv)
if err != nil {
return store.Package{}, store.Version{}, catalogue.Grants{}, err
}
@@ -354,11 +432,11 @@ func (m *Module) registerVersion(ctx context.Context, in *registerVersionInput)
if !pv.pkg.Managed {
return nil, huma.NewError(http.StatusConflict, in.Name+" is accepted by path, not installed from the catalogue")
}
doc, location, err := m.readCatalogue(ctx)
doc, source, err := m.readCatalogue(ctx)
if err != nil {
return nil, m.packageError(ctx, err)
}
ver, err := m.offer(ctx, doc, location, pv, in.Body.Version)
ver, err := m.offer(ctx, doc, source, pv, in.Body.Version)
if err != nil {
return nil, m.packageError(ctx, err)
}
@@ -367,7 +445,7 @@ func (m *Module) registerVersion(ctx context.Context, in *registerVersionInput)
// offer registers a version of pv from the catalogue and accepts it when the
// default version's grants cover what it declares.
func (m *Module) offer(ctx context.Context, doc catalogue.Document, location string, pv packageVersions, version string) (store.Version, error) {
func (m *Module) offer(ctx context.Context, doc catalogue.Document, source catalogueSnapshot, pv packageVersions, version string) (store.Version, error) {
entry, ok := doc.Entry(pv.pkg.Name)
if !ok {
return store.Version{}, huma.NewError(http.StatusNotFound, "the catalogue doesn't list "+pv.pkg.Name)
@@ -376,7 +454,7 @@ func (m *Module) offer(ctx context.Context, doc catalogue.Document, location str
if !ok {
return store.Version{}, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s %s", pv.pkg.Name, version))
}
_, ver, err := m.register(ctx, location, entry, cv)
_, ver, err := m.register(ctx, source, entry, cv)
if err != nil || len(ver.Accepted) > 0 {
return ver, err
}
@@ -427,9 +505,6 @@ func (m *Module) acceptVersion(ctx context.Context, in *acceptVersionInput) (*ht
if ver.Accepted, err = json.Marshal(accepted); err != nil {
return nil, m.packageError(ctx, err)
}
if ver.ID == pv.pkg.DefaultVersion.UUID {
m.relaunchFollowers(context.WithoutCancel(ctx), pv.pkg.ID)
}
return httpapi.OK(versionView(ver, pv.pkg, nil)), nil
}
@@ -456,12 +531,11 @@ func (m *Module) setDefaultVersion(ctx context.Context, in *defaultVersionInput)
if len(ver.Accepted) == 0 {
return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("accept %s %s before running it", in.Name, ver.Version))
}
if err := m.store.SetDefaultVersion(ctx, pv.pkg.ID, ver.ID); err != nil {
if err := m.promote(ctx, pv.pkg, ver); err != nil {
return nil, m.packageError(ctx, err)
}
m.log.InfoContext(ctx, "package default version set", "audit", true, "action", "package.default",
"package", in.Name, "version", ver.Version)
m.relaunchFollowers(context.WithoutCancel(ctx), pv.pkg.ID)
pv.pkg.DefaultVersion = uuid.NullUUID{UUID: ver.ID, Valid: true}
return httpapi.OK(versionView(ver, pv.pkg, nil)), nil
}
@@ -474,6 +548,8 @@ type updatePolicyInput struct {
}
func (m *Module) setUpdatePolicy(ctx context.Context, in *updatePolicyInput) (*httpapi.Reply[packageState], error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
if err := catalogue.CheckPolicy(in.Body.Policy); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
@@ -481,6 +557,9 @@ func (m *Module) setUpdatePolicy(ctx context.Context, in *updatePolicyInput) (*h
if err != nil {
return nil, err
}
if pv.pkg.Contract == store.ContractGuard && in.Body.Policy != catalogue.PolicyManual {
return nil, huma.NewError(http.StatusUnprocessableEntity, "guards must be updated manually")
}
if err := m.store.SetUpdatePolicy(ctx, pv.pkg.ID, in.Body.Policy); err != nil {
return nil, m.packageError(ctx, err)
}
@@ -516,8 +595,7 @@ func errNoVersion(name, version string) error {
// UpdateAuto fetches the newest catalogue version of every package whose
// policy is auto. One whose grants the default version's cover becomes the
// default; one that asks for more waits for an operator. One package that
// fails doesn't stop the rest. It does nothing when no catalogue source is
// set.
// fails doesn't stop the rest.
func (m *Module) UpdateAuto(ctx context.Context) error {
pkgs, err := m.store.Packages(ctx)
if err != nil {
@@ -525,33 +603,36 @@ func (m *Module) UpdateAuto(ctx context.Context) error {
}
var auto []string
for _, p := range pkgs {
if p.Managed && p.UpdatePolicy == catalogue.PolicyAuto {
if p.Managed && p.Contract != store.ContractGuard && p.UpdatePolicy == catalogue.PolicyAuto {
auto = append(auto, p.Name)
}
}
if len(auto) == 0 {
return nil
}
doc, location, err := m.readCatalogue(ctx)
doc, source, err := m.readCatalogue(ctx)
if err != nil {
return err
}
var errs []error
for _, name := range auto {
if err := m.updateOne(ctx, doc, location, name); err != nil {
if err := m.updateOne(ctx, doc, source, name); err != nil {
errs = append(errs, fmt.Errorf("update %s: %w", name, err))
}
}
return errors.Join(errs...)
}
func (m *Module) updateOne(ctx context.Context, doc catalogue.Document, location, name string) error {
func (m *Module) updateOne(ctx context.Context, doc catalogue.Document, source catalogueSnapshot, name string) error {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
pv, err := m.packageNamed(ctx, name)
if err != nil {
return err
}
if pv.pkg.UpdatePolicy != catalogue.PolicyAuto || pv.pkg.Contract == store.ContractGuard {
return nil
}
entry, ok := doc.Entry(name)
if !ok {
return nil
@@ -561,15 +642,14 @@ func (m *Module) updateOne(ctx context.Context, doc catalogue.Document, location
if !ok || (hasDefault && !catalogue.Newer(latest.Version, def.Version)) {
return nil
}
ver, err := m.offer(ctx, doc, location, pv, latest.Version)
ver, err := m.offer(ctx, doc, source, pv, latest.Version)
if err != nil || len(ver.Accepted) == 0 {
return err
}
if err := m.store.SetDefaultVersion(ctx, pv.pkg.ID, ver.ID); err != nil {
if err := m.promote(ctx, pv.pkg, ver); err != nil {
return err
}
m.log.InfoContext(ctx, "package updated", "audit", true, "action", "package.default", "package", name, "version", ver.Version)
m.relaunchFollowers(ctx, pv.pkg.ID)
return nil
}
+4
View File
@@ -17,6 +17,8 @@ import (
func (m *Module) remove(contract string) func(context.Context, *nameInput) (*httpapi.Reply[packageState], error) {
return func(ctx context.Context, in *nameInput) (*httpapi.Reply[packageState], error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
return m.removeAs(ctx, in, contract)
}
}
@@ -118,6 +120,8 @@ type installationInput struct {
// removeInstallation deletes one installation the caller manages and stops it.
// The package stays accepted.
func (m *Module) removeInstallation(ctx context.Context, in *installationInput) (*httpapi.Reply[packageState], error) {
m.pkgMu.Lock()
defer m.pkgMu.Unlock()
a, _, err := m.installationFor(ctx, in.ID, true)
if err != nil {
return nil, err
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"strings"
"testing"
"time"
"filippo.io/age"
"github.com/danielgtaylor/huma/v2"
@@ -38,7 +39,7 @@ func (f *fakeRegistry) Packages(context.Context) ([]store.Package, error) { retu
func (f *fakeRegistry) Versions(context.Context) ([]store.Version, error) { return nil, nil }
func (f *fakeRegistry) RegisterVersion(_ context.Context, p store.Package, v store.Version, _ string) (store.Package, store.Version, error) {
func (f *fakeRegistry) RegisterVersion(_ context.Context, p store.Package, v store.Version, _ string, _ int64, _ time.Time) (store.Package, store.Version, error) {
return p, v, nil
}
+2 -1
View File
@@ -82,6 +82,7 @@ type member struct {
name string
owner store.Owner
contract string
digest string
enabled bool
}
@@ -101,7 +102,7 @@ func newIndex(installed []store.Installed, overrides []store.Override) index {
ix := index{members: make(map[string]member, len(installed)), overrides: make(map[override]struct{}, len(overrides))}
for _, a := range installed {
ix.members[a.ID.String()] = member{
id: a.ID.String(), name: a.Name, owner: a.Owner(), contract: a.Contract, enabled: a.Enabled,
id: a.ID.String(), name: a.Name, owner: a.Owner(), contract: a.Contract, digest: a.SHA256, enabled: a.Enabled,
}
}
for _, o := range overrides {
+24
View File
@@ -108,6 +108,30 @@ func TestOverridesNameTheScopeThatSetThem(t *testing.T) {
}
}
// TestInheritedGuardStillJudges guards against a saved override or a
// narrower installation masking an unavailable enforcing guard.
func TestInheritedGuardStillJudges(t *testing.T) {
instance := store.Installed{ID: uuid.New(), Scope: store.ScopeInstance, Name: "hours", Contract: store.ContractGuard, Enabled: true}
personal := store.Installed{ID: uuid.New(), Scope: store.ScopePerson, PersonID: "me", Name: "hours", Contract: store.ContractGuard, Enabled: true}
m := &Module{
idx: newIndex([]store.Installed{instance, personal}, []store.Override{
{InstallationID: instance.ID, Scope: store.ScopePerson, PersonID: "me"},
}),
guards: map[string]*Guard{personal.ID.String(): {name: "hours", advisory: true}},
}
ctx := WithScope(t.Context(), Scope{PersonID: "me"})
guards := m.Guards(ctx)
for _, g := range guards {
if !g.Advisory() {
if _, err := g.Judge(ctx, GuardRequest{}); err == nil {
t.Fatal("an unavailable guard returned a successful verdict")
}
return
}
}
t.Fatalf("the inherited guard disappeared from %d verdicts", len(guards))
}
// TestCredentialResolutionRespectsScope guards the credential boundary: a name
// resolves to the person's credential, then their organisation's, then the
// instance's, and never to another organisation's or person's.