Skip to content

Agent Mesh

sdk: inject method and path and apply the HTTP narrowing rules

Antonio Ojea7c9b1412ec94
diff --git a/sdk/js/src/authorizer.test.ts b/sdk/js/src/authorizer.test.ts
index b528e1c4..9860edbb 100644
--- a/sdk/js/src/authorizer.test.ts
+++ b/sdk/js/src/authorizer.test.ts
@@ -155,11 +155,30 @@ test("an agent claim is accepted only inside a granted namespace", async () => {
await authorizeCaller(request(nodeToken(CALLER)), options(NODE_ROLE_GRANTS));
});
+test("a grant narrowed by PolicyRole.http follows the request's method and path", async () => {
+ // Rendered as the control plane renders a role with
+ // http: [{service: "mcp://calc", methods: ["GET"], paths: ["/v1/*"]}]:
+ // the plain grant is withheld, the narrowed facts take its place.
+ const rules = [
+ `http_granted_service_exact("mcp", "calc") <- role("sam:role:node")`,
+ `granted_method("mcp", "calc", ["GET"]) <- role("sam:role:node")`,
+ `granted_path_prefix("mcp", "calc", "/v1/") <- role("sam:role:node")`,
+ `target_unrestricted(true) <- role("sam:role:node")`,
+ ];
+ const http = (method: string, path: string): AuthorizeRequest => ({ ...request(nodeToken(CALLER)), method, path });
+ await authorizeCaller(http("GET", "/v1/models"), options(rules));
+ await assert.rejects(authorizeCaller(http("POST", "/v1/models"), options(rules)), AuthorizationError);
+ await assert.rejects(authorizeCaller(http("GET", "/v2/models"), options(rules)), AuthorizationError);
+ // A tunnel, and a stream that carries no HTTP request: neither matches.
+ await assert.rejects(authorizeCaller(http("CONNECT", ""), options(rules)), AuthorizationError);
+ await assert.rejects(authorizeCaller(request(nodeToken(CALLER)), options(rules)), AuthorizationError);
+});
+
test("every baseline item parses in biscuit-wasm", () => {
for (const c of [BASELINE_DATALOG.time_check, BASELINE_DATALOG.replay_check, BASELINE_DATALOG.target_check, BASELINE_DATALOG.agent_check]) {
wasm.Check.fromString(c);
}
- for (const r of [...BASELINE_DATALOG.rules, ...BASELINE_DATALOG.agent_rules, ...BASELINE_DATALOG.target_fact_rules]) {
+ for (const r of [...BASELINE_DATALOG.rules, ...BASELINE_DATALOG.http_rules, ...BASELINE_DATALOG.agent_rules, ...BASELINE_DATALOG.target_fact_rules]) {
wasm.Rule.fromString(r);
}
for (const p of [...BASELINE_DATALOG.policies, BASELINE_DATALOG.allow_if_true]) {
diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.ts
index efe843f3..2b5ac840 100644
--- a/sdk/js/src/authorizer.ts
+++ b/sdk/js/src/authorizer.ts
@@ -33,6 +33,14 @@ export interface AuthorizeRequest {
protocol: string;
/** The agent the caller says it acts for; its own claim, checked against its grants. */
agent?: string;
+ /**
+ * The HTTP method and the path as the backend sees it, when the request is
+ * HTTP. Both are injected together; a request without them (a stream that
+ * carries no HTTP request) does not match a grant narrowed by
+ * PolicyRole.http.
+ */
+ method?: string;
+ path?: string;
}
export interface ProviderAuthorizerOptions {
@@ -122,6 +130,12 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAu
fact(`${BASELINE_DATALOG.fact_connection_peer_id}({p})`, { p: req.peerId });
fact(timeFact(now));
+ // The request as the wire carried it, never as the caller describes it.
+ if (req.method !== undefined) {
+ fact(`${BASELINE_DATALOG.fact_method}({m})`, { m: req.method });
+ fact(`${BASELINE_DATALOG.fact_path}({p})`, { p: req.path ?? "" });
+ }
+
// The caller's word about which agent it acts for, limited to the agent
// namespaces its own token grants.
if (req.agent) {
@@ -148,6 +162,9 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAu
for (const r of BASELINE_DATALOG.rules) {
b.addRule(wasm.Rule.fromString(r));
}
+ for (const r of BASELINE_DATALOG.http_rules) {
+ b.addRule(wasm.Rule.fromString(r));
+ }
for (const r of options.policyRules()) {
b.addRule(wasm.Rule.fromString(r));
}
diff --git a/sdk/js/src/libp2p-http-node.ts b/sdk/js/src/libp2p-http-node.ts
index 3b4bbebc..eb6da96f 100644
--- a/sdk/js/src/libp2p-http-node.ts
+++ b/sdk/js/src/libp2p-http-node.ts
@@ -97,7 +97,7 @@ function nodeHeaders(req: http.IncomingMessage): Headers {
async function serveListener(req: http.IncomingMessage, res: http.ServerResponse, endpoint: A2AEndpoint, listener: NodeRequestListener, options: ProviderOptions): Promise<void> {
const remotePeer = (req.socket as unknown as StreamSocket).remotePeer;
- const admission = await admitIngress({ target: req.url ?? "/", headers: nodeHeaders(req), remotePeer }, endpoint, options);
+ const admission = await admitIngress({ method: req.method ?? "GET", target: req.url ?? "/", headers: nodeHeaders(req), remotePeer }, endpoint, options);
if ("status" in admission) {
res.writeHead(admission.status, { "content-type": "text/plain; charset=utf-8" });
res.end(admission.text + "\n");
diff --git a/sdk/js/src/libp2p-http.test.ts b/sdk/js/src/libp2p-http.test.ts
index 0bc05183..424c8548 100644
--- a/sdk/js/src/libp2p-http.test.ts
+++ b/sdk/js/src/libp2p-http.test.ts
@@ -342,11 +342,11 @@ test("a dot segment is refused however it is spelled", async () => {
// Nothing in options is consulted before the path check.
const options = providerOptions(new Uint8Array());
for (const target of ["/a2a/agent/../x", "/a2a/agent/./x", "/a2a/agent/%2e%2e/x", "/a2a/agent/%2E%2E/x", "/a2a/agent/.%2e/x", "/a2a/agent/%2e/x", "/a2a/%2e%2e/other/x?q=1"]) {
- assert.deepEqual(await admitIngress({ target, headers: new Headers(), remotePeer: "peer" }, endpoint, options), { status: 400, text: "Invalid path" }, target);
+ assert.deepEqual(await admitIngress({ method: "GET", target, headers: new Headers(), remotePeer: "peer" }, endpoint, options), { status: 400, text: "Invalid path" }, target);
}
// Not dot segments: the request reaches the next check, the missing biscuit.
for (const target of ["/a2a/agent/%2e%2ex/x", "/a2a/agent/..x/x", "/a2a/agent/x?p=../y"]) {
- assert.deepEqual(await admitIngress({ target, headers: new Headers(), remotePeer: "peer" }, endpoint, options), { status: 401, text: "Missing X-Sam-Biscuit header" }, target);
+ assert.deepEqual(await admitIngress({ method: "GET", target, headers: new Headers(), remotePeer: "peer" }, endpoint, options), { status: 401, text: "Missing X-Sam-Biscuit header" }, target);
}
});
diff --git a/sdk/js/src/libp2p-http.ts b/sdk/js/src/libp2p-http.ts
index 8b544641..6508fcb8 100644
--- a/sdk/js/src/libp2p-http.ts
+++ b/sdk/js/src/libp2p-http.ts
@@ -132,6 +132,8 @@ function hasDotSegment(path: string): boolean {
/** What the ingress looks at before anything reaches the agent. */
export interface IngressRequest {
+ /** The request method as it came off the wire. */
+ method: string;
/** The request target as it came off the wire, path and query. */
target: string;
headers: Headers;
@@ -199,7 +201,17 @@ export async function admitIngress(req: IngressRequest, endpoint: A2AEndpoint, o
let verified: VerifiedBiscuit;
try {
verified = await authorizeCaller(
- { biscuit, peerId: req.remotePeer, targetService, protocol: HTTP_PROTOCOL, agent: req.headers.get(HEADER_SAM_AGENT) ?? "" },
+ {
+ biscuit,
+ peerId: req.remotePeer,
+ targetService,
+ protocol: HTTP_PROTOCOL,
+ agent: req.headers.get(HEADER_SAM_AGENT) ?? "",
+ // The path as the backend sees it, decided before authorization so
+ // path() is what policy meant, never the routing prefix.
+ method: req.method,
+ path: "/" + upstreamPath,
+ },
options,
);
} catch (err) {
@@ -302,7 +314,7 @@ async function serveIngress(stream: Stream, remotePeer: string, endpoint: A2AEnd
return;
}
headOnly = head.method === "HEAD";
- const admission = await admitIngress({ target: head.target, headers: head.headers, remotePeer }, endpoint, options);
+ const admission = await admitIngress({ method: head.method, target: head.target, headers: head.headers, remotePeer }, endpoint, options);
if ("status" in admission) {
response = refusalResponse(admission);
} else if ("listener" in endpoint.target) {
diff --git a/sdk/python/src/agent_mesh/authorizer.py b/sdk/python/src/agent_mesh/authorizer.py
index 33575815..5145cc9d 100644
--- a/sdk/python/src/agent_mesh/authorizer.py
+++ b/sdk/python/src/agent_mesh/authorizer.py
@@ -54,6 +54,12 @@ class AuthorizeRequest:
protocol: str
# The agent the caller says it acts for; its own claim, checked against its grants.
agent: str = ""
+ # The HTTP method and the path as the backend sees it, when the request is
+ # HTTP. Both are injected together; a request without them (a stream that
+ # carries no HTTP request) does not match a grant narrowed by
+ # PolicyRole.http.
+ method: Optional[str] = None
+ path: str = ""
@dataclass(frozen=True)
@@ -105,6 +111,11 @@ def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions)
b.add_fact(ba.Fact(BASELINE_DATALOG["fact_connection_peer_id"] + "({p})", {"p": req.peer_id}))
b.add_fact(ba.Fact(BASELINE_DATALOG["fact_time"] + "({now})", {"now": now}))
+ # The request as the wire carried it, never as the caller describes it.
+ if req.method is not None:
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_method"] + "({m})", {"m": req.method}))
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_path"] + "({p})", {"p": req.path}))
+
# The caller's word about which agent it acts for, limited to the agent
# namespaces its own token grants.
if req.agent:
@@ -126,6 +137,8 @@ def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions)
b.add_policy(ba.Policy(p))
for r in BASELINE_DATALOG["rules"]:
b.add_rule(ba.Rule(r))
+ for r in BASELINE_DATALOG["http_rules"]:
+ b.add_rule(ba.Rule(r))
for r in options.policy_rules():
b.add_rule(ba.Rule(r))
diff --git a/sdk/python/src/agent_mesh/libp2p_http.py b/sdk/python/src/agent_mesh/libp2p_http.py
index f470fa0d..9d3e2c87 100644
--- a/sdk/python/src/agent_mesh/libp2p_http.py
+++ b/sdk/python/src/agent_mesh/libp2p_http.py
@@ -238,6 +238,10 @@ async def _handle_ingress(
target_service=target_service,
protocol=str(HTTP_PROTOCOL),
agent=headers.get(HEADER_SAM_AGENT, ""),
+ # The path as the backend sees it, decided before authorization
+ # so path() is what policy meant, never the routing prefix.
+ method=request.method.decode("latin-1"),
+ path="/" + upstream_path,
),
options.authorizer,
)
diff --git a/sdk/python/tests/test_authorizer.py b/sdk/python/tests/test_authorizer.py
index bbd988dd..dffc7f89 100644
--- a/sdk/python/tests/test_authorizer.py
+++ b/sdk/python/tests/test_authorizer.py
@@ -136,10 +136,36 @@ def test_agent_claim_only_inside_a_granted_namespace():
authorize_caller(request(node_token(CALLER)), options(NODE_ROLE_GRANTS))
+def test_narrowed_grant_follows_the_requests_method_and_path():
+ # Rendered as the control plane renders a role with
+ # http: [{service: "mcp://calc", methods: ["GET"], paths: ["/v1/*"]}]:
+ # the plain grant is withheld, the narrowed facts take its place.
+ rules = [
+ 'http_granted_service_exact("mcp", "calc") <- role("sam:role:node")',
+ 'granted_method("mcp", "calc", ["GET"]) <- role("sam:role:node")',
+ 'granted_path_prefix("mcp", "calc", "/v1/") <- role("sam:role:node")',
+ 'target_unrestricted(true) <- role("sam:role:node")',
+ ]
+
+ def http(method: str, path: str) -> AuthorizeRequest:
+ return AuthorizeRequest(biscuit=node_token(CALLER), peer_id=CALLER, target_service="mcp://calc", protocol="/libp2p-http", method=method, path=path)
+
+ authorize_caller(http("GET", "/v1/models"), options(rules))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(http("POST", "/v1/models"), options(rules))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(http("GET", "/v2/models"), options(rules))
+ # A tunnel, and a stream that carries no HTTP request: neither matches.
+ with pytest.raises(AuthorizationError):
+ authorize_caller(http("CONNECT", ""), options(rules))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(node_token(CALLER)), options(rules))
+
+
def test_every_baseline_item_parses_in_biscuit_python():
for c in (BASELINE_DATALOG["time_check"], BASELINE_DATALOG["replay_check"], BASELINE_DATALOG["target_check"], BASELINE_DATALOG["agent_check"]):
ba.Check(c)
- for r in BASELINE_DATALOG["rules"] + BASELINE_DATALOG["agent_rules"] + BASELINE_DATALOG["target_fact_rules"]:
+ for r in BASELINE_DATALOG["rules"] + BASELINE_DATALOG["http_rules"] + BASELINE_DATALOG["agent_rules"] + BASELINE_DATALOG["target_fact_rules"]:
ba.Rule(r)
for p in BASELINE_DATALOG["policies"] + [BASELINE_DATALOG["allow_if_true"]]:
ba.Policy(p)