Skip to content

api, controlplane, node, envoy: attest verified OIDC claims as claim() Biscuit facts - #953

Merged
aojea merged 4 commits into
google:mainfrom
aojea:attested-oidc-claims
Nov 26, 2026
Merged

aojea merged 4 commits into
google:mainfrom
aojea:attested-oidc-claims

Conversation

@aojea

@aojea aojea commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds first-class IdP-verified claim(key, value) Biscuit authority facts, structured PolicyBinding.claims matching, node task-scope floors (require_task_scope, max_task_ttl), and tamper-proof PEP provenance headers (X-Mesh-Claims, X-Mesh-Labels, X-Mesh-Actor-Node, X-Mesh-Origin).

This allows operators to enforce device posture, multi-issuer scoping (iss), hardware-backed MFA (amr), and workload/sandbox isolation directly in versioned PolicyConfig and standard Biscuit Datalog—without overloading node-declared label(k, v) or adding control-plane CLI claim flags.

Key Changes

1. Schema & First-Class claim(k, v) Predicate (api/, sdk/)

  • Added PolicyBinding.claims (map<string, string>) and PolicyConfig.attested_claims (repeated string) to api/agentmesh.proto and regenerated Go, TypeScript, and Python bindings.
  • Introduced api.FactClaim = "claim" structurally separate from node-declared label(k, v), so enrolling nodes can never spoof IdP posture claims even when PolicyRole.allowed_labels contains "*".
  • Always allows matching "iss" in PolicyBinding.claims for cross-issuer protection in multi-issuer meshes.
  • Supports top-level/URI keys, dot-separated nested JSON paths, scalar strings/booleans, and string arrays (such as amr, emitting one claim() fact per distinct element).
  • Enforces initial claim bounds (api.MaxAttestedClaims = 16 distinct claim paths rejected with 400 at POST /policies; api.MaxValuesPerClaim = 16 values per claim omitted fail-closed with a warning) and includes them in the control-plane authorizer fact budget.
  • Compiles PolicyBinding.claims into standard cross-language Biscuit Datalog rules distributed over GET /policies.

2. Storage & Control Plane (internal/storage/, internal/controlplane/, internal/identity/)

  • Migration v22 adds role_bindings.claims_json and policy_attested_claims, supporting multiple bindings per role for OR-of-AND claim profiles (SavePolicyConfig / GetAttestedClaims).
  • Extracts and mints claim(k, v) facts onto Member and Delegated Session Biscuits across /register, /refresh (re-attesting fresh JWTs to drop degraded posture immediately and applying updated attested_claims from stored ClaimsJSON), /token/exchange, and /oauth/token.
  • Propagates mesh_claims (scalar string or array for multi-valued claims) and mesh_labels in outbound /sts/token ES256 border JWTs and structured Border Crossing logs.

3. Node Attenuation & Tamper-Proof Provenance (internal/node/, internal/envoy/)

  • Added attenuation.require_task_scope and attenuation.max_task_ttl alongside existing standard Datalog rules/checks/policies over claim().
  • Stripped caller-supplied X-Mesh-* and X-Peer-Id headers across inbound libp2p streams, router ingress, and Envoy ext_authz (headers_to_remove) / ext_proc (remove_headers), stamping verified X-Mesh-Claims, X-Mesh-Labels, X-Mesh-Actor-Node, and X-Mesh-Origin (mesh-remote, mesh-external-ingress, mesh-gateway).
  • Forwarded X-Mesh-Claims, X-Mesh-Labels, and X-Mesh-Actor-Node when EgressDestination.forward_context is enabled.

4. Documentation, Tests & Loopback Demo

  • Added unit and integration coverage: api/claims_test.go, internal/controlplane/claims_policy_test.go, internal/node/compliance_test.go, internal/envoy/envoy_test.go, internal/storage/round_trip_test.go, and tests/integration/posture_isolation_test.go.
  • Added self-contained, zero-Docker loopback demo in development/examples/device-posture-isolation/ running real agentmesh-one and agentmesh-node binaries with dual local RS256 OIDC issuers (15 assertions across 5 acts).
  • Updated reference docs and added site/content/docs/guides/enterprise-posture-compliance.md.

Verification

  • go.mod / go.sum: unchanged (0 new dependencies).
  • make build: all 8 binaries build cleanly.
  • golangci-lint run ./...: 0 issues; gofmt -l: clean; ./hack/verify-secrets.sh: passed.
  • go test -race: all unit, SDK (sdk/meshnet), and integration suites pass.
  • ./development/examples/device-posture-isolation/run.sh: 15 passed, 0 failed.

…) Biscuit facts

Add first-class IdP-verified claim(key, value) Biscuit authority facts,
structured PolicyBinding.claims matching, node task-scope floors, and
tamper-proof PEP provenance headers so deployments can enforce device
posture, issuer scoping, and workload isolation without overloading
node-declared labels or adding control-plane CLI claim flags.

- api/agentmesh.proto: add PolicyBinding.claims (map<string, string>)
  and PolicyConfig.attested_claims (repeated string), and regenerate Go,
  TypeScript, and Python proto bindings.
- api/claims.go, api/datalog.go, api/policy_rules.go: introduce
  FactClaim ("claim") structurally isolated from node-declared
  label(k, v), always allow matching "iss" in PolicyBinding.claims,
  support top-level/URI keys, dotted nested JSON paths, and string
  arrays (such as amr), and enforce bounded claim counts
  (MaxAttestedClaims = 16, MaxValuesPerClaim = 16).
- internal/storage: migration v22 adds role_bindings.claims_json and
  policy_attested_claims, preserving multiple bindings per role for
  OR-of-AND claim profiles.
- internal/controlplane, internal/identity: extract and mint claim(k, v)
  facts on Member and Delegated Session Biscuits across /register,
  /refresh (including dynamic policy updates from stored ClaimsJSON and
  posture downgrade revocation), /token/exchange, and /oauth/token;
  propagate mesh_claims and mesh_labels in outbound /sts/token JWTs.
- internal/node, internal/envoy: add attenuation.require_task_scope and
  attenuation.max_task_ttl alongside Datalog rules/checks/policies over
  claim(); strip caller-supplied X-Mesh-* and X-Peer-Id headers across
  libp2p, router ingress, and Envoy ext_authz/ext_proc, stamping
  verified X-Mesh-Claims, X-Mesh-Labels, X-Mesh-Actor-Node, and
  X-Mesh-Origin.
- development/examples/device-posture-isolation, site/content/docs,
  tests: add unit/integration coverage, documentation, and a
  self-contained loopback demo with dual RS256 OIDC issuers.

@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 comprehensive support for enterprise device posture attestation, workload isolation, and gateway provenance by extracting verified OIDC JWT claims into first-class claim(k, v) Biscuit facts and enforcing them via node-level attenuation (require_task_scope and max_task_ttl). The review feedback highlights a critical security bypass in the node middleware's expiration check, a style guide violation where an error was swallowed in resolveRoles, and an opportunity to improve OIDC claim extraction robustness by supporting numeric types.

Comment on lines +330 to +335
effectiveExp := api.EffectiveTARExpiration(authExp, taskRules)
if remaining := time.Until(effectiveExp); remaining > n.nodeConfig.MaxTaskTTL {
reason := fmt.Sprintf("credential remaining lifetime %s exceeds max_task_ttl %s", remaining.Round(time.Second), n.nodeConfig.MaxTaskTTL)
logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", reason)...)
return nil, errors.New(reason)
}

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-high high

If api.EffectiveTARExpiration returns a zero time (e.g., due to missing or invalid rule expirations), time.Until(effectiveExp) will return a large negative duration. This negative duration will bypass the remaining > n.nodeConfig.MaxTaskTTL check, effectively allowing credentials with invalid or missing expirations to bypass the max_task_ttl restriction.

Adding an explicit check for effectiveExp.IsZero() prevents this potential security bypass.

			effectiveExp := api.EffectiveTARExpiration(authExp, taskRules)
			if effectiveExp.IsZero() {
				logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", "effective credential expiration is zero")...)
				return nil, fmt.Errorf("effective credential expiration is zero")
			}
			if remaining := time.Until(effectiveExp); remaining > n.nodeConfig.MaxTaskTTL {
				reason := fmt.Sprintf("credential remaining lifetime %s exceeds max_task_ttl %s", remaining.Round(time.Second), n.nodeConfig.MaxTaskTTL)
				logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", reason)...)
				return nil, errors.New(reason)
			}

Comment thread api/claims.go
Comment on lines +230 to +269
switch v := raw.(type) {
case string:
if v == "" {
return nil, fmt.Sprintf("claim %q is empty; omitted", path)
}
rawStrings = []string{v}
case bool:
if v {
rawStrings = []string{"true"}
} else {
rawStrings = []string{"false"}
}
case []string:
if len(v) > MaxValuesPerClaim {
return nil, fmt.Sprintf("claim %q has %d values (max %d); omitted", path, len(v), MaxValuesPerClaim)
}
rawStrings = v
case []any:
if len(v) > MaxValuesPerClaim {
return nil, fmt.Sprintf("claim %q has %d values (max %d); omitted", path, len(v), MaxValuesPerClaim)
}
for _, elem := range v {
switch item := elem.(type) {
case string:
if item != "" {
rawStrings = append(rawStrings, item)
}
case bool:
if item {
rawStrings = append(rawStrings, "true")
} else {
rawStrings = append(rawStrings, "false")
}
default:
return nil, fmt.Sprintf("claim %q contains non-scalar element; omitted", path)
}
}
default:
return nil, fmt.Sprintf("claim %q is not a string, boolean, or scalar array; omitted", path)
}

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

OIDC providers frequently emit numeric claims (such as exp, iat, auth_time, or custom numeric levels/IDs). Currently, extractClaimValues only supports string, bool, and arrays of those types, causing any numeric claim to be silently omitted with a warning.

Supporting numeric types (like float64, int, int64) by formatting them as strings will make the claim attestation much more robust and compatible with standard OIDC claims.

	switch v := raw.(type) {
	case string:
		if v == "" {
			return nil, fmt.Sprintf("claim %q is empty; omitted", path)
		}
		rawStrings = []string{v}
	case bool:
		if v {
			rawStrings = []string{"true"}
		} else {
			rawStrings = []string{"false"}
		}
	case float64:
		rawStrings = []string{fmt.Sprintf("%v", v)}
	case int:
		rawStrings = []string{fmt.Sprintf("%v", v)}
	case int64:
		rawStrings = []string{fmt.Sprintf("%v", v)}
	case []string:
		if len(v) > MaxValuesPerClaim {
			return nil, fmt.Sprintf("claim %q has %d values (max %d); omitted", path, len(v), MaxValuesPerClaim)
		}
		rawStrings = v
	case []any:
		if len(v) > MaxValuesPerClaim {
			return nil, fmt.Sprintf("claim %q has %d values (max %d); omitted", path, len(v), MaxValuesPerClaim)
		}
		for _, elem := range v {
			switch item := elem.(type) {
			case string:
				if item != "" {
					rawStrings = append(rawStrings, item)
				}
			case bool:
				if item {
					rawStrings = append(rawStrings, "true")
				} else {
					rawStrings = append(rawStrings, "false")
				}
			case float64, int, int64:
				rawStrings = append(rawStrings, fmt.Sprintf("%v", item))
			default:
				return nil, fmt.Sprintf("claim %q contains non-scalar element; omitted", path)
			}
		}
	default:
		return nil, fmt.Sprintf("claim %q is not a string, boolean, number, or scalar array; omitted", path)
	}

Comment thread internal/controlplane/server.go Outdated

// Extract only the JWT claim paths referenced by bindings so PolicyBinding.claims
// (including "iss") is enforced identically at mint time and in Datalog rules.
bindingClaimPaths, _ := api.CollectPolicyClaimPaths(bindings, 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

Ignoring the error returned by api.CollectPolicyClaimPaths with a blank identifier violates the repository style guide section 6.3 ('Errors are not swallowed'). Swallowing this error can lead to silent failures where roles are not resolved correctly for a peer, making troubleshooting extremely difficult.

Logging a warning when CollectPolicyClaimPaths fails will greatly improve the auditability and maintainability of the control plane.

Suggested change
bindingClaimPaths, _ := api.CollectPolicyClaimPaths(bindings, nil)
bindingClaimPaths, err := api.CollectPolicyClaimPaths(bindings, nil)
if err != nil {
logger.Warnf("Failed to collect policy claim paths in resolveRoles for peer %s: %v", peerID, err)
}
References
  1. Errors must not be swallowed using blank identifiers. Swallowing errors makes debugging difficult and violates the auditable behavior guidelines. (link)

…voy filter header chaining

- internal/envoy: preserve caller-input routing/auth headers
  (X-Mesh-Target-Service, X-Mesh-Authentication, X-Mesh-Required-Labels)
  in spoofedMeshHeadersToRemove so Envoy ext_authz -> ext_proc ->
  agentmesh-node filter chains retain target resolution while still
  stripping all spoofed provenance/identity/task X-Mesh-* headers and
  X-Peer-Id (fixes tests/e2e/standalone.bats).
- internal/node: fail closed when api.EffectiveTARExpiration returns a
  zero time before checking max_task_ttl in authorizeWithRules.
- internal/controlplane: log errors and claim-extraction warnings from
  CollectPolicyClaimPaths / ExtractVerifiedClaims in resolveRoles
  instead of discarding them.
- api, docs: support finite numeric OIDC claims (float64 formatted
  without scientific notation, int, int64, uint64, json.Number) and
  scalar arrays while omitting NaN/Inf fail-closed.
test_a_circuit_the_far_end_never_speaks_on_ends_at_the_dial_timeout
called `await stream.read(1)` in accept_and_stall assuming the caller
sent nothing until DIAL_TIMEOUT reset the stream. In reality,
dial_through_relay immediately runs upgrade_outbound_connection and
writes `/multistream/1.0.0\n`, so `read(1)` returned immediately, set
`released` prematurely, and exited the stream handler before
DIAL_TIMEOUT fired. Under CI scheduling jitter, py-libp2p could then
reclaim/close the stream early and fail the dial with MuxedStreamEOF
instead of waiting for DIAL_TIMEOUT.

Drain inbound handshake bytes in a loop until the caller resets or
closes the stream, and assert that `released` fires at or after
DIAL_TIMEOUT.
@HosniBelfeki

Copy link
Copy Markdown
Contributor

FYI the sdk job also fails on main since py-libp2p 0.8.3 (released 2026-11-26): reproduced locally on 36ccd72, TestNativeSDK* passes with 0.8.2 and fails with 0.8.3, on the same subtests as here.

…ff-stream for py-libp2p 0.8.3

py-libp2p 0.8.3 introduced two stream-handler lifecycle changes that broke
relayed inbound connections and router GoAway failover in the Python SDK:

1. SwarmConn._handle_muxed_stream now closes any inbound stream when its
   handler returns unless `stream._keep_open` is True. `stop_stream_handler`
   in `sdk/python/src/agent_mesh/relay.py` hands the STOP stream off to
   `host.upgrade_inbound_connection` and returns, causing py-libp2p 0.8.3 to
   close the underlying circuit stream immediately after upgrade. Set
   `_keep_open = True` once `upgrade_inbound_connection` succeeds (matching
   py-libp2p's own circuit_v2 STOP handler) and close the stream on upgrade
   failure.
2. SwarmConn._cleanup now cancels the connection's stream-handler nursery
   when a connection closes. `go_away_stream_handler` invoked
   `session.handle_go_away` inline on that stream handler task, so calling
   `host.disconnect(router)` (or the draining router closing its socket)
   cancelled `handle_go_away` before `top_up_routers()` and
   `_relay_trigger.set()` ran. Dispatch GoAway failover onto the session
   nursery and trigger `_relay_trigger` before detaching the router.

Add unit tests covering both invariants in test_relay.py and test_session.py.
@aojea

aojea commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

FYI the sdk job also fails on main since py-libp2p 0.8.3 (released 2026-11-26): reproduced locally on 36ccd72, TestNativeSDK* passes with 0.8.2 and fails with 0.8.3, on the same subtests as here.

fixed

@aojea

aojea commented Nov 26, 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 introduces end-to-end policy-driven OIDC claim attestation, boundary isolation, and gateway provenance to Agent Mesh. It adds structured claims to PolicyBinding and attested_claims to PolicyConfig, allowing verified JWT claims to be minted as first-class claim(k, v) Biscuit facts. The changes update the control plane, storage layer (with a new migration), and node PEPs (including Envoy ext_authz/ext_proc) to enforce these claims, mandate short-lived task scopes (require_task_scope and max_task_ttl), and strip spoofed headers while stamping verified provenance headers. Additionally, it fixes stream keep-open and GoAway failover handling in the Python SDK for py-libp2p compatibility, adds comprehensive unit/integration tests, and updates the documentation and examples. There are no review comments, so I have no feedback to provide.

@aojea
aojea merged commit ae04538 into google:main Nov 26, 2026
22 checks passed
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