SPB Git

Repository Public

envelope.go 4.7 KB 138 lines go

1// Package protocol defines the agent wire protocol shared by the agent, the2// ingest service and the orchestrator. Version 1.3package protocol45import (6	"crypto/ed25519"7	"crypto/rand"8	"encoding/base64"9	"encoding/json"10	"errors"11	"fmt"12	"time"13)1415const Version = 11617// MaxCommandLifetime bounds expires_at - issued_at; agents refuse longer-lived commands.18const MaxCommandLifetime = 120 * time.Second1920// MaxClockSkew is tolerated between orchestrator and agent clocks.21const MaxClockSkew = 30 * time.Second2223// Command is the signed instruction. It is serialized once by the24// orchestrator; the exact bytes are signed and transported unchanged25// (SignedCommand.Payload), so no canonicalization is involved.26type Command struct {27	V         int             `json:"v"`28	ID        string          `json:"id"` // agent_commands.id29	ActionID  string          `json:"action_id"`30	AgentID   string          `json:"agent_id"` // recipient: an agent executes only its own commands31	NodeID    string          `json:"node_id"`32	Type      string          `json:"type"`33	Params    json.RawMessage `json:"params"`34	TimeoutS  int             `json:"timeout_s"`35	IssuedAt  time.Time       `json:"issued_at"`36	ExpiresAt time.Time       `json:"expires_at"`37	Nonce     string          `json:"nonce"`38}3940// SignedCommand is what travels through the ingest service to the agent.41type SignedCommand struct {42	KeyID     string `json:"key_id"`43	Payload   []byte `json:"payload"`   // JSON of Command, exactly as signed44	Signature []byte `json:"signature"` // Ed25519 over domain || payload45}4647// The signature covers a domain-separation prefix so a command signature can48// never be confused with any other signature made by the same key.49const sigDomain = "mcc-agent-command-v1\x00"5051func signingInput(payload []byte) []byte {52	return append([]byte(sigDomain), payload...)53}5455func NewNonce() string {56	b := make([]byte, 16)57	if _, err := rand.Read(b); err != nil {58		panic("protocol: entropy source failed: " + err.Error())59	}60	return base64.RawURLEncoding.EncodeToString(b)61}6263// Sign serializes and signs a command.64func Sign(priv ed25519.PrivateKey, keyID string, c Command) (SignedCommand, error) {65	if c.V != Version {66		return SignedCommand{}, fmt.Errorf("protocol: unsupported version %d", c.V)67	}68	if c.Nonce == "" || c.ID == "" || c.AgentID == "" || c.Type == "" {69		return SignedCommand{}, errors.New("protocol: incomplete command")70	}71	if d := c.ExpiresAt.Sub(c.IssuedAt); d <= 0 || d > MaxCommandLifetime {72		return SignedCommand{}, fmt.Errorf("protocol: lifetime %s out of bounds", d)73	}74	payload, err := json.Marshal(c)75	if err != nil {76		return SignedCommand{}, err77	}78	return SignedCommand{KeyID: keyID, Payload: payload, Signature: ed25519.Sign(priv, signingInput(payload))}, nil79}8081// Verification failures. Agents report the reason and never execute.82var (83	ErrBadSignature = errors.New("bad signature")84	ErrUnknownKey   = errors.New("unknown signing key")85	ErrWrongAgent   = errors.New("command addressed to another agent")86	ErrExpired      = errors.New("command expired")87	ErrNotYetValid  = errors.New("command issued in the future")88	ErrLifetime     = errors.New("command lifetime too long")89	ErrReplay       = errors.New("command nonce already seen")90	ErrMalformed    = errors.New("malformed command")91)9293// NonceStore remembers nonces until their command has expired. Remember94// must be atomic and durable: it returns false when the nonce was already present.95type NonceStore interface {96	Remember(nonce string, until time.Time) (fresh bool, err error)97}9899// Verify authenticates a signed command for the given agent. It checks, in100// order: key, signature, shape, recipient, validity window, replay. Only a101// command that passes every check is returned.102func Verify(sc SignedCommand, keys map[string]ed25519.PublicKey, agentID string, now time.Time, nonces NonceStore) (*Command, error) {103	pub, ok := keys[sc.KeyID]104	if !ok || len(pub) != ed25519.PublicKeySize {105		return nil, ErrUnknownKey106	}107	if !ed25519.Verify(pub, signingInput(sc.Payload), sc.Signature) {108		return nil, ErrBadSignature109	}110	var c Command111	if err := json.Unmarshal(sc.Payload, &c); err != nil {112		return nil, ErrMalformed113	}114	if c.V != Version || c.ID == "" || c.Type == "" || c.Nonce == "" || c.TimeoutS <= 0 {115		return nil, ErrMalformed116	}117	if c.AgentID != agentID {118		return nil, ErrWrongAgent119	}120	if d := c.ExpiresAt.Sub(c.IssuedAt); d <= 0 || d > MaxCommandLifetime {121		return nil, ErrLifetime122	}123	if now.After(c.ExpiresAt) {124		return nil, ErrExpired125	}126	if c.IssuedAt.After(now.Add(MaxClockSkew)) {127		return nil, ErrNotYetValid128	}129	fresh, err := nonces.Remember(c.Nonce, c.ExpiresAt.Add(MaxClockSkew))130	if err != nil {131		return nil, fmt.Errorf("nonce store: %w", err)132	}133	if !fresh {134		return nil, ErrReplay135	}136	return &c, nil137}138
Files main
Menu

Theme