cpdp

package
v1.0.310 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cpdp implements the signed, immutable Control-Plane → Data-Plane snapshot model for the two MCP capabilities (Gateway and Management), plus the epoch fencing, minimum-DP-version compatibility gate, acknowledgement model, and signed rollback directive that PR-10 (MCP-CPDP-001..003, MCP-HA-001..002) requires. It is DECISION-ONLY distribution machinery: it distributes and activates decision state (policy/catalog/credential-metadata revisions), and it never executes an upstream tool, materializes a credential, or introduces a Data-Plane dependency on the Control Plane on any request/tool-call path.

Design doctrine (see docs/design/mcp/CP-DP-HA-MODEL.md):

  • Whole-snapshot validation, never partial apply. A single failed check rejects the entire capability snapshot and leaves the current active snapshot byte-unchanged.
  • Validate-then-swap. Signature, schema, caps, revisions and minimum version are all proven BEFORE any active-state mutation; runtime objects are built off the active request path; the active pointer swap is one atomic step.
  • Capability isolation. Gateway and Management have separate namespaces, payloads, revisions, active/previous pointers, minimum-version requirements, acknowledgements and rollback targets. A Gateway snapshot can never activate Management state and vice versa; capability is a mandatory SIGNED field and a mismatch fails closed.
  • Reuse, do not reinvent. The signing envelope mirrors the release-catalog ed25519 pattern; deterministic bytes come from internal/mcp/canonical; epoch fencing reuses the ADR-0005 HA lease epoch; the private signing key never leaves a scoped Signer (no raw-byte getter) and is never distributed to a Data Plane.

The package is a leaf: it depends only on internal/mcp/canonical and internal/mcp/mcperr, so it can be consumed by the apply/publication sub-packages and by package main's thin adapters without an import cycle.

Index

Constants

View Source
const SchemaVersion = 1

SchemaVersion is the current MCP snapshot envelope schema version. A DP rejects any envelope whose declared schema version is not in the supported set — a newer/unknown schema is never partially interpreted (MCP-CPDP-002).

View Source
const SigAlgEd25519 = "ed25519"

SigAlgEd25519 is the ONLY accepted signature algorithm identifier. An unknown algorithm is never treated as ed25519 (downgrade guard, MCP-CPDP-001).

Variables

This section is empty.

Functions

func CandidateHash

func CandidateHash(capability Capability, p Payload, b canonical.Bounds) (string, error)

CandidateHash computes a stable hex SHA-256 over just the capability + payload, EXCLUDING the CP-stamped manifest fields (epoch, created time, revisions). It lets the CP bind an approved four-eyes candidate to the EXACT payload that will be signed: the coordinator recomputes it from the payload it is about to sign and rejects a mismatch with the approved candidate hash, so a caller cannot approve one candidate and then sign a different payload.

func CheckMinVersion

func CheckMinVersion(minVer, dp CompatVersion) error

CheckMinVersion evaluates the minimum-DP-version gate for a snapshot declaring min as its minimum_dp_version, running on a DP whose own compatibility version is dp. It returns:

  • ReasonSnapshotMinVersionMalformed if min is absent/out of range;
  • ReasonSnapshotMinVersionUnmet if the DP is below the required minimum (the DP MUST NOT apply and keeps its prior valid snapshot);
  • nil if the DP is at or above the minimum and may continue validation.

func CheckMonotonic

func CheckMonotonic(active, cand Revisions, activeEpoch, candEpoch int64) error

CheckMonotonic evaluates the revision-ordering contract for a candidate tuple (cand) arriving to advance from the currently-active tuple (active), where candEpoch/activeEpoch are the respective configuration epochs. It enforces:

  • a lower Config revision in the same or a lower epoch is rejected (ReasonSnapshotRevisionRegression);
  • credential metadata cannot move backwards silently — a lower Credential revision in the same or a lower epoch is rejected;
  • catalog cannot silently regress within the same or a lower epoch (an intended catalog revert is an explicit rollback, not a stale publication);
  • a HIGHER epoch is permitted to carry any revision (a new leader generation re-bases the tuple) — but ONLY after the snapshot's authenticity has already been proven by the caller; this function assumes signature/schema validation has passed and does not itself bypass it.

Idempotence (same revision, same content) and same-revision-different-content rejection are handled by the active store against the content hash; this function is the pure ordering rule and is content-hash agnostic.

func ContentHash

func ContentHash(m Manifest, p Payload, alg, keyID string, b canonical.Bounds) (string, error)

ContentHash computes the hex SHA-256 content hash over the canonical signable representation of (manifest, payload, alg, keyID). It is the single hashing primitive used by both the signer (to produce content_hash) and the verifier (to recompute and compare). Any mutation of any signed field — including a payload section, the algorithm, the key id, or any revision — changes the hash.

func Validate

func Validate(env *Envelope, in ValidateInput) error

Validate performs the complete whole-snapshot validation in the mandated order, rejecting the ENTIRE snapshot on any failure (no partial apply). It runs BEFORE any state mutation. The order is:

envelope bounds → schema → alg → key trust → content hash → signature
→ capability match → capability isolation → epoch stale check (non-mutating)
→ revision bounds → minimum DP version → per-section + aggregate bounds
→ payload consistency (safe config, references, no secret-bearing fields).

It does NOT ratchet the epoch or mutate any state — a caller applies the mutating CommitObservedEpoch only after Validate returns nil.

func ValidateCandidate

func ValidateCandidate(m Manifest, p Payload, in ValidateInput) error

ValidateCandidate validates an UNSIGNED candidate (manifest + payload) before it is signed — the CP-side "validate the unsigned candidate completely" step. It runs every check Validate runs EXCEPT the signature/hash verification (there is no signature yet). A candidate that fails here is never signed or published.

func VerifyRollback

func VerifyRollback(d *RollbackDirective, trust *TrustStore, expectCap Capability, currentActiveHash string, nowUnixNano int64, dpVersion CompatVersion) error

VerifyRollback verifies a rollback directive's signature and structural validity against the trust store, then checks it is not expired and binds to the expected current active hash. A directive that is malformed, signed by an untrusted key, expired, or bound to a different current hash is rejected.

func VerifySignature

func VerifySignature(env *Envelope, trust *TrustStore, l Limits) error

VerifySignature performs the cryptographic verification of an envelope in the mandated order, WITHOUT the semantic validation (which is a separate step so the ordering "authenticate before ratchet, validate before mutate" is explicit in the caller):

  1. structural: bounded header fields are present;
  2. known schema version;
  3. known algorithm (ed25519);
  4. trusted key id;
  5. recomputed content hash equals the declared content hash;
  6. ed25519 signature verifies over the domain-separated content hash.

An unknown algorithm, unknown key, malformed hash, or malformed/oversized signature rejects the whole snapshot. A key carried inside the snapshot never authorizes itself — only the trust store is consulted.

Types

type AckState

type AckState uint8

AckState is the state a DP reports for a specific signed snapshot.

const (
	// AckReceived — the snapshot was received (pre-validation).
	AckReceived AckState = iota
	// AckRejected — the snapshot was rejected whole; the DP retained its current
	// valid snapshot.
	AckRejected
	// AckValidated — the snapshot passed whole validation but is not yet active.
	AckValidated
	// AckApplied — the snapshot was atomically activated.
	AckApplied
	// AckRolledBack — the DP reverted to a retained target (rollback acknowledgement).
	AckRolledBack
)

func (AckState) String

func (s AckState) String() string

String returns the stable wire string for the ack state.

func (AckState) Valid

func (s AckState) Valid() bool

Valid reports whether s is a defined ack state.

type Acknowledgement

type Acknowledgement struct {
	AckID        string        `json:"ack_id"`
	NodeID       string        `json:"node_id"` // from authenticated enrollment identity
	Capability   Capability    `json:"capability"`
	ContentHash  string        `json:"content_hash"`
	Epoch        int64         `json:"epoch"`
	Revisions    Revisions     `json:"revisions"`
	State        AckState      `json:"state"`
	ActiveHash   string        `json:"active_hash"`
	PreviousHash string        `json:"previous_hash,omitempty"`
	DPVersion    CompatVersion `json:"dp_version"`
	Health       string        `json:"health"`
	RejectReason string        `json:"reject_reason,omitempty"` // bounded machine code, never raw text
	TimeUnixNano int64         `json:"time_unix_nano"`
	RetrySeq     int           `json:"retry_seq"`
}

Acknowledgement is the typed, bounded report a DP sends the CP, bound to a SPECIFIC signed snapshot by content hash. It carries only SAFE fields — never a raw snapshot, credential data, private key, raw policy, tool arguments/output, or unbounded error text.

func (Acknowledgement) Matches

func (a Acknowledgement) Matches(nodeID string, capability Capability, contentHash string) bool

Matches reports whether the acknowledgement binds to exactly (nodeID, capability, contentHash). The CP tracks acknowledgements per (node, capability, content hash); an acknowledgement for one snapshot can never satisfy another.

func (Acknowledgement) Validate

func (a Acknowledgement) Validate() error

Validate checks that an acknowledgement is well-formed and bound: it must carry an ack id, an authenticated node id, a valid capability, a content hash, and a defined state, and its reject reason must be a bounded machine code. An acknowledgement missing any binding field fails closed.

type ActiveStore

type ActiveStore struct {
	// contains filtered or unexported fields
}

ActiveStore is a capability-local holder of the current and previous signed snapshots. The request/tool-call path reads the current active pointer LOCK-FREE (an atomic load) and never blocks on the CP, the signer, an acknowledgement service, or storage (MCP-HA-001). Swaps and rollbacks are serialized by a mutex that the request path never touches.

One ActiveStore instance serves exactly one capability; a Gateway store can never hold or activate Management state and vice versa.

func NewActiveStore

func NewActiveStore(capability Capability) *ActiveStore

NewActiveStore returns an empty capability-local store. Until a valid snapshot is activated, Active returns nil (the DP stays disabled / fails closed for that capability).

func (*ActiveStore) Activate

func (s *ActiveStore) Activate(env *Envelope) (swapped bool, err error)

Activate atomically installs env as the current snapshot, moving the prior current to previous. The caller MUST have already validated env (whole-snapshot validation) and durably persisted it BEFORE calling Activate — this is the swap step of persist-before-swap, not the validation or persistence step.

Semantics:

  • env's capability must match the store's, else it fails closed.
  • If env's content hash equals the current active hash, the activation is idempotent: the store is unchanged and (false, nil) is returned.
  • If env carries the SAME config revision+epoch as the current active snapshot but a DIFFERENT content hash, it is rejected (same revision, different content) — a revision must never name two different contents.
  • Otherwise the swap advances: previous ← current, current ← env, and (true, nil) is returned.

func (*ActiveStore) Active

func (s *ActiveStore) Active() *Envelope

Active returns the current active snapshot, or nil if none is active. This is the lock-free read the request path uses.

func (*ActiveStore) ActiveHash

func (s *ActiveStore) ActiveHash() string

ActiveHash returns the current active content hash, or "" if none.

func (*ActiveStore) Capability

func (s *ActiveStore) Capability() Capability

Capability returns the capability this store serves.

func (*ActiveStore) Previous

func (s *ActiveStore) Previous() *Envelope

Previous returns the retained previous snapshot, or nil.

func (*ActiveStore) PreviousHash

func (s *ActiveStore) PreviousHash() string

PreviousHash returns the retained previous content hash, or "".

func (*ActiveStore) Restore

func (s *ActiveStore) Restore(current, previous *Envelope) error

Restore reinstalls a validated (current, previous) pair at startup recovery. Both envelopes must already be signature/hash-verified and match the store's capability. current may be nil only if previous is also nil.

func (*ActiveStore) Revert

func (s *ActiveStore) Revert(targetHash string) (reverted bool, err error)

Revert atomically reverts the current pointer to a retained target snapshot identified by targetHash. The target MUST be the retained previous snapshot (the only retained rollback target in the current+previous retention model). The caller has already verified the signed rollback directive AND re-verified the target snapshot's signature/hash before calling Revert. On success the prior current becomes previous (so the operation is itself reversible) and (true, nil) is returned. A missing/mismatched target fails closed and leaves the current pointer UNCHANGED.

type Capability

type Capability uint8

Capability names one of the two MCP capabilities. It is a mandatory SIGNED field of every snapshot envelope; a mismatch between the envelope's capability and the target store fails closed.

const (
	// CapabilityUnknown is the zero value: no capability. Fails closed.
	CapabilityUnknown Capability = iota
	// CapabilityGateway is the MCP Security Gateway capability (business tool
	// traffic). Its payload carries the reviewed server registry, tool catalog,
	// compiled policy, inspection profiles and credential-profile METADATA.
	CapabilityGateway
	// CapabilityManagement is the Culvert Management MCP capability (configuration).
	// Its payload carries only its own reviewed listener/access/operation state and
	// never a Gateway tool catalog or a Gateway credential profile.
	CapabilityManagement
)

func ParseCapability

func ParseCapability(s string) (Capability, error)

ParseCapability resolves a capability from its wire string, failing closed on anything outside the closed set.

func (Capability) MarshalText

func (c Capability) MarshalText() ([]byte, error)

MarshalText encodes the capability as its stable wire string.

func (Capability) String

func (c Capability) String() string

String returns the stable wire string for the capability. These strings are part of the signed manifest and MUST NOT change.

func (*Capability) UnmarshalText

func (c *Capability) UnmarshalText(b []byte) error

UnmarshalText decodes a capability from its stable wire string. An unknown string fails closed rather than defaulting to a capability.

func (Capability) Valid

func (c Capability) Valid() bool

Valid reports whether c is one of the two real capabilities.

type CompatVersion

type CompatVersion uint32

CompatVersion is a MONOTONIC MCP-snapshot compatibility integer, NOT a display version. A snapshot's minimum_dp_version is a CompatVersion; a DP build declares its own DPCompatVersion. The comparison is a numeric ordering, never a lexicographic string compare (MCP-CPDP-003): a DP applies a snapshot only when its own compatibility version is greater than or equal to the snapshot's minimum. Each increment maps to a concrete DP-build capability change; the mapping is recorded next to DPCompatVersion below.

const DPCompatVersion CompatVersion = 1

DPCompatVersion is THIS build's MCP snapshot compatibility version. It is the value a running Data Plane compares against a snapshot's minimum_dp_version. It increments (by a deliberate edit here) whenever a DP build gains the ability to interpret a security-relevant snapshot semantic that an older DP must not partially apply.

1 — PR-10 baseline: signed envelope, epoch fencing, revision tuple,
    minimum-version gate, acknowledgements, atomic activation, rollback.

func (CompatVersion) ValidMinVersion

func (v CompatVersion) ValidMinVersion() bool

ValidMinVersion reports whether v is a well-formed minimum_dp_version for a PR-10 MCP snapshot. An ABSENT minimum (0) is rejected — a PR-10 snapshot MUST declare a positive minimum so an older DP can never ignore the gate — as is a value above the hard cap.

type Config

type Config struct {
	MaxEnvelopeBytes       int
	MaxPayloadSectionBytes int
	MaxAggregateBytes      int
	MaxRegistryServers     int
	MaxCatalogTools        int
	MaxPolicyRules         int
	MaxCredentialProfiles  int
	MaxInspectionProfiles  int
	MaxTrustRoots          int
	MaxKeyIDBytes          int
	MaxSignatureBytes      int
	MaxAcksPerNodeCap      int
	MaxAckHistory          int
	MaxPendingAckRetries   int
	MaxRetainedSnapshots   int
	MaxRetainedBytes       int
	MaxRollbackDirectives  int
	RollbackExpiry         time.Duration
	MaxDryValidationCases  int
	MaxConcurrentApplies   int
	MaxConcurrentPublish   int
	MaxConcurrentRollbacks int
}

Config is the mutable input to NewLimits. Callers set every field; NewLimits validates it and returns an immutable Limits. A zero Config is invalid.

type CredentialProfileMeta

type CredentialProfileMeta struct {
	ProfileID   string `json:"profile_id"`
	Scope       string `json:"scope"`
	ProviderRef string `json:"provider_ref"`
	Version     uint64 `json:"version"`
}

CredentialProfileMeta is credential-profile METADATA ONLY: the profile id, its scope, and a provider REFERENCE (never a secret value or ciphertext). This is exactly what "credential_revision" tracks — profile shape, not secret material.

type Envelope

type Envelope struct {
	Manifest    Manifest `json:"manifest"`
	Payload     Payload  `json:"payload"`
	ContentHash string   `json:"content_hash"` // hex sha256 of the canonical signable form
	SigAlg      string   `json:"sig_alg"`      // MUST be "ed25519"
	KeyID       string   `json:"key_id"`
	Signature   string   `json:"signature"` // std-base64 of the raw 64-byte ed25519 signature
}

Envelope is one versioned, immutable, signed MCP snapshot. The signature authenticates the content hash; the content hash covers the complete unsigned manifest + algorithm + key id + payload (everything EXCEPT the content_hash and signature themselves, which would create a circular dependency).

func Sign

func Sign(m Manifest, p Payload, s Signer, l Limits) (*Envelope, error)

Sign produces a signed Envelope from a manifest + payload using the signer. It computes the content hash over the canonical signable form, then signs the domain-separated content hash. The manifest's schema version, capability, and the signer's algorithm/key id are stamped into the envelope. Signing does NOT perform semantic validation — the caller validates the candidate BEFORE signing (validate-then-sign).

type EpochRatchet

type EpochRatchet struct {
	// contains filtered or unexported fields
}

EpochRatchet is a pure, in-memory monotonic fencing-epoch ratchet that splits the existing dpObserveEpoch check-and-commit into two explicit operations, as PR-10 requires: a NON-mutating preliminary stale check (CheckEpoch), used before signature/schema validation; and a mutating ratchet (CommitObservedEpoch), used only AFTER authenticity is proven. This ordering is what prevents a malicious or corrupt high-epoch envelope from permanently fencing out the currently trusted CP before authenticity is established (MCP-HA-001).

It preserves the two special rejects of the root dpObserveEpoch: an epoch below the last-seen epoch is stale, and a zero/unfenced epoch after a positive epoch has already been seen is a zombie signal. The ratchet is seeded at startup from the DP's durable last-seen epoch and never regresses.

func NewEpochRatchet

func NewEpochRatchet(seed int64) *EpochRatchet

NewEpochRatchet returns a ratchet seeded to seed (the DP's durable last-seen trusted epoch; 0 means unseeded/legacy).

func (*EpochRatchet) CheckEpoch

func (r *EpochRatchet) CheckEpoch(epoch int64) error

CheckEpoch performs the NON-mutating preliminary check. It rejects:

  • an epoch below the last-seen epoch (a stale/zombie Control Plane); and
  • a zero/unfenced epoch once a positive epoch has already been seen.

It NEVER advances the ratchet — a snapshot that passes CheckEpoch must still be authenticated (signature/schema/revisions/min-version) before CommitObservedEpoch is called. A same-or-higher trusted epoch returns nil.

func (*EpochRatchet) CommitObservedEpoch

func (r *EpochRatchet) CommitObservedEpoch(epoch int64) (advanced bool, err error)

CommitObservedEpoch ratchets the trusted epoch forward to epoch, returning true if the ratchet advanced (so the caller can persist the new durable last-seen epoch). It MUST be called only after the snapshot's authenticity has been proven. It re-applies the stale/zombie guards under the lock so a racing lower or zero epoch can never win. A same epoch is accepted (idempotent) but does not advance; a higher epoch advances.

func (*EpochRatchet) Last

func (r *EpochRatchet) Last() int64

Last returns the highest observed trusted epoch.

type GatewayListener

type GatewayListener struct {
	Enabled                  bool     `json:"enabled"`
	BindAddress              string   `json:"bind_address"`
	Port                     int      `json:"port"`
	ProtocolVersionPolicy    string   `json:"protocol_version_policy"`
	OriginHostAllowlist      []string `json:"origin_host_allowlist"`
	TLSProfileRef            string   `json:"tls_profile_ref"`
	ClientCertMode           string   `json:"client_cert_mode"`
	UnknownToolDefaultAction string   `json:"unknown_tool_default_action"`
	PolicyDefaultAction      string   `json:"policy_default_action"`
	RateLimitRPS             int      `json:"rate_limit_rps"`
	RateLimitBurst           int      `json:"rate_limit_burst"`
}

GatewayListener is the reviewed Gateway listener/access configuration assigned to DP distribution. References/metadata only — never key material or a token.

type GatewayPayload

type GatewayPayload struct {
	Listener           GatewayListener         `json:"listener"`
	Servers            []ServerRecord          `json:"servers"`
	Tools              []ToolRecord            `json:"tools"`
	PolicySource       string                  `json:"policy_source"` // strictly serializable PR-6 policy document
	InspectionProfiles []InspectionProfileMeta `json:"inspection_profiles"`
	CredentialProfiles []CredentialProfileMeta `json:"credential_profiles"`
	// Rollout is the OPTIONAL PR-11 signed rollout config (mode + scope + connector
	// mode). nil ⇒ no rollout change (an older/rolled-back CP that predates PR-11
	// never wipes a DP's rollout state). It rides the content hash + signature with
	// no extra plumbing and is validated + applied on the DP whole-or-nothing.
	Rollout *rollout.SignedConfig `json:"rollout,omitempty"`
}

GatewayPayload is the reviewed state a Gateway DP needs. It never contains a credential value, a client token, or a signing private key.

type InspectionProfileMeta

type InspectionProfileMeta struct {
	ID      string `json:"id"`
	Version uint64 `json:"version"`
}

InspectionProfileMeta is inspection-profile metadata (id + version). The profile bodies themselves are compiled from reviewed config on the DP.

type Limits

type Limits struct {
	// contains filtered or unexported fields
}

Limits is an immutable, validated bound set.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the validated production default bound set.

func NewLimits

func NewLimits(c Config) (Limits, error)

NewLimits validates a Config and returns an immutable Limits, or an error if any field is zero, negative, over its hard cap, or internally contradictory.

func (Limits) CanonicalBounds

func (l Limits) CanonicalBounds() canonical.Bounds

CanonicalBounds derives the strict canonical-serializer bounds used to decode and hash a snapshot payload, sized from the envelope byte bound. It is exported so the publication coordinator can compute a content hash pre-sign with the same bounds the DP verifier uses.

func (Limits) MaxAckHistory

func (l Limits) MaxAckHistory() int

MaxAckHistory is the maximum retained acknowledgement/known-hash history.

func (Limits) MaxAcksPerNodeCap

func (l Limits) MaxAcksPerNodeCap() int

MaxAcksPerNodeCap is the maximum tracked acknowledgements per node/capability.

func (Limits) MaxAggregateBytes

func (l Limits) MaxAggregateBytes() int

MaxAggregateBytes is the maximum aggregate payload byte budget.

func (Limits) MaxCatalogTools

func (l Limits) MaxCatalogTools() int

MaxCatalogTools is the maximum number of tool records in a Gateway payload.

func (Limits) MaxConcurrentApplies

func (l Limits) MaxConcurrentApplies() int

MaxConcurrentApplies is the maximum concurrent DP applies.

func (Limits) MaxConcurrentPublish

func (l Limits) MaxConcurrentPublish() int

MaxConcurrentPublish is the maximum concurrent CP publications.

func (Limits) MaxConcurrentRollbacks

func (l Limits) MaxConcurrentRollbacks() int

MaxConcurrentRollbacks is the maximum concurrent rollbacks.

func (Limits) MaxCredentialProfiles

func (l Limits) MaxCredentialProfiles() int

MaxCredentialProfiles is the maximum number of credential-profile metadata entries.

func (Limits) MaxDryValidationCases

func (l Limits) MaxDryValidationCases() int

MaxDryValidationCases is the maximum bounded dry-validation case count.

func (Limits) MaxEnvelopeBytes

func (l Limits) MaxEnvelopeBytes() int

MaxEnvelopeBytes is the maximum encoded bytes of a whole signed envelope.

func (Limits) MaxInspectionProfiles

func (l Limits) MaxInspectionProfiles() int

MaxInspectionProfiles is the maximum number of inspection-profile metadata entries.

func (Limits) MaxKeyIDBytes

func (l Limits) MaxKeyIDBytes() int

MaxKeyIDBytes is the maximum length of a signing key id.

func (Limits) MaxPayloadSectionBytes

func (l Limits) MaxPayloadSectionBytes() int

MaxPayloadSectionBytes is the maximum encoded bytes of a single payload section.

func (Limits) MaxPendingAckRetries

func (l Limits) MaxPendingAckRetries() int

MaxPendingAckRetries is the maximum pending-acknowledgement retry count.

func (Limits) MaxPolicyRules

func (l Limits) MaxPolicyRules() int

MaxPolicyRules is the maximum number of compiled policy rules.

func (Limits) MaxRegistryServers

func (l Limits) MaxRegistryServers() int

MaxRegistryServers is the maximum number of server records in a Gateway payload.

func (Limits) MaxRetainedBytes

func (l Limits) MaxRetainedBytes() int

MaxRetainedBytes is the maximum retained-snapshot byte budget.

func (Limits) MaxRetainedSnapshots

func (l Limits) MaxRetainedSnapshots() int

MaxRetainedSnapshots is the maximum retained snapshot count (>= 2 for rollback).

func (Limits) MaxRollbackDirectives

func (l Limits) MaxRollbackDirectives() int

MaxRollbackDirectives is the maximum retained rollback-directive count.

func (Limits) MaxSignatureBytes

func (l Limits) MaxSignatureBytes() int

MaxSignatureBytes is the maximum encoded length of a signature.

func (Limits) MaxTrustRoots

func (l Limits) MaxTrustRoots() int

MaxTrustRoots is the maximum number of trust roots in a trust store.

func (Limits) RollbackExpiry

func (l Limits) RollbackExpiry() time.Duration

RollbackExpiry is the maximum validity window of a rollback directive.

type ManagementListener

type ManagementListener struct {
	Enabled               bool     `json:"enabled"`
	BindAddress           string   `json:"bind_address"`
	Port                  int      `json:"port"`
	ProtocolVersionPolicy string   `json:"protocol_version_policy"`
	OriginHostAllowlist   []string `json:"origin_host_allowlist"`
	TLSProfileRef         string   `json:"tls_profile_ref"`
	ClientCertMode        string   `json:"client_cert_mode"`
	AuthMode              string   `json:"auth_mode"`
	DefaultMinRole        string   `json:"default_min_role"`
	MutationEnabled       bool     `json:"mutation_enabled"` // MUST be false in V1
	TenantScopeMode       string   `json:"tenant_scope_mode"`
	OutputMaxBytes        int      `json:"output_max_bytes"`
	OutputRedaction       string   `json:"output_redaction"`
}

ManagementListener is the reviewed Management listener/access configuration.

type ManagementPayload

type ManagementPayload struct {
	Listener                ManagementListener `json:"listener"`
	OperationCatalogVersion uint64             `json:"operation_catalog_version"`
	PolicyReadScope         string             `json:"policy_read_scope"`
	// Rollout is the OPTIONAL PR-11 signed rollout config for the Management
	// capability (mode + scope; Management never executes, so its mode gates only
	// listener presence + read behavior). nil ⇒ no rollout change.
	Rollout *rollout.SignedConfig `json:"rollout,omitempty"`
}

ManagementPayload is the reviewed state a Management DP needs. It never contains a Gateway tool catalog, a Gateway credential profile, or a mutation capability.

type Manifest

type Manifest struct {
	SchemaVersion   int           `json:"schema_version"`
	Capability      Capability    `json:"capability"`
	Epoch           int64         `json:"epoch"`
	Revisions       Revisions     `json:"revisions"`
	MinDPVersion    CompatVersion `json:"minimum_dp_version"`
	PayloadType     string        `json:"payload_type"`
	PayloadVersion  int           `json:"payload_version"`
	CreatedUnixNano int64         `json:"created_unix_nano"`
	Source          SourceMeta    `json:"source"`
}

Manifest is the immutable, signed header of an MCP snapshot. Every field is part of the content hash.

type Payload

type Payload struct {
	Gateway    *GatewayPayload    `json:"gateway,omitempty"`
	Management *ManagementPayload `json:"management,omitempty"`
}

Payload carries exactly ONE capability's reviewed state. Exactly one of the two pointers is non-nil, and it MUST match the envelope's signed capability. This makes cross-capability contamination a structural rejection: a Gateway snapshot can never carry (or activate) Management state and vice versa.

type Revisions

type Revisions struct {
	// Config is the overall configuration revision — monotonic within a capability
	// and epoch, used for change detection and idempotent re-apply.
	Config uint64 `json:"config"`
	// Policy is the policy-bundle revision, tracked independently of Config.
	Policy uint64 `json:"policy"`
	// Catalog is the server-and-tool inventory revision (MCP-specific).
	Catalog uint64 `json:"catalog"`
	// Credential is the credential-profile METADATA/version only — never a secret.
	Credential uint64 `json:"credential"`
}

Revisions is the complete, independent revision tuple carried by every MCP snapshot. Each component is tracked separately so that a policy-only or catalog-only change is distinguishable, and so one generic counter can never conceal an inconsistent component revision (MCP-CPDP-001).

func (Revisions) ValidBounds

func (r Revisions) ValidBounds() bool

ValidBounds reports whether every component revision is within [0, maxRevision]. (uint64 is non-negative by construction; the upper bound guards against an absurd counter.)

type RollbackDirective

type RollbackDirective struct {
	SchemaVersion     int           `json:"schema_version"`
	Capability        Capability    `json:"capability"`
	Epoch             int64         `json:"epoch"`
	CurrentActiveHash string        `json:"current_active_hash"`
	TargetHash        string        `json:"target_hash"`
	CommandID         string        `json:"command_id"`
	MinDPVersion      CompatVersion `json:"minimum_dp_version"`
	ExpiryUnixNano    int64         `json:"expiry_unix_nano"`
	SigAlg            string        `json:"sig_alg"`
	KeyID             string        `json:"key_id"`
	Signature         string        `json:"signature"`
}

RollbackDirective is an operator-authorized, signed, hash-bound command to atomically revert a capability's active pointer to an EXACT retained signed snapshot (identified by TargetHash). It never republishes an unsigned document — it selects a snapshot the DP already holds and has re-verified. It is signed by the same CP signing key boundary as a snapshot.

func SignRollback

func SignRollback(d RollbackDirective, s Signer) (*RollbackDirective, error)

SignRollback produces a signed rollback directive. The caller has already validated the target and current hashes and holds write authority; signing does not itself verify those.

type ServerRecord

type ServerRecord struct {
	ID             string `json:"id"`
	Endpoint       string `json:"endpoint"`
	PinnedIdentity string `json:"pinned_identity"`
	Verified       bool   `json:"verified"`
	Enabled        bool   `json:"enabled"`
}

ServerRecord is a reviewed, SAFE registered-server record: endpoint + pinned identity + verification/enabled state. No credential material.

type Signer

type Signer interface {
	// KeyID returns the stable identifier of the signing key.
	KeyID() string
	// Algorithm returns the signature algorithm identifier ("ed25519").
	Algorithm() string
	// Public returns the ed25519 public key (safe to distribute as a trust root).
	Public() ed25519.PublicKey
	// Sign signs msg and returns the raw signature bytes. It never exposes the
	// private key.
	Sign(msg []byte) ([]byte, error)
}

Signer is the scoped CP-side signing interface. The private key NEVER leaves the implementation: there is no raw-private-bytes accessor. A Signer performs the signing operation and exposes only its public key, key id and algorithm — mirroring the ca.KeyProvider boundary, so an HSM/KMS-backed signer can satisfy it without ever surfacing key material.

func GenerateLocalSigner

func GenerateLocalSigner(keyID string) (Signer, error)

GenerateLocalSigner generates a fresh ed25519 key pair and returns a Signer. This is intended for tests and one-time key provisioning through a trusted boundary — a production build must NOT generate an ephemeral signing key on every restart.

func NewLocalSigner

func NewLocalSigner(keyID string, priv ed25519.PrivateKey) (Signer, error)

NewLocalSigner wraps an ed25519 private key as a Signer with the given key id. It fails closed on a malformed key or empty id — a signer that cannot sign is never silently returned.

type SourceMeta

type SourceMeta struct {
	// Kind is "publish" or "rollback".
	Kind string `json:"kind"`
	// RollbackOfHash is the retained target content hash when Kind == "rollback".
	RollbackOfHash string `json:"rollback_of_hash,omitempty"`
}

SourceMeta records a snapshot's provenance. For a rollback-produced snapshot it keeps the original target hash and rollback lineage explicit, so a reverted snapshot is never mistaken for a fresh forward publication.

type ToolRecord

type ToolRecord struct {
	Server      string `json:"server"`
	Name        string `json:"name"`
	Fingerprint string `json:"fingerprint"`
	DriftState  string `json:"drift_state"`
	Quarantined bool   `json:"quarantined"`
}

ToolRecord is a reviewed tool-catalog entry with its fingerprint and drift/quarantine state.

type TrustRoot

type TrustRoot struct {
	KeyID  string
	Alg    string
	Public ed25519.PublicKey
}

TrustRoot is a public ed25519 trust root the DP verifies against. It carries PUBLIC material only; a private signing key is never distributed to a DP.

type TrustStore

type TrustStore struct {
	// contains filtered or unexported fields
}

TrustStore is an immutable, fail-closed set of trusted public keys, keyed by key id. It supports overlapping old/new roots during rotation (multiple roots) and removal (build a new store without the key). A key carried inside a snapshot is NEVER consulted — only keys provisioned through this trusted boundary are.

func NewTrustStore

func NewTrustStore(roots []TrustRoot) (*TrustStore, error)

NewTrustStore builds an immutable trust store from a bounded set of ed25519 roots. It fails closed on: an empty set (an empty allowlist trusts nothing), a non-ed25519 algorithm, a wrong-length key (ed25519.Verify panics on a bad length, so the check is load-bearing), an empty or duplicate key id, or a root count over the hard cap. Each public key is defensively copied so the store is unaliased from caller memory.

func (*TrustStore) Len

func (t *TrustStore) Len() int

Len returns the number of trusted keys (for status/diagnostics). It never returns key material.

type ValidateInput

type ValidateInput struct {
	// ExpectCapability is the capability of the store the snapshot targets. The
	// envelope's signed capability must equal it.
	ExpectCapability Capability
	// DPVersion is the receiving DP's compatibility version.
	DPVersion CompatVersion
	// LastEpoch is the DP's last-seen trusted epoch, for a NON-mutating stale check
	// (the mutating ratchet is applied separately, only after validation passes).
	LastEpoch int64
	// Trust is the DP's trust store (public roots only).
	Trust *TrustStore
	// Limits is the validated bound set.
	Limits Limits
}

ValidateInput carries the context the whole-snapshot validator needs.

Directories

Path Synopsis
Package apply implements the Data-Plane application and recovery path for signed MCP snapshots: it prepares immutable runtime objects OFF the active request path, runs bounded self-validation and dry policy samples using the EXACT PR-6 compiler/evaluator, durably persists the validated candidate, ratchets the trusted epoch, atomically swaps the capability-local active pointer, retains the previous snapshot, and generates a hash-bound acknowledgement.
Package apply implements the Data-Plane application and recovery path for signed MCP snapshots: it prepares immutable runtime objects OFF the active request path, runs bounded self-validation and dry policy samples using the EXACT PR-6 compiler/evaluator, durably persists the validated candidate, ratchets the trusted epoch, atomically swaps the capability-local active pointer, retains the previous snapshot, and generates a hash-bound acknowledgement.
Package publication implements the Control-Plane publication, acknowledgement tracking, and rollback coordinator for signed MCP snapshots.
Package publication implements the Control-Plane publication, acknowledgement tracking, and rollback coordinator for signed MCP snapshots.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL