Skip to content

egress, router: native RFC 9421 signing, signed DHT ingress docs, and declarative transforms - #998

Open
aojea wants to merge 2 commits into
google:mainfrom
aojea:web_bot_auth_agentmesh
Open

aojea wants to merge 2 commits into
google:mainfrom
aojea:web_bot_auth_agentmesh

Conversation

@aojea

@aojea aojea commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds three zero-dependency native primitives to agentmesh-node and agentmesh-router so outbound signed HTTP protocols (Web Bot Auth, UCP 2026-08-25 REST & MCP, and signed APIs) run end-to-end without external sidecars or new go.mod dependencies:

  1. Native RFC 9421 + RFC 9530 Outbound Signing (EgressDestination.signing, internal/httpsig):

    • Pure Go standard-library ES256 (raw 64-byte r||s) and Ed25519 signing, RFC 9530 Content-Digest, RFC 7638 JWK thumbprints, multi-key PEM bundle rotation (--secrets-dir), and Web Bot Auth (tag: "web-bot-auth", created/expires/nonce, Signature-Agent).
    • Runs in egressSigningRoundTripper after content inspection (ModelArmor / ext_proc), declarative transforms, and CredentialBroker, stripping caller-spoofed Signature* / Content-Digest headers and failing closed (413 on oversized bodies, 502 + signing_failed metric on signing errors).
  2. Generic Signed Read-Only Ingress Documents in Kademlia DHT (SignedIngressDocuments):

    • ConfigMap-style read-only documents published under PeerKey(peerID) in DirectoryProvide / PeerRecord, signed with the owning node's Ed25519 libp2p identity key (peerID.ExtractPublicKey()).
    • Verified offline on Provide, Kademlia Place, FindPeer (LookupPeerDocuments), and before HTTP serving, with monotonic sign_time rollback protection and Datalog policy gating (granted_ingress_documents(true) derived automatically for destinations with publish_public_key: true or ingress_documents, plus PolicyRole.allow_ingress_documents).
    • Routers serve GET/HEAD /ingress/<peer_id>/<path> directly from the Kademlia directory (zero inbound stream opened to the PEP node), enforcing a strict non-executable media type allowlist (application/json, application/*+json, text/plain), header allowlist, X-Content-Type-Options: nosniff, Content-Security-Policy: default-src 'none'; sandbox, IP rate limiting, and banned-peer 404.
    • When signing.publish_public_key: true, agentmesh-node auto-publishes .well-known/jwks.json and pre-signed .well-known/http-message-signatures-directory. Custom templated documents (EgressDestination.ingress_documents, e.g., .well-known/ucp-profile.json) expand {{ingress_url}}, {{peer_id}}, {{destination}}, {{key_id}}, {{public_jwk}}, and {{public_jwks}}.
  3. Stateless Declarative Egress Transforms (EgressDestination.transforms):

    • Applies header (set_headers, default_headers) and JSON object field (set_json) mutations filtered by HTTP method, path prefix, and json_equals before credential brokering and signing. Rejects protected headers (Authorization, Cookie, Host, Signature*, Content-Digest, X-Mesh-*) at policy validation.
  4. Example, Live Demo Video, & Site Docs:

    • Minimal zero-sidecar UCP/WBA policy example in development/examples/egress-commerce/ (policy.json, run.sh, record.sh), keeping stateful PAP 1.0 (which requires per-user OAuth token storage and browser /oauth/callback) clearly separated under development/examples/egress-commerce/external-pap/.
    • Recorded live demo video (site/static/demo-signed-egress.mp4) and updated site docs (site/content/docs/use-cases/signed-egress-commerce.md, site/content/docs/guides/egress-destinations.md, site/content/docs/guides/external-ingress.md).
    • Regenerated Go, JS, and Python protobuf bindings from api/agentmesh.proto.

Relates to #990.

Verification

  • Dependencies: git diff go.mod go.sum is empty (0 new dependencies).
  • Build & Lint: make, go vet ./..., gofmt, golangci-lint run (0 issues), ./hack/verify-secrets.sh, ./hack/gen-sdk-proto.sh, go run ./hack/gen-sdk-docs -check sdk site/content/docs.
  • Unit & Integration Tests (-race):
    • api/ingress_documents_test.go
    • internal/httpsig/httpsig_test.go
    • internal/node/egress_signing_test.go
    • internal/router/ingress_documents_test.go (2-router Kademlia replication + HTTP ingress)
    • tests/integration/egress_signing_ingress_docs_test.go (standalone + PEP + peer LookupPeerDocuments + verifying mock merchant, 3/3 PASS at ~0.65s)
    • development/examples/egress-commerce/external-pap/...
  • Live End-to-End Verification (flowers.ucpsandbox.com over Cloudflare HTTPS tunnel, zero sidecars):
    • GET /ingress/<peer_id>/.well-known/{jwks.json,http-message-signatures-directory,ucp-profile.json} → HTTP/2 200 directly from router DHT with Signature, Content-Digest, nosniff, and CSP: default-src 'none'; sandbox.
    • POST /egress/flowers.ucpsandbox.com/mcp (search_catalog + create_checkout) → 200 OK (24 live products + live continue_url).
    • POST /egress/flowers.ucpsandbox.com/ucp/checkout-sessions → HTTP/1.1 201 Created.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces native Signed Egress capabilities to Agent Mesh, implementing RFC 9421 HTTP Message Signatures, RFC 9530 Content-Digest, and signed read-only Kademlia DHT ingress documents with zero external sidecars. Feedback on the changes highlights a compilation error in internal/httpsig/httpsig.go where ecdsa.PublicKey lacks a Bytes() method, a peer ID comparison style guide violation in api/ingress_documents.go, a swallowed error from rand.Read in internal/node/egress_transform.go, and missing peer ID identifiers in log lines in internal/node/egress_signing.go and internal/node/node.go.

Comment thread internal/httpsig/httpsig.go Resolved
Comment thread api/ingress_documents.go Outdated
Comment on lines +295 to +297
if bundle.GetPeerId() != expectedPeer.String() {
return nil, fmt.Errorf("ingress document bundle peer_id %q does not match %s", bundle.GetPeerId(), expectedPeer)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The bundle.GetPeerId() is a raw string from protobuf, which might not be in the canonical base58 form (e.g., it could be in CIDv1 base32 form). Comparing it directly with expectedPeer.String() violates Rule 1.5 of the style guide, which requires decoding both sides and comparing peer.ID values.

	bundlePeer, err := peer.Decode(bundle.GetPeerId())
	if err != nil {
		return nil, fmt.Errorf("invalid peer_id in bundle: %w", err)
	}
	if bundlePeer != expectedPeer {
		return nil, fmt.Errorf("ingress document bundle peer_id %q does not match %s", bundle.GetPeerId(), expectedPeer)
	}
References
  1. Peer IDs must be canonicalized at the boundary. Raw string compared for identity must decode both sides and compare peer.ID values. (link)

Comment thread internal/node/egress_transform.go Outdated

func newUUIDv4() string {
var b [16]byte
_, _ = rand.Read(b[:])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The error from rand.Read is swallowed here. According to Rule 6.3 of the style guide, errors must not be swallowed. Since a failure of crypto/rand is a catastrophic system failure, panicking is appropriate.

Suggested change
_, _ = rand.Read(b[:])
if _, err := rand.Read(b[:]); err != nil {
panic(fmt.Sprintf("crypto/rand failed: %v", err))
}
References
  1. Errors are not swallowed. Flag the bare form of swallowed errors. (link)

Comment thread internal/node/egress_signing.go Outdated
Comment on lines +348 to +351
logger.Warnf("[Directory] Truncating ingress documents from %d to max %d", len(out), api.MaxIngressDocumentsPerPeer)
out = out[:api.MaxIngressDocumentsPerPeer]
}
return out

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This log line does not carry the peer ID identifier, which violates Rule 6.4 of the style guide. Log lines about a peer must name the peer ID.

	if len(out) > api.MaxIngressDocumentsPerPeer {
		peerID := "unknown"
		if n.Host != nil {
			peerID = n.Host.ID().String()
		}
		logger.Warnf("[Directory] %s: truncating ingress documents from %d to max %d", peerID, len(out), api.MaxIngressDocumentsPerPeer)
		out = out[:api.MaxIngressDocumentsPerPeer]
	}
References
  1. Log lines carry the identifier. A line about a peer names the peer ID. (link)

Comment thread internal/node/node.go
Comment on lines +889 to +891
if docErr != nil {
logger.Warnf("[Directory] Building signed ingress documents: %v", docErr)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This log line does not carry the peer ID identifier, which violates Rule 6.4 of the style guide. Log lines about a peer must name the peer ID.

Suggested change
if docErr != nil {
logger.Warnf("[Directory] Building signed ingress documents: %v", docErr)
}
if docErr != nil {
logger.Warnf("[Directory] %s: building signed ingress documents: %v", n.Host.ID(), docErr)
}
References
  1. Log lines carry the identifier. A line about a peer names the peer ID. (link)

… declarative transforms

Adds three zero-dependency native primitives for signed outbound egress (Web Bot Auth, UCP REST & MCP, and signed APIs) without external sidecars:

- Pure-stdlib RFC 9421 + RFC 9530 HTTP message signing (internal/httpsig) wired onto EgressDestination.signing (ES256 P-256 and Ed25519 PEM bundles from --secrets-dir, multi-key rotation, Web Bot Auth tag + Signature-Agent).
- Generic signed read-only ingress documents (SignedIngressDocuments) published under PeerKey into the Kademlia directory, verified offline via peerID.ExtractPublicKey() with rollback protection, strict non-executable media type allowlist, nosniff + CSP sandbox headers, and served directly by routers at GET/HEAD /ingress/<peer_id>/<path> with zero inbound stream to the PEP.
- Stateless declarative EgressTransform rules (headers + JSON body mutations) applied after inspection and before credential brokering and signing.
- Trimmed live UCP/WBA example (zero Go plugin binary), external PAP 1.0 reference packages, recorded site demo video (site/static/demo-signed-egress.mp4), and updated site documentation.
@aojea
aojea force-pushed the web_bot_auth_agentmesh branch from e50682c to e15a896 Compare December 1, 2026 07:47
… egress transform, and external-pap audit findings
@aojea
aojea force-pushed the web_bot_auth_agentmesh branch from e15a896 to 003d1af Compare December 1, 2026 09:37
@aojea

aojea commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (11db4a69, preserving directory answer frame-bounding and regenerating Go/JS/Python bindings with protoc-gen-es v2.17.0), resolved the review comments, and completed a three-part adversarial RFC & security review (RFC 9421 / 8941 / 9530 / WBA / UCP, Agent Mesh Zero-Trust & Kademlia DHT, and OAuth 2.1 / DPoP / PAP 1.0) in 003d1afc:

PR Review Comments Addressed

  • api/ingress_documents.go: canonicalized bundle.GetPeerId() via peer.Decode before comparing against expectedPeer.
  • internal/node/egress_transform.go: newUUIDv4() now checks and propagates crypto/rand.Read errors.
  • internal/node/egress_signing.go & internal/node/node.go: added peer_id context to truncation and directory announcement warning logs.
  • Note on internal/httpsig/httpsig.go ((*ecdsa.PublicKey).Bytes()): kept k.PublicKey.Bytes() and ecdsa.ParseUncompressedPublicKey because this module targets Go 1.26 (go.mod) and golangci-lint SA1019 flags elliptic.Marshal as deprecated.

RFC 9421 / 8941 / 9530 / WBA / UCP Hardening (internal/httpsig, development/examples/egress-commerce/policy.json)

  • Strict RFC 8941 parser & serializer (internal/httpsig/sfv.go): replaced ad-hoc string splitting with a full RFC 8941 Dictionary/Inner-List/String/Byte-Sequence parser and serializer; closes parameter smuggling via quoted ;, enables multi-signature & multi-line Signature-Input/Signature headers, rejects uppercase/duplicate/unknown/@signature-params components and unsupported component params, and formats RFC 8941 strings safely without %q.
  • Directory response signatures: SignDirectoryResponse now covers ("@authority";req "repr-digest") with ;alg=... and normalized authority (VerifyDirectoryResponse added and verified in integration tests); HEAD omits Content-Digest per RFC 9530 §6.3 while preserving Repr-Digest.
  • Verification & interop: added alg enforcement (both Signature-Input and JWK.alg), strict timestamp bounds (expires<=0, expires<=created, future created, half-open expiry, WBA profile checks), kid-less WBA JWK thumbprint matching, multi-algorithm/multi-line RFC 9530 Content-Digest verification (sha-256/sha-512), @authority default-port & IPv6 normalization, case-sensitive @method, empty @query binding, empty-body POST Content-Digest, strict 32-octet EC P-256 coordinates, low-S ECDSA signing, and 64-byte WBA nonces.
  • UCP 2026-08-25 policy: removed deprecated signing_keys, added checkout spec/schema, and scoped Idempotency-Key injection to mutating HTTP methods.

Zero-Trust, DHT Anti-Rollback & Egress Hardening (api, internal/router, internal/node)

  • Persistent monotonic anti-rollback watermarks (internal/router/directory_store.go): docWatermarks survives null-overwrites (Documents: nil), withdrawals, bans, and shorter directory record TTLs until bundle expiry; rejects equal-sign_time payload collisions; bounds store size.
  • PeerKey & ban enforcement (internal/router/directory.go, ingress.go, router.go): validates api.ServiceOfRecord and bannedPeers on placed records (closing PeerKey eclipse DoS), filters banned peers on lookup/FindPeer/node LookupPeerDocuments, merges multi-router FindPeer documents, re-verifies live mesh policy on serve and syncPolicy, caps cache-control (max-age<=300, no immutable/s-maxage), rejects untrimmed content_type/uppercase header keys, and negative-caches external 404 misses without triggering refederateIfStale().
  • Egress transform & signing pipeline (internal/node/): strips Connection-nominated hop-by-hop headers and caller Signature-Agent before transforms/signing, decompresses/checks Content-Encoding for transforms too, parses JSON strictly (UseNumber(), rejects duplicate keys, JSON-RPC batch arrays, and trailing tokens with 400), rejects // paths on /libp2p-http, JSON-escapes string template vars, fails closed on missing {{ingress_url}}, deterministically sorts multi-router ingress URLs, and hot-reloads rotated PEM files on disk.
  • Added IngressDocumentPolicies to api.BaselineSources and updated SDK baseline Datalog artifacts.

External PAP 1.0 / OAuth 2.1 / DPoP Adapter (development/examples/egress-commerce/external-pap/)

  • Unconditionally enforces protected_resources exact-origin binding, HTTPS-only endpoints by default, SSRF-safe dialing, and no automatic redirect following (ErrUseLastResponse).
  • Fails closed unless both HopToken and AuthenticateCallback (anti-login-CSRF binding on /oauth/callback) are configured; adds RFC 9207 iss and duplicate-param rejection, per-(principal, origin, isToken) DPoP nonces, singleflight refresh coalescing, invalid_grant eviction, RFC 7009 revocation on re-consent, refusal of DPoP-to-Bearer downgrades, per-task sid isolation, and sanitized callback responses with security headers.

@aojea

aojea commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements signed ingress documents for peer records, enabling routers to serve static documents (e.g., JWKS, UCP profiles) directly from the Kademlia DHT without requiring inbound streams to the node. It introduces RFC 9421 HTTP message signing, declarative egress transforms for header and JSON body mutations, and robust anti-rollback watermarks for ingress documents. The review feedback identified a compilation error in the record store logic, suggested more idiomatic hex formatting for UUID generation, and recommended expanding the SSRF blocklist to include Azure metadata IPs.

var oldestExp time.Time
for k, existing := range s.docWatermarks {
if oldestKey == "" || existing.expireTime.Before(oldestExp) {
oldestKey = k

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The variable oldExp is undefined in this scope and will cause a compilation error. It should be oldestExp instead.

				if oldestKey == "" || existing.expireTime.Before(oldestExp) {

}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since %x on a slice of bytes already formats it as a hex string of the exact length (e.g., 4 bytes becomes 8 hex characters), the width modifiers (like 08, 04, 12) are redundant. Using a simpler format string is more idiomatic in Go.

Suggested change
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil

Comment thread api/ingress.go
Comment on lines +270 to +271
if addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || addr.IsUnspecified() ||
addr == netip.MustParseAddr("100.100.100.200") || addr == netip.MustParseAddr("fd00:ec2::254") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

To prevent SSRF attacks against Azure Instance Metadata Service (IMDS), consider adding the Azure metadata IP 168.63.129.16 to the forbidden IP list. Since it is a public IP owned by Microsoft, it is not covered by IsPrivate() or IsLinkLocalUnicast().

Suggested change
if addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || addr.IsUnspecified() ||
addr == netip.MustParseAddr("100.100.100.200") || addr == netip.MustParseAddr("fd00:ec2::254") {
if addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || addr.IsUnspecified() ||
addr == netip.MustParseAddr("100.100.100.200") || addr == netip.MustParseAddr("fd00:ec2::254") ||
addr == netip.MustParseAddr("168.63.129.16") {

@frostyhand frostyhand left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, it's a big step up from the ext_proc example. I focused my review on Web Bot Auth conformance, since that's the part I know well, and checked it against draft-ietf-webbotauth-httpsig-protocol-01.

What I ran on 003d1af

  • go test -race for internal/httpsig, internal/node, api, internal/router and the signing/ingress integration tests: all pass.
  • Signed a GET and a POST with httpsig.SignRequest using the RFC 9421 B.1.4 Ed25519 key, then verified both with Cloudflare's published verifier (web-bot-auth 0.2.0 from npm). Both verify, including content-digest and content-type on the POST.
  • keyid equals the draft's poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U, ComputeContentDigest matches the draft's directory vector, and Signature-Agent uses the dictionary form keyed to the label. The body the signer hashes is the body that's sent, including gzip passthrough when no transform runs.

So request signing looks right to me. Three things on the edges:

1. The directory response signature covers repr-digest, but -01 requires content-digest

SignDirectoryResponse signs ("@authority";req "repr-digest"). Appendix B of -01 says the directory server MUST cover @authority;req and content-digest, and a verifier MUST check Content-Digest against the body. A verifier written to the draft won't accept this signature, even though the bytes are right.

I get why you picked Repr-Digest (HEAD). A simpler fix is to sign content-digest and, on HEAD, drop Signature and Signature-Input along with Content-Digest in the router. Verifiers fetch the directory with GET, so HEAD loses nothing.

Smaller point: -01 recommends one signature per key in the directory. Only primaryKey signs today, so during a rotation the second key has no possession proof.

2. Do peer-scoped directories need the authority binding at all?

The directory lives at /ingress/<peer_id>/.well-known/http-message-signatures-directory on a shared router. -01 only applies the domain binding (Appendix B) when the Signature-Agent value is the registered well-known URI, at the root of the origin. For a path under /ingress/<peer_id>/, a conformant verifier resolves the URL as a plain JWK Set and ignores the binding.

The other side of this: any peer on a router can publish a pre-signed response bound to that router's @authority, because @authority doesn't cover the path. A verifier that recognises the directory by its path suffix (the draft lets verifiers "recognise the shape of the URL") would then credit the router's domain for every tenant's keys. I'd consider skipping SignDirectoryResponse for peer-scoped paths, and maybe not using .well-known inside the /ingress/<peer_id>/ prefix at all. Happy to be told the router is always single-operator and this is fine.

3. VerifyRequest is stricter than -01 and rejects the draft's own test vector

validateWebBotAuthRequirements:

  • The 24h lifetime cap is a hard error, but -01 only RECOMMENDS 24h. The draft's dictionary-form Ed25519 vector (expires=4889289600) fails with lifetime 3153600000s exceeds maximum 86400s. Re-signing the same base with a 1h expiry verifies.
  • It requires @authority, while -01 says agents MUST cover "at least one of" @authority or @target-uri. A valid @target-uri-only signature fails with must cover "@authority".

Since the verifier is only used in tests right now, this is low impact. Making the cap an option, and accepting either component, would let the draft's vectors run as regression tests. I have the dictionary, legacy and signed-directory vectors from -01 Appendix E wired up locally against internal/httpsig and can send them as a follow-up PR once this lands, if that's useful.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants