Repository navigation
api, controlplane, node, envoy: attest verified OIDC claims as claim() Biscuit facts - #953
Conversation
…) 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.
There was a problem hiding this comment.
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.
| 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) | ||
| } |
There was a problem hiding this comment.
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)
}| 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) | ||
| } |
There was a problem hiding this comment.
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)
}|
|
||
| // 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) |
There was a problem hiding this comment.
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.
| 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
- 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.
|
FYI the |
…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.
fixed |
|
/gemini review |
There was a problem hiding this comment.
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.
Summary
Adds first-class IdP-verified
claim(key, value)Biscuit authority facts, structuredPolicyBinding.claimsmatching, 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 versionedPolicyConfigand standard Biscuit Datalog—without overloading node-declaredlabel(k, v)or adding control-plane CLI claim flags.Key Changes
1. Schema & First-Class
claim(k, v)Predicate (api/,sdk/)PolicyBinding.claims(map<string, string>) andPolicyConfig.attested_claims(repeated string) toapi/agentmesh.protoand regenerated Go, TypeScript, and Python bindings.api.FactClaim = "claim"structurally separate from node-declaredlabel(k, v), so enrolling nodes can never spoof IdP posture claims even whenPolicyRole.allowed_labelscontains"*"."iss"inPolicyBinding.claimsfor cross-issuer protection in multi-issuer meshes.amr, emitting oneclaim()fact per distinct element).api.MaxAttestedClaims = 16distinct claim paths rejected with400atPOST /policies;api.MaxValuesPerClaim = 16values per claim omitted fail-closed with a warning) and includes them in the control-plane authorizer fact budget.PolicyBinding.claimsinto standard cross-language Biscuit Datalog rules distributed overGET /policies.2. Storage & Control Plane (
internal/storage/,internal/controlplane/,internal/identity/)role_bindings.claims_jsonandpolicy_attested_claims, supporting multiple bindings per role for OR-of-AND claim profiles (SavePolicyConfig/GetAttestedClaims).claim(k, v)facts onto Member and Delegated Session Biscuits across/register,/refresh(re-attesting fresh JWTs to drop degraded posture immediately and applying updatedattested_claimsfrom storedClaimsJSON),/token/exchange, and/oauth/token.mesh_claims(scalar string or array for multi-valued claims) andmesh_labelsin outbound/sts/tokenES256 border JWTs and structuredBorder Crossinglogs.3. Node Attenuation & Tamper-Proof Provenance (
internal/node/,internal/envoy/)attenuation.require_task_scopeandattenuation.max_task_ttlalongside existing standard Datalogrules/checks/policiesoverclaim().X-Mesh-*andX-Peer-Idheaders across inbound libp2p streams, router ingress, and Envoyext_authz(headers_to_remove) /ext_proc(remove_headers), stamping verifiedX-Mesh-Claims,X-Mesh-Labels,X-Mesh-Actor-Node, andX-Mesh-Origin(mesh-remote,mesh-external-ingress,mesh-gateway).X-Mesh-Claims,X-Mesh-Labels, andX-Mesh-Actor-NodewhenEgressDestination.forward_contextis enabled.4. Documentation, Tests & Loopback Demo
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, andtests/integration/posture_isolation_test.go.development/examples/device-posture-isolation/running realagentmesh-oneandagentmesh-nodebinaries with dual local RS256 OIDC issuers (15 assertions across 5 acts).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.