# IndyKite Developer Hub - full content > Single-file concatenation of every guide, code example, Terraform example, tutorial, and agent skill on https://developer.indykite.com. For the structured index (per-document URLs, JSON APIs), fetch /llms.txt instead. --- # Agent Gateway: Authorize Agent-to-Agent and MCP Calls > How the IndyKite Agent Gateway (IAG) decides whether an agent call may proceed, what to set up in your identity provider and your IndyKite project, how to configure, run and test one gateway, and how to read its responses and audit records. **Category:** Agent Gateway ## Summary From zero to a first authorized call: identity provider clients, graph data, KBAC and ContX IQ configuration, the gateway config file, a test request, and the audit record it produces. Then the complete reference: every configuration key with the exact startup errors, the capability checks that decide which tools, resources, prompts and skills a caller may use, deployment, HTTP behaviour in a2a and mcp mode, and the audit record format. ## Content # What is the Agent Gateway? The **IndyKite Agent Gateway** (IAG) is a self-hosted proxy placed in front of one AI agent or one MCP server. On every request it authenticates the caller, establishes the chain of agents acting for the user, checks in the IndyKite Knowledge Graph that this chain is a modelled workflow the user may trigger, forwards the request with a delegation token, and writes an audit record. Nothing reaches the protected agent without passing the gateway. You run **one gateway per protected agent**. ```text user token │ ▼ [orchestrator-iag] ──► orchestrator agent ──► [retriever-iag] ──► retriever agent introspect · exchange · check chain [orchestrator] against wf1 · authorize · audit introspect · exchange · check chain [orchestrator, retriever] · authorize · audit ``` Two protocols are understood, selected by `protected_agent.protocol`: `a2a` (Agent-to-Agent JSON-RPC, the default) and `mcp` (Model Context Protocol over Streamable HTTP). The [Agent Gateway MCP tutorial](/tutorials/tutorial-agent-gateway-mcp) walks the mcp mode end to end with a Google Drive server; this guide uses the a2a mode for its example and documents both. ## Terms used in this guide | Term | Meaning | | --- | --- | | **IKG** | The IndyKite Knowledge Graph: nodes and relationships loaded through the Capture API ([Data Schema guide](/guides/guide-data-schema)). | | **KBAC** | Knowledge-Based Access Control: a policy is a graph pattern between a subject and a resource; the **AuthZEN** API answers "may this subject perform this action on this resource?" from it ([AuthZEN guide](/guides/guide-authzen)). | | **ContX IQ** | The API that runs a stored **Knowledge Query** against the graph under a ContX IQ policy, and whose `whoami` endpoint resolves a token to its graph subject ([ContX IQ guide](/guides/guide-contx-iq)). The gateway uses only `whoami`. | | **Admission policy** | The KBAC policy the gateway asks AuthZEN to evaluate for every request: subject the user, action `authzen.action`, resource the protected agent, condition comparing the delegation chain in `$ik_token.act_chain` with a workflow's path in the graph. | | **A2A** | Agent-to-Agent protocol: JSON-RPC methods such as `message/send` exchanged between agents. **MCP** is the Model Context Protocol between an AI client and a tool server. | | **Subject** | The user on whose behalf the call is made: the `sub` claim of the tokens. **Actor**: an agent acting for the subject. The actors form the **delegation chain**. | | **Delegation token** | A token obtained by OAuth 2.0 token exchange (RFC 8693) whose `act` claim names the acting agent and nests the previous `act`, so `act.sub`, `act.act.sub`, ... is the chain, newest first. | | **Token Service** | The optional self-hosted IndyKite issuer of delegation tokens ([Token Service guide](/guides/guide-token-service)). Without it, your identity provider performs the exchange. | | **Application Agent credential token** | The credential the gateway sends as `X-IK-ClientKey` to the IndyKite APIs; the agent needs the `Authorization` and `ContXIQ` API permissions ([Credentials guide](/guides/guide-credentials)). | | **GID** | The platform identifier of a configuration object, prefixed `gid:`. Where a GID is accepted, the object's `name` usually is too. | # How a request is decided ![One request through the Agent Gateway, nine steps in order. 1, the bearer token is introspected at the identity provider; a missing or inactive token answers 401. 2, the gateway gets its own actor token from the identity provider with the client credentials grant. 3, both are exchanged for a delegation token at the identity provider, or at the Token Service when one is configured. 4, the subject is resolved with ContX IQ whoami; a token it rejects answers 401. 5, admission: one AuthZEN evaluation decides whether the subject may reach the agent through the delegation chain; a denial answers 403. 6, capabilities: an AuthZEN resource search gives the tools, resources, prompts and skills the caller may use; lists are filtered and a call outside the set answers 403. 7, intent, in a2a mode with ibac.enabled: the Intent Agent reads the prompt, and with a Token Service the intent is compared with the skills of the agent; without an intent the gateway answers in place of the agent, and an intent that fits no skill answers 403. 8, mappings, in mcp mode with ibac.enabled and an intent in the token: a call is checked against the mapping of the capability and the resolved evaluations are decided by AuthZEN; a mismatch or a denial answers 403. 9, forward to the agent or the MCP server with the delegation token; an unreachable target answers 502. One audit record is written per decision, before forwarding.](/assets/images/iag-request-pipeline.svg) The picture is the overview: each step, the party it asks, and what a refusal there answers. The list below has the exact rules of each step, including the statuses the picture leaves out. For every request, in this order: 1. **Bearer token, or the delegation token of the previous hop.** A request without `X-IK-Token` starts a workflow: `Authorization: Bearer ` is required, without it the answer is `401`, and the token is introspected at the identity provider and must be active. With `token_service` configured, the token must also have been issued for one of `protected_agent.authentication.audiences`, read from the introspection answer or, when that names none, from the token itself; any other token, one without an audience included, is refused with `401` and `Access token not issued for this agent`, so a workflow starts only at the agent the token was issued for. A request with `X-IK-Token` is a later hop: the gateway introspects that token at the issuer named under `token_service`, requires an `act` object and a `sub` in it, and needs no `Authorization`. A bearer token that travels beside it is handled by `authorization_header.forward`: with the default `correct_audience` it is introspected and passed on only when it is active and issued for one of `protected_agent.authentication.audiences`, otherwise it is dropped and the request goes on; with `all` it is passed on as sent; with `none` nothing is passed on. A token the gateway passes on must also name the same user as the delegation token while `authorization_header.same_user_check` is on (the default). Without `token_service`, `X-IK-Token` is ignored and every hop arrives with the previous hop's delegation token as its bearer token. 2. **Actor token.** The gateway obtains a token for the protected agent with the client credentials grant, using `protected_agent.authentication`. The request names an `audience` only when `identity_provider.client_credential_audience` is set. The token is kept and reused until `identity_provider.client_credential_renew_before` (default 10 seconds) before the `expires_in` of the grant answer; an answer without `expires_in`, or with a lifetime no longer than that margin, gives a token used once. When the exchange is refused with `400` or `401`, the gateway drops the kept token and tries once more with a new one, so a revoked token costs one retry, not a failed request. 3. **Delegation token.** The subject token, or on a later hop the incoming delegation token, and the actor token are exchanged for one delegation token. Without a Token Service the identity provider does the exchange at `identity_provider.exchange_endpoint`; with `token_service` configured, the issuer named there does: the IndyKite Token Service, or an identity provider that meets the requirements listed under [token_service](#configuration). On a later hop the issuer nests the incoming chain in the token it mints, so the chain grows by one agent per hop. The result must carry `sub` and an `act` object; the gateway reads the chain from it. 4. **Subject.** The gateway sends the bearer token of the request to ContX IQ `GET /contx-iq/v1/whoami`, with the AppAgent credential as `X-IK-ClientKey`, and takes the subject from the answer: `type` is the `ikg_node_type` of the project's Token Introspect configuration that validates the token, `id` is the token's subject claim ([whoami](/guides/guide-contx-iq#whoami)). A token `whoami` rejects ends the request with `401`. On a later hop that carries no bearer token, or whose bearer token the gateway neither passes on nor checks, the gateway sends the delegation token it just minted instead, as the bearer token; the platform resolves it through the Token Introspect configuration that matches the issuer under `token_service`, so every subject of such a hop gets the `ikg_node_type` of that one configuration. 5. **Admission.** The gateway asks AuthZEN once, with `POST /access/v1/evaluation`, whether the subject may reach the protected agent. The subject is the `type` and `id` from `whoami`; the action is `authzen.action`; the resource `id` is the newest hop of the chain, the gateway's own agent, and the resource `type` is that hop's `act.type`, or `protected_agent.node_type` when the token has none, or `Agent` when neither is set. `authzen.input_params` and `authzen.policy_tags`, when set, go as `context`. Beside the AppAgent credential in `X-IK-ClientKey`, the call carries the user's bearer token in `Authorization`, when the request had one, and the delegation token of this hop in `X-IK-Token`, with and without a Token Service; the policy therefore reads the chain as `$ik_token.act_chain` and compares it with the graph itself. The gateway does not compare the chain with anything: `decision: false` means `403`. A chain that cannot be read is refused without a call, and a token whose `act.type` differs from a set `protected_agent.node_type` is refused as an error. The decision is kept per subject, resource type, chain and token claims for `authzen.cache_ttl`, and the audit record says whether it came from the cache. In `mcp` mode, a request that names or lists capabilities skips this step and gets the capability decision of the next step instead. 6. **Capabilities (mcp mode, and the extended card in a2a mode).** With `authzen.capabilities.enabled` on, the default, the gateway also decides what the caller may use on the server. For each kind of capability a request needs, it reads the **permitted set** with one `POST /access/v1/search/resource`: the subject from `whoami`, the action `authzen.capabilities.action` (`CAN_USE` by default), the resource type from `authzen.capabilities.labels` (`Tool`, `McpResource`, `Prompt` and `Skill` by default), with the same headers and `context` as the admission call. The answer is the identifiers the caller may use: tool names, resource URIs, prompt names, skill ids. A `tools/list`, `resources/list` or `prompts/list` is a **discovery**: the server's list is filtered to the set of its kind, in the server's order and with its cursor untouched, and a caller who may use nothing of the kind gets an empty list without the server being called. A `tools/call`, `resources/read`, `resources/subscribe`, `prompts/get` or a `subscriptions/listen` naming resources is an **invocation**: every capability it names must be in the set of its kind, or the answer is `403` with the JSON-RPC error `-31403`, `Forbidden: the caller may not use the named tool` (or `resource`, `prompt`), and the server is not called. Such a request gets no admission decision: one decision per request, never both. Every other request, `initialize` included, keeps the admission decision. In `a2a` mode every request keeps the admission decision, and only the extended agent card is filtered, to the skills of the permitted set; with `ibac.enabled` and an intent in the delegation token, the card keeps of those skills only the ones that fit that intent, and with capability checks off the intent is compared with every skill of the agent, as the Mappings step describes. A set is kept per subject, action, label, chain and token claims for `authzen.cache_ttl`, an empty one too; a set that cannot be read fails the request with the platform's status, or `500`. The graph model and the policy are under [Capability checks](#capability-checks-what-the-caller-may-use). 7. **Intent (a2a mode, with `ibac.enabled`).** For a `message/send` or `message/stream` whose message has text, the gateway sends the text parts, joined one per line, to the [Intent Agent](/guides/guide-intent-agent#gateway) with the `whoami` subject in the metadata, authenticated by its own client credentials token for `intent_agent.audience`. Without `token_service`, an intent lets the message through; with it, the intent must also fit the skills of the agent, as described below. A failed task answers the caller in place of the agent, with status `200`: an agent message in the same `contextId` whose text is the task's error followed by its obligation, and whose `metadata.intent_error` holds `prompt`, `error`, `reason` and `obligation`; a streaming request gets it as its one event. An Intent Agent that cannot be reached, or answers in a shape the gateway cannot read, refuses the message with `502`; one that does not answer within `intent_agent.timeout`, with `504`. Messages without text and the other methods are not sent to the Intent Agent. The gateway reads an intent of at most 64 evaluations; without `token_service`, a larger one is a `502`. With `token_service`, the intent is first **compared with the skills** of the agent the caller may use: the permitted skills, or every skill of the agent with capability checks off. A skill covers an evaluation when the subject type, the resource type and the action of the evaluation match one of its `x-coaz-mappings`; a skill without a mapping covers every evaluation with `ibac.capabilities.unmapped: allow` and none with `deny`. An evaluation that no skill covers is left out, and an intent of which nothing is covered refuses the message with `403` and `Authorization check failed`; the agent does not get it. A message without text has no intent of its own: when its chain carries one, the newest is compared the same way. With `token_service`, a message with an intent also gets a **second exchange** of the delegation token: the same subject token and actor as the first, plus the evaluations of the intent that fit the skills in the `intent` parameter, exactly as the Intent Agent wrote them, with no field it left out or left empty, which the issuer writes into `act.intent` of this hop. The gateway authorizes on the token of the first exchange, and the agent receives the token of the second in `X-IK-Token`, so the next hop and the platform see what this hop is about to do. This needs an issuer that knows the `intent` parameter, such as the [IndyKite Token Service](/guides/guide-token-service#intent): a token that comes back without all the evaluations is refused with `502` and `cannot delegate the token with the intent`. An intent with more evaluations than the Token Service accepts (its `max_intent_evaluations`, 10 by default) or more than 64 is neither forwarded nor cut down: the gateway answers in place of the agent, as for a failed task, with the error `The request asks for too much at once: its intent has evaluations, too many for one request.`, the reason `intent_too_large` and the obligation `Send the request in smaller parts.` A delegation token the Token Service finds too large, from either exchange, is refused with `403` and `Authorization check failed`. A `429` of the second exchange goes to the caller, as on the first. 8. **Mappings (with `ibac.enabled` and an intent: invocations in mcp mode, the extended card in a2a mode).** When the delegation token of the request carries an intent, written by an earlier hop, the gateway also checks each invocation (`tools/call`, `resources/read`, `resources/subscribe`, `prompts/get`, `subscriptions/listen`) against the [x-coaz-mappings](/guides/guide-ibac#mappings) of the capability it names. The gateway keeps a catalog of the server's tools, resources and prompts with their mappings, filled from every list that passes through it, before filtering, and kept for `ibac.capabilities.cache_ttl`. For a capability it has not seen listed, it first lists the server itself, every page of that kind, with the tokens of the request; that list fills the catalog and never reaches the caller, and a server that cannot be listed fails the call with `502` and `cannot list the capabilities of the MCP server`. Then: a capability whose mapping cannot be read is refused with `403` and the JSON-RPC error `-31403`, `Forbidden: the named tool has an invalid mapping` (or `resource`, `prompt`); a capability without a mapping, or one the server does not list, goes on when `ibac.capabilities.unmapped` is `allow` (the default), so the permitted set alone decides, and is refused with `Forbidden: the named tool has no mapping` when it is `deny`; a capability with a valid mapping is checked twice. **Against the intent:** the call goes on only when at least one evaluation of the current intent, the newest intent in the `act` chain of the token, matches a mapping of the capability by subject type, resource type and action; a mapping that lists no action accepts any action. The ids of a mapping are read from the call, `$request` being the `params` of the request and `$token` the claims of the delegation token, never from the intent; a mapping whose expression has no value, or a value that is not a non-empty string, does not match, so a call without the argument a mapping reads is refused. A call the intent does not match is refused with `403` and `Forbidden: the named tool does not match the intent` (or `resource`, `prompt`). **At the platform:** for every matched mapping whose subject and resource both name an id, one evaluation is resolved, the resource with its id and the action of the matched evaluation of the intent, and the gateway sends the evaluations of the request in one `POST /access/v1/evaluations`, with the subject from `whoami` and the same headers and `context` as the admission call. The call goes on only when the platform allows every one of them; otherwise it is refused with `403` and `Forbidden: the caller may not access the data the named tool uses` (or `resource`, `prompt`), and when the platform cannot be asked the call fails with the platform's status and the server does not get it. The answers are kept like an admission decision, for `authzen.cache_ttl`. A request that names several capabilities goes on only when every one of them passes. **The lists are filtered by the intent too:** of a `tools/list`, `resources/list` or `prompts/list` answer, after the permitted set with capability checks on and of every entry with them off, an entry stays when one of its mappings matches at least one evaluation of the current intent. An entry without a mapping stays with `ibac.capabilities.unmapped: allow` and is removed with `deny`; an entry whose mapping cannot be read is removed. Nothing is refused: a list can come back empty. Without an intent in the delegation token this step does not run: the gateway lists nothing itself and refuses nothing. In `a2a` mode, a message is compared with the mappings of the agent's skills in the Intent step above, with a Token Service; here the mappings decide what the **extended agent card** lists. With an intent in the delegation token of the request, the card lists only the skills that fit the **current intent**, of the permitted skills with capability checks on and of every skill of the agent with them off. The current intent is the newest intent in the `act` chain of the token: a skill fits when the subject type, the resource type and the action of at least one evaluation of the intent match one of its `x-coaz-mappings`. The gateway reads the mappings from the skills of the card as the agent sent it, before any filter, and keeps them for `ibac.capabilities.cache_ttl`. A skill without a mapping follows `ibac.capabilities.unmapped`: with `allow` it stays on the card, with `deny` it is dropped. A skill whose mapping cannot be read, or whose id the card lists twice, is dropped in both settings. When the skills of the card cannot be read with their mappings, the caller gets an error and no card. Without an intent in the token, the card is filtered to the permitted set only, or with capability checks off goes to the caller with every skill. 9. **Forward.** Without a Token Service the delegation token replaces the caller's token in `Authorization`; an A2A agent then gets no other header of the caller, and an MCP server gets all of them except `Authorization`, `X-IK-Token` and `Accept-Encoding`. With one, the delegation token travels in `X-IK-Token`, where IndyKite policies read it as `$ik_token`; `Authorization` carries what `authorization_header.forward` passes on, by default the user's token when it is issued for this agent; and the other headers of the caller travel too, except the headers of one connection (`Connection` and the headers it names, `Keep-Alive`, `Proxy-Authorization` and the like). A call to an A2A agent with a Token Service also carries the `A2A-Extensions` header naming the delegated token extension, whose identifier is the string `https://indykite.com/extensions/delegated-token/v1` (a name to compare against, not a page), so the agent knows the token in `X-IK-Token` is the token of that extension. 10. **Audit.** One record per decision, written before forwarding, on every outcome including refusals: `action` names the question (`ADMISSION`, `DISCOVERY`, `INVOCATION`, `INTENT`, or `noop` for a request refused before any question was asked) and `decision` the answer, see [Audit records](#audit-records). What IBAC adds beyond this step, the mappings a skill or tool declares and how an intent is matched against them, is in the [IBAC engine guide](/guides/guide-ibac). Facts that follow from this sequence and matter when something is refused: - The subject is always the user. On later hops the token's `sub` is still the user's; an agent is the subject only when it starts a workflow with its own token. - The graph must hold a node of the subject type whose `external_id` equals the token's `sub`. For a `2.0-kbac` policy that node must be an identity node (`is_identity: true`). Otherwise every call ends in `403`. The subject type is the `ikg_node_type` of the matching Token Introspect configuration. - Every token that reaches a gateway in `Authorization` needs a Token Introspect configuration in the project whose `jwt_matcher` matches its `iss` and `aud`; without one, `whoami` refuses it and the gateway answers `401`. On a later hop without a Token Service, `Authorization` carries the delegation token of the previous hop, so the issuer and audience of those tokens need a configuration too. With a Token Service, `Authorization` carries the user's own token at the start of a workflow; a later hop may carry it too, or no `Authorization` at all, and then the delegation token itself is resolved, so the issuer and audience of the delegation tokens (the issuer under `token_service` and its `audience`) need a Token Introspect configuration as well. - The agent names in the chain are the `sub` claims of the agents' client-credentials tokens, as the exchange writes them into `act.sub`. The `Agent` nodes' `external_id` must equal those values. Which value an identity provider puts in `sub` for a client-credentials token is the provider's choice; the IndyKite demos run on a provider that uses the client id. - The admission policy sees both tokens. The gateway sends the user's bearer token in `Authorization` and the delegation token in `X-IK-Token` on its admission call, in both modes, so the policy reads `$token` and `$ik_token`, and compares `$ik_token.act_chain` with the `INVOKES` path of a workflow in the graph. For the platform to read the delegation token, the project needs a Token Introspect configuration for the issuer and audience of the delegation tokens, also without a Token Service. What the protected agent receives does not change: without a Token Service it still gets the delegation token in `Authorization` only. - The resource of the admission call is the protected agent, and its type selects the policy: one admission policy covers every agent and MCP server of that type. The type comes from the delegation token's `act.type`, which the IndyKite Token Service writes from its `idp.actor_type`, `Agent` by default. With an identity provider that writes no `act.type`, set `protected_agent.node_type`, or the type is `Agent`. When the token's type and the setting differ, every request is refused with an `ERROR` record that names both. - A subject or resource type without a matching policy gives `decision: false`, so `403`, not an error. - Without a Token Service, the chain grows across hops only if the identity provider nests the previous `act` claim when the subject token is itself a delegation token. RFC 8693 allows this but does not require it; a provider that does not nest gives the second gateway a chain of one agent, which matches no two-agent workflow. - With a Token Service, an incoming `X-IK-Token` is validated at the issuer and becomes the subject of the next exchange. It must carry an `act` object, otherwise `401` with `Invalid delegated token, missing act claim`: an issuer may mint users' access tokens as well, and such a token cannot take the place of a delegation token. When a bearer token travels beside it and `authorization_header.same_user_check` is on, its `sub` must equal the `sub` of the `Authorization` token, otherwise `401` with `Invalid delegated token, subject mismatch`; with the check off, the bearer token of a later hop is not read at all. Without a Token Service an incoming `X-IK-Token` is ignored and removed from the forwarded request. - With a Token Service, a user's token starts a workflow only at the gateway whose `protected_agent.authentication.audiences` lists one of its audiences. Sending the token for the orchestrator straight to the retriever's gateway is refused with `401` and `Access token not issued for this agent`, before any chain or policy check. A direct call to a later agent is allowed by issuing the user a token for that agent's audience and modelling the one-agent workflow, not by reusing the orchestrator's token. ## What is cached - The admission decision is cached for `authzen.cache_ttl` (default 5 minutes), per subject, resource type, chain and the claims of both tokens other than `exp`, `iat`, `nbf` and `jti`, so a policy may read any other claim and a new token with the same content hits the cache. A grant or revocation in the graph takes effect when the entry expires, not on the next call. - A failed admission call is cached as well: callers keep getting the error until `authzen.cache_update_after_error` (default 10 seconds) has passed and a retry succeeds. - The `whoami` answer is kept per issuer, audience and subject of the token for `contx_iq.cache_ttl`; `0` keeps none. A failed `whoami` is not kept. A change of the Token Introspect configuration, such as its `ikg_node_type`, reaches the gateway after up to `contx_iq.cache_ttl`. - Introspection and the token exchange are not cached; they run on every request. The protected agent's client credentials token, and the gateway's own token for the Intent Agent, are kept and reused until `identity_provider.client_credential_renew_before` (default 10 seconds) before they expire; a token the issuer or the Intent Agent refuses is replaced once. - In a2a mode the agent card, and the client built from it, are kept for `a2a.cache_ttl` (default 5 minutes) and fetched again after `a2a.cache_update_after` (defaults to `cache_ttl`); a new delegation token causes no new card fetch, the tokens travel with each call. A failed card fetch is returned to every call for `a2a.cache_update_after_error` (default 10 seconds) before the next attempt. # a2a or mcp: the two kinds of link in a chain The decision sequence above is the same in both modes. What differs is what sits behind the gateway and, because of it, where the chain can go next. An A2A agent can itself call another gateway, so it is a link in the middle of a chain; an MCP server only answers tool calls, so it is always the last link. | | a2a mode | mcp mode | | --- | --- | --- | | Behind the gateway | One A2A agent, reached through the JSON-RPC URL of its agent card. | One MCP server over Streamable HTTP: a third-party server, or the IndyKite MCP server itself. The gateway serves one MCP endpoint, at the path of `service.base_url`, and forwards it to the server's endpoint URL in `protected_agent.base_url`. | | Who calls the gateway | The user's client on the first hop; an upstream agent on later hops. | An MCP client: the user's tool directly, or an agent that uses the server as a tool. | | What the caller sends | A JSON-RPC message such as `message/send`, with the user's token in `Authorization` at the start of a workflow and, with a Token Service, the chain so far in `X-IK-Token` on a later hop, with or without the user's token beside it. | The MCP messages as they are, `initialize`, `tools/list`, `tools/call`, with `Mcp-Protocol-Version`, and the same two headers. In front of the IndyKite MCP server with a Token Service, a later hop must keep the user's token in `Authorization` beside `X-IK-Token`: the gateway passes `Authorization` on as `authorization_header.forward` decides (by default only a token issued for this agent, nothing when the hop had none), and that server requires a bearer token and answers `401` without one even when `X-IK-Token` is present. | | Position in the chain | Any: the agent receives the forwarded token and can call the next gateway, which exchanges again and appends the next agent to the chain. | Last: the chain ends at the server's agent name. A workflow that includes an MCP server lists it last. | | Workflow shapes it needs, with the reference admission policy | `[orchestrator]` for the first gateway, `[orchestrator, retriever]` for the second, one workflow per shape. | `[retriever, mcp-agent]` when the retriever calls the server; a separate `[mcp-agent]` workflow if a user's own MCP client may call it directly. | | What is forwarded | The JSON-RPC request to the card's interface URL on the configured host; the agent's response, or a JSON-RPC error frame in a stream. | The MCP request unchanged, to the server's endpoint URL with the request's query appended; `Mcp-Session-Id` and the server's status and body pass through, streamed for SSE, except that with capability checks on the server's `tools/list`, `resources/list` and `prompts/list` answers are filtered to what the caller may use. | | What the protected target can do with the chain | With a Token Service: read `X-IK-Token` and call IndyKite APIs with it, so its own policies see `$ik_token`, or exchange it again at the Token Service for its next hop. Without one, it receives the delegation token in `Authorization` only. | The IndyKite MCP server validates `X-IK-Token` itself and its policies see `$ik_token`; a third-party server just receives the headers. | | Refusals specific to the mode | The gateway serves the agent card at `/.well-known/agent-card.json`, public without a token, extended with one, and public again for a caller the gateway refuses (see [HTTP behaviour](#http-behaviour)). The card's interface URLs are rewritten to the scheme and host of `base_url`, and a card that cannot be used, or a redirect off that host, fails with `502`. With capability checks on, the extended card lists only the skills the caller may use, and with `ibac.enabled` and an intent in the delegation token, of them only the skills that fit that intent; with capability checks off, of every skill of the agent only the ones that fit it. With `ibac.enabled` and a Token Service, a message whose intent fits no skill of the agent the caller may use is refused with `403`. | A request to any path other than the endpoint path is answered `404` before the token is read, except the two OAuth metadata paths, which are public. A `401` carries a `WWW-Authenticate` challenge that links the gateway's protected resource metadata (see [OAuth discovery](#oauth-discovery)). Then the protocol-revision and request-classification checks of the [mcp mode table](#http-behaviour), answered as JSON-RPC errors before authorization. With capability checks on, an invocation outside the caller's permitted set is answered `403` with the JSON-RPC error `-31403`, and a list of a kind the caller may use nothing of is answered empty, without the server. With `ibac.enabled` and an intent in the delegation token, the lists are also filtered to the entries that fit the intent, and a call the intent does not match, or whose data the platform denies, is answered `403`. | Everything about the chain itself is identical: the delegation token is exchanged on every hop, the admission policy compares the chain with the agent path of a workflow the subject may trigger, and the audit record carries `actorsChain`. Three refusals follow from the reference policy and look the same in both modes, `403` with `{"message": "Authorization check failed"}` and, in the audit record, the one reason `subject / may not reach / through the delegation chain`; which of the three it was is read from `actorsChain` and the graph: - **Skipping a hop.** A user sends their own token straight to the retriever's or the MCP server's gateway. The gateway exchanges it, the chain is `[retriever]` or `[mcp-agent]`, and unless a one-agent workflow with that shape exists, the policy finds no matching path. Modelling the direct shape as its own workflow is how you allow it deliberately. With a Token Service this case is already refused with `401`, since the user's token is not issued for that agent. - **Reusing a token across workflows.** A delegation token minted for `[orchestrator, notifier]` is presented to the retriever's gateway. The exchange appends the retriever, and the chain `[orchestrator, notifier, retriever]` is the path of no workflow. A token therefore cannot be replayed from one workflow into another, even by an agent that is legitimately part of both. - **Right chain, wrong user.** The chain is the path of a workflow, but no `CAN_TRIGGER` relationship links this subject to it. On a shared agent, two users with the same chain get their own answer, since the subject is always the user of the token. The example that follows runs in a2a mode for both gateways; the [MCP tutorial](/tutorials/tutorial-agent-gateway-mcp) ends its chains at an MCP server and models the direct and the orchestrated shape as separate workflows. # From zero to a first authorized call The example protects one agent, the **retriever**, called by a user through the **orchestrator** agent: the workflow `wf1` is `user -> orchestrator -> retriever`. It is the shape the `a2a/` demos of the [developer-hub repository](https://github.com/indykite/developer-hub) run. Five steps, in the order they must happen. ## Step 1: Identity provider The gateway works with any OAuth 2.0 provider that offers the three things below over HTTP Basic client authentication. Create one confidential client per agent, plus the client your users log in with. | The provider must | Used for | | --- | --- | | Introspect tokens (RFC 7662) and report `active` and `sub` | Every incoming user or delegation token. | | Issue a token to a client with the client credentials grant | The protected agent's own token. Its `sub` is what appears in the delegation chain, so note it: it must be the agent's `external_id` in the graph. | | Exchange a subject token and an actor token for a delegation token (RFC 8693) whose `act.sub` is the actor, and nest the subject token's own `act` when it has one | Building the chain hop by hop. If your provider cannot nest, run the [Token Service](/guides/guide-token-service), which does the exchange instead; the provider then only needs the first two. | For this example: client `indykiteagent` (orchestrator) and client `indykiteagent-2` (retriever), each with a secret, and a login client for the user `millicent`. The gateway also needs a [Token Introspect](/guides/guide-token-introspect) configuration in your IndyKite project for the tokens it receives in `Authorization`, since it resolves the user through `whoami`; its `ikg_node_type` is the subject type of the admission policy in step 3. One configuration covers one issuer and audience pair. The delegation tokens need a matching configuration too, in both modes: the gateway sends the delegation token to the platform in `X-IK-Token` on its admission call, and the platform reads it only through a matching configuration. When the provider issues them with the same issuer and audience as the user tokens, the configuration above covers both; create a second one only when the pair differs, since a duplicate pair is refused with `409`. Without a Token Service these are the exchanged tokens of the provider; with one, the Token Service's issuer and `token_service.audience`, which always need their own configuration. Created with Service Account credentials: ```json POST /configs/v1/token-introspects Authorization: Bearer { "project_id": "gid:AAAABbbbCCCC...", "name": "iag-user-tokens", "display_name": "IAG user tokens", "jwt_matcher": { "issuer": "", "audience": "" }, "offline_validation": {}, "ikg_node_type": "User" } ``` The issuer must be an `https` URL on a public host. Check it with the user's token: `GET /contx-iq/v1/whoami` with `X-IK-ClientKey` and `Authorization: Bearer ` must answer `{"type": "User", "id": "millicent"}`. ## Step 2: Graph data Four kinds of nodes and two kinds of relationships, loaded with the Capture API and AppAgent credentials (`X-IK-ClientKey`). The user is an identity node whose `external_id` is the `sub` of their token; each agent's `external_id` is the `sub` of its client-credentials token. ```json POST /capture/v1/nodes { "nodes": [ { "external_id": "millicent", "type": "User", "is_identity": true, "properties": [ { "type": "email", "value": "millicent@canbank.com" } ] }, { "external_id": "wf1", "type": "Workflow" }, { "external_id": "indykiteagent", "type": "Agent" }, { "external_id": "indykiteagent-2", "type": "Agent" } ] } ``` The workflow is a path of `INVOKES` relationships from the `Workflow` node through the agents in call order. Every relationship carries `workflow_name` equal to the workflow's `external_id`; that property is what keeps two workflows apart when they share agents. The user is linked to the workflow with the relationship the KBAC policy will match, here `CAN_TRIGGER`. ```json POST /capture/v1/relationships { "relationships": [ { "source": { "type": "Workflow", "external_id": "wf1" }, "target": { "type": "Agent", "external_id": "indykiteagent" }, "type": "INVOKES", "properties": [ { "type": "workflow_name", "value": "wf1" } ] }, { "source": { "type": "Agent", "external_id": "indykiteagent" }, "target": { "type": "Agent", "external_id": "indykiteagent-2" }, "type": "INVOKES", "properties": [ { "type": "workflow_name", "value": "wf1" } ] }, { "source": { "type": "User", "external_id": "millicent" }, "target": { "type": "Workflow", "external_id": "wf1" }, "type": "CAN_TRIGGER" } ] } ``` **One workflow per call shape.** A workflow holds exactly one agent list. If the same agent is reached by two paths, model two workflows (for example `wf3` for `user -> analyst` and `wf3-console` for `user -> orchestrator -> analyst`). ## Step 3: KBAC admission policy One policy per subject type and agent type, with the action from `authzen.action` and the resource type of the protected agents, `Agent` here. The subject type is the `ikg_node_type` of the Token Introspect configuration from step 1. The condition does the whole check: the subject may trigger a workflow whose `INVOKES` path, agent by agent, equals the delegation chain the gateway sends as `$ik_token.act_chain`, and that path ends at the resource, the protected agent. One such policy serves every gateway whose agent has that type. Created with Service Account credentials: ```json POST /configs/v1/authorization-policies Authorization: Bearer { "project_id": "gid:AAAABbbbCCCC...", "name": "user-can-reach-agent", "display_name": "User can reach agent through a workflow", "policy": "{\"meta\":{\"policy_version\":\"2.0-kbac\"},\"subject\":{\"type\":\"User\"},\"actions\":[\"CAN_TRIGGER\"],\"resource\":{\"type\":\"Agent\"},\"condition\":{\"cypher\":\"MATCH (subject:User)-[:CAN_TRIGGER]->(wf:Workflow) MATCH (wf)-[rels:INVOKES*]->(resource:Agent) WHERE ALL(r IN rels WHERE r.workflow_name = wf.external_id AND endNode(r):Agent) AND [r IN rels | endNode(r).external_id] = $ik_token.act_chain\"}}", "status": "ACTIVE" } ``` A request is admitted when the token's chain equals the agent path of a workflow the subject may trigger: `[indykiteagent, indykiteagent-2]` passes for `wf1` at the retriever's gateway; `[indykiteagent-2]` alone or `[indykiteagent, indykiteagent-3, indykiteagent-2]` does not. The policy matches the upstream hops by `external_id` among `Agent` nodes; to also require that each hop's type equals the node's, add `AND [r IN rels | endNode(r).type] = $ik_token.act_chain_types` as the [AuthZEN guide](/guides/guide-authzen#token-claims-in-cypher) shows, which needs every hop to carry `act.type`: the Token Service writes it, and a hop without one yields a `null` entry that equals no type. To restrict one gateway to some workflows, give it `authzen.input_params` such as `workflow_ids: ["wf1"]` and a tag in `authzen.policy_tags`, and add `AND wf.external_id IN $workflow_ids` to a copy of the policy that carries that tag. Check it the way the gateway will, with the AppAgent credential and a delegation token whose chain is `[indykiteagent, indykiteagent-2]` in `X-IK-Token` (the platform needs the Token Introspect configuration for it from step 1): ```json POST /access/v1/evaluation X-IK-ClientKey: Authorization: Bearer X-IK-Token: { "subject": { "type": "User", "id": "millicent" }, "action": { "name": "CAN_TRIGGER" }, "resource": { "type": "Agent", "id": "indykiteagent-2" } } ``` ```json { "decision": true } ``` ### Capability checks: what the caller may use Admission decides whether the chain may reach the agent. With `authzen.capabilities.enabled` on, the default, a gateway in front of an MCP server also decides which tools, resources and prompts the caller may use on it, and a gateway in front of an A2A agent shows the caller only the skills they may use on the extended card. For each kind a request needs, the gateway reads the **permitted set** with one resource search, with the same headers and `context` as the admission call: ```json POST /access/v1/search/resource X-IK-ClientKey: X-IK-Token: { "subject": { "type": "User", "id": "millicent" }, "action": { "name": "CAN_USE" }, "resource": { "type": "Tool" } } ``` The identifiers in the answer are what the caller may use: tool names, resource URIs, prompt names, skill ids. Each capability is a node of the label configured for its kind (`Tool`, `McpResource`, `Prompt` and `Skill` by default) whose `external_id` is the identifier exactly as the protocol carries it, attached to its agent with a `HAS` relationship whose `workflow_name` confines it to one workflow: ```plain (:Workflow)-[:INVOKES {workflow_name}]->(:Agent)-[:HAS {workflow_name}]->(:Tool {external_id}) (:Agent)-[:HAS {workflow_name}]->(:McpResource {external_id}) (:Agent)-[:HAS {workflow_name}]->(:Prompt {external_id}) (:Agent)-[:HAS {workflow_name}]->(:Skill {external_id}) ``` For the retriever of this example, a skill `read-document` it may offer within `wf1` (a tool of an MCP server is modelled the same way, as a `Tool` node named after the tool): ```json POST /capture/v1/nodes X-IK-ClientKey: { "nodes": [ { "external_id": "read-document", "type": "Skill" } ] } ``` ```json POST /capture/v1/relationships X-IK-ClientKey: { "relationships": [ { "source": { "type": "Agent", "external_id": "indykiteagent-2" }, "target": { "type": "Skill", "external_id": "read-document" }, "type": "HAS", "properties": [ { "type": "workflow_name", "value": "wf1" } ] } ] } ``` One policy per label, with the action of `authzen.capabilities.action`. Its first half is the admission condition, so a non-empty set proves admission, and the last comparison keeps a capability attached for one workflow out of every other workflow that reaches the agent: ```json POST /configs/v1/authorization-policies Authorization: Bearer { "project_id": "gid:AAAABbbbCCCC...", "name": "user-can-use-skill", "display_name": "User can use a skill of an agent reached through a workflow", "policy": "{\"meta\":{\"policy_version\":\"2.0-kbac\"},\"subject\":{\"type\":\"User\"},\"actions\":[\"CAN_USE\"],\"resource\":{\"type\":\"Skill\"},\"condition\":{\"cypher\":\"MATCH (subject:User)-[:CAN_TRIGGER]->(wf:Workflow) MATCH (wf)-[rels:INVOKES*]->(agent:Agent)-[h:HAS]->(resource:Skill) WHERE ALL(r IN rels WHERE r.workflow_name = wf.external_id AND endNode(r):Agent) AND [r IN rels | endNode(r).external_id] = $ik_token.act_chain AND h.workflow_name = wf.external_id\"}}", "status": "ACTIVE" } ``` - The same policy with `Tool`, `McpResource` or `Prompt` as the resource type serves the other kinds. Kinds that share one label share one search; the sets of different labels are never merged, so a tool and a prompt with the same name are two capabilities. - A caller the platform admits nowhere matches no path, so the search finds nothing: an empty list on a discovery, `403` on an invocation. Not admitted, admitted with nothing permitted and nothing modelled look the same, by design; the audit record carries the permitted set. - A deployment that models no capabilities switches the checks off with `authzen.capabilities.enabled: false` (`JARVIS_AUTHZEN_CAPABILITIES_ENABLED=false`); every request then gets the admission decision alone, as before the checks existed. With the checks on and nothing modelled, every list is empty, every invocation is refused, and the extended card lists no skill. ## Step 4: Configure and run the gateway The smallest useful configuration for the retriever's gateway, with audit records written to a file. Secrets are shown as placeholders; the file is not environment-expanded, so either write the values in or set them through `JARVIS_` variables, which override the file (see [Configuration](#configuration)). ```yaml service: name: retriever-iag port: 8888 # public URL of this gateway, written into the agent card it serves base_url: https://retriever-iag.example.com identity_provider: base_url: https://idp.example.com/oauth/v2/ introspect_endpoint: oauth-introspect client_credential_endpoint: oauth-token exchange_endpoint: oauth-token # security scheme named in the served agent card openid_configuration_url: https://idp.example.com/.well-known/openid-configuration protected_agent: base_url: http://retriever:6002 protocol: a2a authentication: client_id: indykiteagent-2 client_secret: authzen: base_url: https://eu.api.indykite.com/access/v1 action: CAN_TRIGGER # optional: restrict this gateway through a tagged copy of the admission policy # input_params: # workflow_ids: ["wf1"] # policy_tags: ["pinned"] contx_iq: base_url: https://eu.api.indykite.com/contx-iq/v1 app_agent_credentials_token: audit: delivery: file file: storage_path: /app/audit format: json rotation_strategy: size-and-time ``` ```bash docker run -d \ --name retriever-iag \ -p 8888:8888 \ -v $(pwd)/config.yaml:/app/config.yaml:ro \ -v $(pwd)/audit:/app/audit \ indykite/agent-gateway: \ --config=/app/config.yaml ``` The audit directory must be writable by user 65532, the user the container runs as. The orchestrator gets its own gateway with `client_id: indykiteagent` and its own `base_url`; the orchestrator agent is configured to call the retriever through `retriever-iag`, not directly. ## Step 5: Test A probe without a token proves the gateway is up and enforcing, and writes an audit record: ```bash curl -i -X POST http://localhost:8888/ -H "Content-Type: application/json" -d '{}' # HTTP/1.1 401 Unauthorized # {"message":"Missing bearer token"} ``` A real call needs a delegation token whose chain is `[indykiteagent]`, the token the orchestrator receives from its own gateway. In the demos the orchestrator makes this call. To make it by hand, obtain a token for the user, exchange it at the provider with the orchestrator's client credentials as actor, and send the result: ```bash curl -s -X POST http://localhost:8888/ \ -H "Authorization: Bearer $DELEGATED_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "message/send", "params": { "message": { "role": "user", "messageId": "m-1", "parts": [ { "kind": "text", "text": "Which policy documents pertain to refunds?" } ] } } }' ``` On `200` the body is the retriever's JSON-RPC response. A user without the `CAN_TRIGGER` relationship, or a chain that is not `[indykiteagent]`, gets: ```json { "message": "Authorization check failed" } ``` The status alone does not say why. Read the audit record, whose `reason` does; it names the subject as `/`, while `subject` stays the token's `sub`: ```json { "decision": "NOT_AUTHORIZED", "reason": "subject User/carol may not reach Agent/indykiteagent-2 through the delegation chain", "subject": "carol", "actor": "indykiteagent-2", "action": "noop", "service": "retriever-iag", "timestamp": "2026-09-30T09:12:00.123456789Z", "traceID": "4bf92f3577b34da6a3ce929d0e0e4736", "actorsChain": [ "indykiteagent", "indykiteagent-2" ] } ``` ## Troubleshooting | Symptom | Cause | Fix | | --- | --- | --- | | `401` `{"message":"Unauthorized","errors":["identity provider: the token is not active"]}` | The user or delegation token is expired or unknown to the provider. | Obtain a fresh token; check the provider's introspection endpoint in `identity_provider`. | | `401` `Invalid token, missing act claim` | The exchange returned a token without `act`: the provider did not perform a delegation, or the token sent was not exchanged. | Confirm the provider's RFC 8693 support, or run the Token Service. | | `403`, audit reason `subject / may not reach / through the delegation chain` | The admission policy answered `false`. Either the chain (`actorsChain` in the record) is the `INVOKES` path of no workflow: the agents' `external_id` differ from the token subs, a hop is missing because the provider does not nest `act`, or the workflow shape is not ingested; or no `CAN_TRIGGER` relationship links the subject to that workflow, the subject node is missing or is not an identity node; or no ACTIVE policy exists for the subject type (the `ikg_node_type` of the Token Introspect configuration) and the agent type named in the reason; or the policy reads an `input_params` value this gateway does not send. | Replay the evaluation of step 3 by hand with the same subject, agent and `X-IK-Token`, then compare `actorsChain` with the workflow's path in the graph. | | Every `tools/list` comes back empty, `tools/call` answers `403` with JSON-RPC `-31403` `Forbidden: the caller may not use the named tool`, or the extended card lists no skill | Capability checks are on (the default) and the caller's permitted set is empty: no `Tool`, `McpResource`, `Prompt` or `Skill` node is attached to the agent with a `HAS` relationship carrying the workflow name, no `CAN_USE` policy exists for the label, or the caller is admitted to no workflow that reaches the agent. The `DISCOVERY` or `INVOCATION` record shows the `permittedSet`. | Model the capabilities and create one policy per label ([Capability checks](#capability-checks-what-the-caller-may-use)), or set `authzen.capabilities.enabled: false` on that gateway. | | An A2A message is refused with `403` `Authorization check failed` although admission is `AUTHORIZED`; the `INTENT` record says `none fits the skills of the agent` | `ibac.enabled` with a Token Service: no skill of the agent the caller may use covers any evaluation of the intent. Either the caller has no permitted skill on that agent (no `Skill` node attached with a `HAS` relationship for the workflow, or no `CAN_USE` policy for `Skill`), or the `x-coaz-mappings` of the permitted skills name other subject types, resource types or actions than the intent, or `ibac.capabilities.unmapped` is `deny` and the skills have no mapping. The `IBAC_DISCOVERY` record lists each evaluation with the skills it matched. | Model the skills of the agent and give them mappings that match the policies the intent uses; or switch capability checks off for that gateway (`authzen.capabilities.enabled: false`), so every skill on the agent's cards counts. | | An MCP call answers `403` with `Forbidden: the named tool does not match the intent` (or `resource`, `prompt`) | `ibac.enabled` is on and the delegation token carries an intent: no evaluation of that intent matches a mapping of the capability by subject type, resource type and action, or the call lacks an argument a mapping reads. The `IBAC_USAGE` record has `reasonCode` `intent_mismatch`, and `currentIntent` shows the intent it was checked against. | Compare `currentIntent` with the `x-coaz-mappings` of the capability; send the argument the mapping reads; or correct the mapping on the server. | | An MCP call answers `403` with `Forbidden: the caller may not access the data the named tool uses` | The intent matches, and the platform denied one of the evaluations resolved from the matched mappings: no KBAC policy lets this subject do that action on that resource, or `authzen.policy_tags` is set and the policy carries none of the tags. The `RESOLVED_EVALUATIONS` record lists each evaluation with `allowed`. | Read `resolvedEvaluations` in the record, then replay the denied one with `POST /access/v1/evaluations` and create or correct the policy. | | Decision `ERROR` on a `DISCOVERY` or `INVOCATION` record; the caller gets the platform's status or `500` | The resource search for the permitted set failed. The error is kept for `authzen.cache_update_after_error`. | Check the AppAgent credential and the Token Introspect configuration for the delegation tokens, as for an admission `ERROR`. | | The agent behind a later hop gets no `Authorization` header | `authorization_header.forward` is `correct_audience` (the default) and the bearer token of the hop is not issued for this agent, or it is `none`. | Issue the user's token for every agent that needs it in `Authorization`, or set `forward: all` on that gateway. | | A browser client reports a CORS error, while the same request from `curl` works | The page's origin is not in `cors.allowed_origins` (empty by default), so the gateway sends no CORS headers on the MCP endpoint, the JSON-RPC paths or the extended card, and the browser refuses the answer. | Add the page's exact origin, `scheme://host[:port]`, to `cors.allowed_origins`. If the MCP server behind the gateway checks `Origin` itself, allow the same origin there. | | Decision `ERROR`, reason `the delegated token names the protected agent , protected_agent.node_type is ` | The token's `act.type` and the configured `protected_agent.node_type` differ, so the resource type of the admission call is ambiguous; every request is refused. | Remove `protected_agent.node_type`, or make it equal to the issuer's actor type (`idp.actor_type` of the Token Service). | | `403`, audit reason `the delegation chain cannot be read` | A hop of the delegation token's `act` chain has no usable `sub`, or a `type` that is not a non-empty string. | Inspect the delegation token the exchange returns; check the issuer's `act` nesting. | | `401` `{"message":"Unauthorized","errors":["ContX IQ whoami failed"]}`, audit reason `cannot resolve the subject of the access token` | No Token Introspect configuration in the project matches the issuer and audience of the token in `Authorization`, or the token fails its validation. | Call `GET /contx-iq/v1/whoami` by hand with the same token and add or fix the configuration (step 1). | | Decision `ERROR`, reason `cannot authenticate protected agent` | The provider refused the client credentials grant. | Check `protected_agent.authentication` and the client at the provider. | | Decision `ERROR`, reason `unable to evaluate the admission of subject /`, caller gets `401` or `403` with `["evaluating admission through AuthZEN failed"]` or `500` | AuthZEN could not be reached, refused the AppAgent credential, or could not read the delegation token in `X-IK-Token` because no Token Introspect configuration matches its issuer and audience. The error is cached for `authzen.cache_update_after_error`. | Check `app_agent_credentials_token`, its API permissions, the region base URL, and the Token Introspect configuration for the delegation tokens (step 1). | | No audit records although `JARVIS_AUDIT_*` variables are set | The `audit` section must exist in a configuration file; environment variables only override its values. | Mount a file with at least `audit.delivery` and pass `--config`. | | Gateway starts, webhook auth fails, or the async queue is 512 whatever you set | The webhook auth and queue keys are read under the compact names given in parentheses in the audit table below. | Write `apikey`, `apikeyheader`, `mtlscertificatepath`, `mtlsprivatekeypath`, `buffersize`. | # Configuration The gateway reads one YAML file passed with `--config=`, or a directory of `.yaml`, `.yml`, `.json` or `.toml` files merged in alphabetical order with `--config-dir=`; the two flags are mutually exclusive. Rules that apply to every key: - **Environment overrides.** Upper-case the key path, replace dots with underscores, prefix `JARVIS_`: `protected_agent.authentication.client_secret` is `JARVIS_PROTECTED_AGENT_AUTHENTICATION_CLIENT_SECRET`. A variable replaces the file value. `service.port` also honours `PORT`. - **Lists** set from the environment are split on whitespace: `JARVIS_PROTECTED_AGENT_AUTHENTICATION_AUDIENCES="aud-1 aud-2"`. - **No expansion.** `${VAR}` in the file is a literal string. Put secrets in the file or in `JARVIS_` variables. - **The audit section is the one exception to "everything from the environment".** Audit is enabled by the presence of `audit` in a file; variables cannot create it, only override its values. Every other section works from variables alone. - The gateway listens on plain HTTP. Terminate TLS in front of it. It calls the identity provider and the Token Service with HTTP Basic client authentication and a 10 second timeout, and the IndyKite APIs with a 10 second timeout. ## service | Key | Default | Meaning | | --- | --- | --- | | `service.name` | `service` | Name of this instance, written to every audit record and audit file name. Set it; the default is the binary name. | | `service.port` | `8888` | Listening port. | | `service.base_url` | | Public URL of the gateway, required in both modes. In `a2a` mode every interface URL in the agent cards the gateway serves is replaced with it, so callers never reach the agent directly. In `mcp` mode it is the full public URL of the MCP endpoint at the gateway, with its path and without a query, credentials or fragment, for example `https://agents.example.com/mcp/v1/gid:AAAA…`: the gateway serves MCP on that path only, and its OAuth protected resource metadata names it (see [OAuth discovery](#oauth-discovery)). Write the path unencoded, `gid:` and not `gid%3A`. It is a setting rather than the host of the request because, behind an ingress, the scheme and host of a request are not the public ones and the `Host` header is chosen by the caller. | | `service.healthcheck_port` | `9080` | Port of `/healthz`, `/readyz` and `/startupz`, probed by the image's `HEALTHCHECK`. | | `service.environment` | | Free label such as `prod` or `demo`. | | `service.log_level` | `info` | `debug`, `info`, `warn` or `error`; JSON logs on standard output. At `debug` the log shows the chain and the platform answers per request. | ## identity_provider (required) | Key | Meaning | | --- | --- | | `identity_provider.base_url` | Provider base URL; the endpoints below are joined to it. | | `identity_provider.issuer` | Required in `mcp` mode: the issuer identifier of the identity provider, exactly as it appears in its metadata and in the `iss` of its tokens, an absolute URL without a query or fragment, for example `https://idp.example.com/realms/main`. The gateway's protected resource metadata lists it in `authorization_servers`, and an MCP client builds the provider's metadata URL from it. | | `identity_provider.introspect_endpoint` | Token introspection endpoint. | | `identity_provider.client_credential_endpoint` | Token endpoint for the client credentials grant. | | `identity_provider.client_credential_audience` | Optional: the `audience` parameter of the client credentials grant for the token of the protected agent, one value. Left out, the grant names no audience. Set it for an identity provider that refuses a grant without an audience; Auth0 does: use the identifier of an API registered there, and authorize the application of the agent for that API. The token is read by the service that does the token exchange, so with the IndyKite Token Service and a `jwt` matcher for actor tokens, the matcher must name the same audience. The token for the Intent Agent keeps `intent_agent.audience`. | | `identity_provider.exchange_endpoint` | Token endpoint for the exchange grant, used when no Token Service is configured. Usually the same endpoint. | | `identity_provider.client_credential_renew_before` | Optional, default `10s`: how long before its expiry a kept client credentials token is renewed, leaving time for the token to reach its recipient and for a clock difference. `0` takes the default; a negative value is refused at startup. | | `identity_provider.openid_configuration_url` | OpenID Connect discovery URL of the identity provider, required in `a2a` mode: the security scheme the served agent cards name, where callers obtain their token. | ## token_service (optional) When present, the issuer it names mints the delegation token, the IndyKite Token Service or an identity provider that meets the requirements below, and the gateway forwards it in `X-IK-Token` beside the caller's `Authorization`. A workflow then starts only at the agent the user's token was issued for, and a later hop needs only its `X-IK-Token`. All keys below except `audience` are then required; `identity_provider` stays required for introspection and the actor token, and `protected_agent.authentication.audiences` becomes required. | Key | Meaning | | --- | --- | | `token_service.base_url` | Where the gateway reaches the issuer, e.g. `http://token-service:8102`. | | `token_service.exchange_endpoint`, `introspect_endpoint` | `oauth2/token` and `oauth2/introspect` for the IndyKite Token Service. | | `token_service.audience` | Optional: the audience asked for in every exchange, so the audience of every delegation token; `protected_agent.authentication.audiences` when left out. The delegation token travels on to the next gateway, so every gateway of a deployment should ask for the same one, and the Token Service must list it in its `idp.audiences`; a value it does not list is refused with `invalid_target`. The Token Introspect configuration that lets the platform resolve delegation tokens names this audience. | | `token_service.client_auth.type` | Only `client_secret_basic`. | | `token_service.client_auth.client_id`, `client_secret` | The credentials the issuer expects from gateways (for the IndyKite Token Service, its own `idp.client_auth`), not the identity provider credentials. | An identity provider named here instead of the IndyKite Token Service has to support the RFC 8693 exchange with the user's access token as `subject_token` and the protected agent's client credentials token as `actor_token`; take its own delegated token as `subject_token` on a later hop and nest the previous `act` in the new one; keep the `sub` of the subject token and write the actor as `act.sub`; and answer RFC 7662 introspection of the tokens it issued with their `act` claim, since a later hop refuses an `X-IK-Token` without one. Two features depend on what it writes into `act`, both of which the IndyKite Token Service writes: `act.type` on every level, without which the platform looks each actor up by `external_id` alone, which then has to be unique, and `$ik_token.act_chain_types` holds `null` for each hop without a type, so a comparison of that list with a fully typed graph path denies; and `act.intent`, the intent of the hop. Without `token_service`, the identity provider's own exchange at `identity_provider.exchange_endpoint` is used. The gateway still sends the delegation token it minted in `X-IK-Token` on its admission call, so the admission policy reads the chain as `$ik_token.act_chain` in both modes. What changes is the forwarded request: the delegation token replaces the subject token in `Authorization`, so when the protected agent calls the platform with it, the agent's own policies read it as `$token`. The entry-agent rule, the later hop without `Authorization` and the `same_user_check` apply only with `token_service`. ## protected_agent (required) | Key | Meaning | | --- | --- | | `protected_agent.base_url` | In `a2a` mode, where the agent card is read; requests go to the JSON-RPC URL the card declares. In `mcp` mode, the full URL of the MCP endpoint of the server, with its path, unencoded, without a fragment, and with its query when the server needs one, for example `http://mcp-server:8080/mcp/v1/gid:AAAA…`. Every request the gateway accepts goes to this URL, with the request's query appended after the configured one; the request path is not used to build it. Its path may differ from the path of `service.base_url`. | | `protected_agent.protocol` | `a2a` (default) or `mcp`. | | `protected_agent.node_type` | Optional, no default: the IKG node type of the protected agent, the resource type of the admission evaluation, used only when the delegation token of this hop carries no `act.type`. Without either, the type is `Agent`. When the token has `act.type` (the IndyKite Token Service writes its `idp.actor_type`, `Agent` by default), that type is used; when it differs from this setting, every request is refused with an `ERROR` record naming both. | | `protected_agent.authentication.client_id`, `client_secret` | The protected agent's client at the identity provider, used for the client credentials grant. | | `protected_agent.authentication.audiences` | Without `token_service`: optional list sent as `audience` on the exchange at the identity provider. With `token_service`: required, the audiences of user tokens this gateway accepts in `Authorization` as the start of a workflow (a token issued for none of them is refused with `401`), and the audiences asked for in the exchange unless `token_service.audience` is set. Each exchange audience must be in the Token Service's `idp.audiences`, otherwise the exchange is refused with `invalid_target`. From the environment, a space-separated list. | ## a2a (optional) | Key | Default | Meaning | | --- | --- | --- | | `a2a.cache_ttl` | `5m` | How long the protected agent's card, and the client built from it, are kept. | | `a2a.cache_update_after` | `cache_ttl` | Age after which the card is fetched again. Must not exceed `cache_ttl`. | | `a2a.cache_update_after_error` | `10s` | How long a failed card fetch is returned to every call before the next attempt. Must not exceed `cache_update_after`. | ## authorization_header (optional, with token_service) | Key | Default | Meaning | | --- | --- | --- | | `authorization_header.forward` | `correct_audience` | What the protected agent gets in `Authorization`; the delegation token goes in `X-IK-Token` with every value. `none`: nothing, so the agent cannot use the user's token to start a new workflow as the user. `correct_audience`: a bearer token only when the identity provider reports it active and its `aud` names one of `protected_agent.authentication.audiences`; a credential that is not a bearer token passes unchanged; any other bearer token is dropped and the request goes on; when the identity provider fails or answers `429` the request fails, since the gateway cannot tell whom the token is for. At the entry the user's token is always issued for this agent, so it is passed on. `all`: `Authorization` exactly as the caller sent it. | | `authorization_header.same_user_check` | `true` | On a later hop, refuse a bearer token in `Authorization` whose `sub` differs from that of the delegation token. It checks only a token the gateway passes on, so never with `forward: none`. Switch it off for a flow whose `Authorization` does not carry the user's token, such as the service token of the calling agent: the gateway then reads that token only to decide whether `correct_audience` passes it on, and is responsible for the delegation token alone. | A later hop whose bearer token is not passed on, or not checked, has no user's token: `whoami` and the admission call get the delegation token. With a Token Service the other headers of the caller are passed on to the agent, in both modes, except the headers of one connection (`Connection` and the headers it names, `Keep-Alive`, `Proxy-Authorization` and the like). Without one, an A2A agent gets no header of the caller, and an MCP server gets all of them except `Authorization`, `X-IK-Token` and `Accept-Encoding`. ## cors (optional) | Key | Default | Meaning | | --- | --- | --- | | `cors.allowed_origins` | empty | The origins a browser may call the gateway's token-protected paths from: the MCP endpoint in `mcp` mode, the JSON-RPC paths and the extended agent card in `a2a` mode. Each entry is an origin, `scheme://host[:port]`, without a path, query, fragment or credentials, for example `https://mcp-client.example.com`; the single entry `*` allows every origin. Empty, no origin is allowed. Origins are compared exactly, with the scheme and host lower-cased and the default port dropped. From the environment, `JARVIS_CORS_ALLOWED_ORIGINS` as a space-separated list. The public paths (OAuth metadata, public agent card) allow every origin whatever this setting says; see [CORS](#cors). | ## ibac and intent_agent (optional) With `ibac.enabled` on, a gateway in front of an A2A agent asks the [Intent Agent](/guides/guide-intent-agent#gateway) about every A2A message before forwarding it, and a gateway in front of an MCP server checks the mappings of invocations whose delegation token carries an intent, as described in [How a request is decided](#how-a-request-is-decided). Off, neither happens, and the `intent_agent` and `ibac.capabilities` settings are not read. The [IBAC engine guide](/guides/guide-ibac) covers the model behind the switch. | Key | Default | Meaning | | --- | --- | --- | | `ibac.enabled` | `false` | Switches IBAC on: the Intent Agent call in front of an A2A agent and, with `token_service`, the comparison of the intent of a message with the skills of the agent; the mapping check of invocations and the intent filter of the lists in front of an MCP server; and, in front of an A2A agent, the filtering of the extended agent card to the skills that fit the current intent of the delegation token: of the permitted skills with capability checks on, of every skill of the agent with them off. On, in front of an A2A agent, `intent_agent.base_url` is required. | | `ibac.capabilities.cache_ttl` | `5m` | In front of an MCP server: how long the gateway keeps a tool, resource or prompt, with its mappings, after the server last listed it. A list adds and refreshes entries and removes none, since a list can be one page of several. In front of an A2A agent: how long the gateway keeps the skills of the card the agent publishes and of the extended card, with their mappings, the same way; for a skill on both cards, the entry of the published card counts. Must be positive. | | `ibac.capabilities.unmapped` | `allow` | In front of an MCP server: what happens to the call of a capability without a mapping, when the delegation token carries an intent. `allow`: the call goes on and only the permitted set decides. `deny`: the call is refused with `403`. A mapping that cannot be read refuses the call in both settings. The setting applies to the lists of the server too: with `allow` an entry without a mapping stays in a list, with `deny` it is removed. In front of an A2A agent it applies to the skills, on the extended card and in the comparison of a message with the skills: with `allow` a skill without a mapping fits every intent, so it stays on the card and covers every evaluation of a message, with `deny` it fits none. A message does not name the skill it uses, so under `allow` one permitted skill without a mapping lets the whole intent through, whatever the mappings of the other skills: give every skill a mapping, or set `deny`. | | `intent_agent.base_url` | | Where the Intent Agent serves its agent card; an absolute `http` or `https` URL. | | `intent_agent.audience` | `intent_agent` | Audience of the client credentials token the gateway gets for the Intent Agent; must match the Intent Agent's `EXPECTED_TOKEN_AUDIENCE`. | | `intent_agent.timeout` | `45s` | How long one prompt may take, the token grant included; longer answers `504`. Must be positive. | | `audit.include_prompt` | `false` | Adds the prompt, the reason of a failed task, and the text the model answered with in place of an intent, to the `INTENT` audit records. Off, those records carry none of them, since all three can quote the user. | ## authzen (required) | Key | Default | Meaning | | --- | --- | --- | | `authzen.base_url` | | AuthZEN API of your region, e.g. `https://eu.api.indykite.com/access/v1`. | | `authzen.action` | | The action of the admission evaluation, the one the admission policy lists, e.g. `CAN_TRIGGER`. | | `authzen.input_params` | | Optional map sent as `context.input_params` in every admission call; a policy reads a value as `$name`, and the platform refuses a request that lacks a value the policy reads. A key has 2 to 20 lowercase letters, digits or `_` and starts with a letter; a text value has 1 to 256 bytes; the keys the platform fills are refused: `token`, `ik_token`, `subject_external_id`, `subject_id`, `subject_type`, `resource_external_id`, `resource_type`. From the environment, the whole map as JSON in `JARVIS_AUTHZEN_INPUT_PARAMS`. | | `authzen.policy_tags` | | Optional list sent as `context.policy_tags` in every admission call, so that only policies carrying at least one of the tags apply. A tag has 1 to 20 letters or digits, listed once. From the environment, space-separated. When a project uses tags, every gateway of the project should send them: a call without tags also reaches the tagged policies and their required parameters. | | `authzen.subject_types` | | Not read: the subject type comes from `whoami`. A value left over from an older configuration is ignored. | | `authzen.cache_ttl` | `5m` | How long an admission decision is kept, per subject, resource type, chain and token claims, and how long a permitted set is kept, per subject, action, label, chain and token claims; an empty set too. Also how long the platform's answers to the resolved evaluations of an MCP call are kept, per subject, chain, evaluations and token claims; a denial and a failed call too. | | `authzen.cache_update_after` | `cache_ttl` | Age after which a decision or a set is refreshed in the background by the next request that uses it; the last good value keeps being served for up to 12 hours while the platform is unreachable. With the default it coincides with expiry, so a value is read again only once it expired. Must not exceed `cache_ttl`. | | `authzen.cache_update_after_error` | smaller of `10s` and `cache_update_after` | How long a failed evaluation or a failed search is served before a retry. Must not exceed `cache_update_after`. | | `authzen.capabilities.enabled` | `true` | The [capability checks](#capability-checks-what-the-caller-may-use): the permitted set of the caller in front of an MCP server, and the filtering of the extended card in front of an A2A agent. Off, the gateway asks no capability question and every request gets the admission decision. `JARVIS_AUTHZEN_CAPABILITIES_ENABLED`. | | `authzen.capabilities.action` | `CAN_USE` | The action of every capability search, the one the capability policies list. An empty value stops the gateway at startup. `JARVIS_AUTHZEN_CAPABILITIES_ACTION`. | | `authzen.capabilities.labels.tools`, `resources`, `prompts`, `skills` | `Tool`, `McpResource`, `Prompt`, `Skill` | The IKG node types of the capabilities of each kind, the resource type of the search for that kind. Two kinds may share a label and then share one search; a label set to an empty value stops the gateway at startup. `JARVIS_AUTHZEN_CAPABILITIES_LABELS_TOOLS` and so on. | ## contx_iq (required) | Key | Meaning | | --- | --- | | `contx_iq.base_url` | ContX IQ API of your region, e.g. `https://eu.api.indykite.com/contx-iq/v1`. | | `contx_iq.app_agent_credentials_token` | The Application Agent credential token, sent as `X-IK-ClientKey` to ContX IQ `whoami` and to AuthZEN. | | `contx_iq.cache_ttl` | Default `5m`: how long a `whoami` answer is kept, `0` keeps none. | | `contx_iq.cache_update_after`, `cache_update_after_error` | Still checked at startup with the same ordering rules as under `authzen`, but without effect: a `whoami` answer is kept for `cache_ttl`. | | `contx_iq.query_id`, `contx_iq.allowed_workflow_id` | No longer used: the gateway runs no Knowledge Query. `query_id` is ignored; a non-empty `allowed_workflow_id` stops the gateway at startup. Restrict a gateway through the admission policy with `authzen.input_params` and `authzen.policy_tags` instead. | ## audit (optional, file only) Without an `audit` section nothing is recorded. With one, records are always delivered through a background queue so requests never wait for the sink; a full queue drops records with the log line `dropping payload, async queue is full`, and the queue is drained on shutdown. The five webhook authentication and queue keys are documented with their snake_case names; the compact name in parentheses is the one the current releases read. | Key | Meaning | | --- | --- | | `audit.delivery` | `file` or `webhook`; the matching sub-section is required. | | `audit.file.storage_path` | Directory for the files, named `audit--...`. Must be writable by user 65532. | | `audit.file.format` | `json`, `csv` or `txt`. | | `audit.file.rotation_strategy` | `time`, `size` or `size-and-time`. Required. | | `audit.file.rotation_interval`, `rotation_max_bytes` | Defaults `24h` and `104857600` (100 MiB). | | `audit.http.url`, `audit.http.method` | Webhook destination; method `POST` or `PUT`. Records are sent as JSON. | | `audit.http.auth.type` | `no-auth`, `api-key` or `mTLS`. | | `audit.http.auth.api_key` (`apikey`), `api_key_header` (`apikeyheader`) | For `api-key`; the header defaults to `X-API-Key`. | | `audit.http.auth.mtls_certificate_file_path` (`mtlscertificatepath`), `mtls_private_key_path` (`mtlsprivatekeypath`) | For `mTLS`; both required. | | `audit.async.buffer_size` (`buffersize`) | Queue length, default `512`. | | `audit.include_prompt` | Default `false`: whether the `INTENT` records carry the prompt, the reason of a failed task and the text the model answered with in place of an intent, see [ibac and intent_agent](#ibac-and-intent_agent-optional). | ## Startup errors A configuration problem stops the process with one of these messages in the log. | Message | Cause | | --- | --- | | `invalid identity_provider configuration: missing `, `invalid identity_provider configuration: client_credential_renew_before must not be negative` | One of the four identity provider keys is absent, or the renewal margin is negative. | | `missing authentication.audiences in protected_agent configuration`, `invalid authorization_header.same_user_check: …`, `invalid authorization_header.forward "…", must be one of none, correct_audience, all` | With `token_service`, the entry audiences are absent, `same_user_check` is not a boolean, or `forward` is none of the three values. | | `intent_agent.base_url is required when ibac.enabled is on in front of an A2A agent`, `intent_agent.base_url must be an absolute http or https URL`, `intent_agent.timeout must be positive` | Incomplete `intent_agent` section with `ibac.enabled` on. | | `ibac.capabilities.cache_ttl must be positive, got …`, `ibac.capabilities.unmapped must be allow or deny, got "…"` | An invalid value in the `ibac.capabilities` section. | | `invalid token_service configuration: missing `, `client_auth of type "client_secret_basic" requires client_id and client_secret`, `client_auth has invalid type "…" (want "client_secret_basic")` | Incomplete Token Service section. | | `cannot get protected_agent base_url`, `invalid protected_agent protocol`, `missing client_id in protected_agent configuration`, `missing client_secret in protected_agent configuration` | Incomplete protected agent section. | | `cannot get service base_url, the public URL of the gateway`, `service base_url must be an absolute URL`, `cannot get identity_provider openid_configuration_url` | In `a2a` mode, the settings the served agent card needs are absent. | | `protected_agent base_url must be the full URL of the MCP endpoint of the server, with its path, unencoded, and without a fragment`, `cannot get service base_url, the public URL of the MCP endpoint at the gateway`, `service base_url must be the full public URL of the MCP endpoint at the gateway, http or https, with its path, unencoded, and without credentials, a query or fragment`, `cannot get identity_provider issuer`, `identity_provider issuer must be an absolute URL without a query or fragment` | In `mcp` mode, one of the three endpoint settings is absent or malformed, for example a `protected_agent.base_url` without a path or a percent-encoded `gid%3A`. | | `missing required authzen.base_url`, `missing required authzen.action` | Incomplete AuthZEN section. An empty `authzen.capabilities.action` or an empty `authzen.capabilities.labels.*` value stops the gateway as well. | | `missing required contx_iq.base_url`, `missing required contx_iq.app_agent_credentials_token in configuration` | Incomplete ContX IQ section. | | `contx_iq.allowed_workflow_id is no longer supported: restrict the workflows in the admission policy and pass the values with authzen.input_params and authzen.policy_tags` | A configuration from before the admission policy still restricts the gateway to one workflow. | | `authzen.input_params must be a map: …`, `authzen.input_params: the key "…" is reserved, the platform fills it`, `authzen.input_params: the key "…" must have 2 to 20 lowercase letters, digits or underscores and start with a lowercase letter`, `authzen.input_params: the value of "…" must have 1 to 256 bytes`, `authzen.policy_tags: the tag "…" must have 1 to 20 letters or digits`, `authzen.policy_tags: the tag "…" is listed twice` | An `input_params` or `policy_tags` value the platform would refuse, including invalid JSON in `JARVIS_AUTHZEN_INPUT_PARAMS`. | | `
.cache_ttl must not be negative, got …`, `
.cache_update_after (…) must not exceed
.cache_ttl (…)`, `
.cache_update_after_error (…) must not exceed
.cache_update_after (…)` | Cache durations out of order, for `authzen`, `contx_iq` or `a2a`. | | `cors.allowed_origins: invalid origin "…", it must be scheme://host[:port] without a path, query, fragment or credentials`, `cors.allowed_origins: "*" must be the only entry` | An entry of `cors.allowed_origins` is not an origin (including `null`), or `*` is listed beside other origins. | | `invalid port value … - not in range` | `service.port` or `service.healthcheck_port` is not a valid TCP port. | | `audit: unknown delivery type "…", must be one of: file, webhook`, `audit: http url is required`, `audit: http method must be POST or PUT, got "…"`, `audit: unsupported auth type "…"`, `audit: api-key auth requires api_key`, `audit: mTLS requires mtls_certificate_file_path and mtls_private_key_path`, `audit: file storage path is required`, `audit: file rotation is required and must be one of "time", "size", "size-and-time"` | Incomplete audit section. The two auth messages name the keys in their snake_case form, but the values are read from `apikey`, `mtlscertificatepath` and `mtlsprivatekeypath`. | # Deployment The gateway ships as the Docker image `indykite/agent-gateway`: built from scratch with no shell, entrypoint `/app/service` so container arguments are the gateway flags, running as user `65532`, published for `linux/amd64` (add `platform: linux/amd64` on Apple Silicon), with a `HEALTHCHECK` on `http://localhost:9080/healthz` every 10 seconds after a 30 second start period. - **Pin a version tag** from the [tag list](https://hub.docker.com/r/indykite/agent-gateway/tags). A `latest` tag exists but lags weeks behind the newest release, so it silently gives an old image. The IndyKite demos pin the release they were built against. Run the Token Service on the same tag ([Token Service guide](/guides/guide-token-service#release-pairing)). This guide describes the newest release; an older image may lack a behaviour described here, so when something documented does not happen, move to a newer tag before looking elsewhere. - **Moving from the workflow query to the admission policy.** A deployment set up when the gateway still ran a ContX IQ Knowledge Query and an AuthZEN resource search needs, in this order: first, create the [admission policy](#step-3-kbac-admission-policy) (without it the new gateway refuses every request) and a Token Introspect configuration for the issuer and audience of the delegation tokens of every gateway, also without a Token Service; both are harmless to the old gateway. With the upgrade, remove any `contx_iq.allowed_workflow_id`, which stops the new gateway, and express the restriction with `authzen.input_params` and `authzen.policy_tags`. After the upgrade, remove `contx_iq.query_id`, which the new gateway ignores but the old one required, and delete the old `Workflow` trigger policy, the ContX IQ policy and the Knowledge Query it named. - **Capability checks are on by default.** A gateway in front of an MCP server, or in front of an A2A agent with an extended card, needs one of two things: the capabilities of the server and the skills of the agent modelled in the graph with one `CAN_USE` policy per label ([Capability checks](#capability-checks-what-the-caller-may-use)), or `authzen.capabilities.enabled: false` on that gateway. With the checks on and nothing modelled, every list comes back empty, every invocation is refused and the extended card lists no skill. With the checks on, a caller the platform admits nowhere gets an empty list on `tools/list` and `403` with a JSON-RPC error on `tools/call`. With the checks on or off, a `prompts/get` without a prompt name is refused with `400`. - **JSON-RPC codes of a refused caller.** A gateway in front of an A2A agent answers `-31401` (unauthenticated) and `-31403` (unauthorized) in a stream when the agent refuses the caller, codes outside the ranges the A2A specification and the MCP SDK assign, and a gateway in front of an MCP server refuses an invocation outside the permitted set with `-31403` too. A client built against an older image may still read `-32003` for these cases and needs to read both. - **Docker Compose.** One pattern for several agents is a base service with the shared `JARVIS_` variables (identity provider, IndyKite URLs, credential token, action), extended once per gateway with `JARVIS_SERVICE_NAME`, `JARVIS_PROTECTED_AGENT_BASE_URL`, the agent's client id and secret, and, to restrict a gateway to some workflows, `JARVIS_AUTHZEN_INPUT_PARAMS` and `JARVIS_AUTHZEN_POLICY_TAGS`. Mount a small file with the `audit` section and pass `--config`, since audit cannot be enabled from variables. Complete stacks, with a Token Service and MCP-protecting gateways, are in the `a2a/` folder of the [developer-hub repository](https://github.com/indykite/developer-hub). - **Kubernetes.** A plain `Deployment`; no Helm chart is published. Mount the configuration file from a `Secret` at `/app/config.yaml`, or keep it in a `ConfigMap` with the secrets in `JARVIS_` variables from a `Secret`. Run as a standalone Pod with its own `Service`, or as a sidecar in the agent's Pod with `protected_agent.base_url` set to `http://127.0.0.1:` and only the gateway port exposed. Probes: `/startupz`, `/readyz`, `/healthz` on port `9080`; `runAsUser: 65532`; a writable volume for file audit; egress to the identity provider, the IndyKite region, the protected agent and the audit webhook. # HTTP behaviour ## a2a mode - JSON-RPC is accepted on any path and any method. Supported methods: `message/send`, `message/stream`, `tasks/get`, `tasks/list`, `tasks/cancel`, `tasks/resubscribe`, the four `tasks/pushNotificationConfig/*` methods and `agent/getAuthenticatedExtendedCard`. - The gateway serves the agent card at `GET /.well-known/agent-card.json`: it is the card of the protected agent reduced to its JSON-RPC interfaces, each pointing at `service.base_url`, with the security scheme of the gateway's identity provider (`identity_provider.openid_configuration_url`) in place of the agent's on the card and on each skill, and without the agent's signatures. Without an `Authorization` header the answer is the public card, with no skills and `capabilities.extendedAgentCard` set; with a bearer token it is the extended card, after the same authentication and authorization as any other request. With an `Authorization` header the gateway would refuse with `401` or `403`, the answer is the public card as well: a header without a bearer token, a token that is not valid or not issued for this agent, a delegation token that cannot be used, or a caller that is not authorized. The refusal is audited as for any other request. A check that fails, such as an identity provider that does not answer, keeps its error. `agent/getAuthenticatedExtendedCard` answers with the same extended card; an agent that has no extended card answers with its own card. With capability checks on, the extended card lists only the skills the caller may use; when the permitted set cannot be read, the answer is an error and no card. With `ibac.enabled` and an intent in the delegation token, the card lists only the skills that fit the current intent, by their `x-coaz-mappings` and `ibac.capabilities.unmapped`: of the permitted skills with capability checks on, of every skill of the agent with them off; when the skills cannot be read with their mappings, the answer is an error and no card. Without an intent in the token the card is filtered to the permitted set only, or with capability checks off lists every skill. With a Token Service, both cards declare the delegated token extension in `capabilities.extensions`, with the identifier `https://indykite.com/extensions/delegated-token/v1` (a name, not a page) and `required: false`, in place of any declaration of that identifier the agent wrote, so a caller knows it may send its `X-IK-Token` to the agent. Both `service.base_url` and `identity_provider.openid_configuration_url` are required in `a2a` mode for this reason. - The gateway reads the agent card from `protected_agent.base_url` and calls the card's interface URLs with the scheme and host of that base URL, keeping only their path and query, so a card cannot send requests to another host. A card that lists a null supported interface, or an interface without a URL, cannot be used: the request fails with `502`. A redirect from the agent is followed only while it stays on the host, port and scheme of `base_url`, or upgrades `http` to `https` on port 443, and for at most 5 hops; any other redirect fails the request with `502`. - `message/stream` and `tasks/resubscribe` answer `200` with `text/event-stream` before the agent is contacted; an unreachable agent or a later failure arrives as a JSON-RPC error frame inside the stream; an agent that refuses the caller is reported there as `-31401` (unauthenticated) or `-31403` (unauthorized), and the A2A specification maps the other errors. ## mcp mode ![An MCP request in the Agent Gateway. Every request passes three gates. Path: only the path of service.base_url is served, any other path answers 404 before the token is read. Token: a missing or inactive bearer token answers 401 with a WWW-Authenticate challenge that links the protected resource metadata. Protocol: the request must be one JSON-RPC message on a supported protocol revision and name what it uses, otherwise a JSON-RPC error with 400, 413 or 415. Then it depends on the kind of request. A list, tools/list, resources/list or prompts/list, is filtered to the permitted set of the caller and, with ibac.enabled and an intent in the token, to the entries that fit the intent; nothing is refused and a list can come back empty. A call, tools/call, resources/read or prompts/get, must name a capability in the permitted set, otherwise 403 with the JSON-RPC error -31403; with ibac.enabled and an intent, it must also fit the intent by its mapping, and the platform must allow the resolved evaluations, otherwise 403. Any other request, such as initialize or a notification, gets the admission decision, one AuthZEN evaluation, and a denial answers 403. What passes is forwarded to the MCP server at protected_agent.base_url with the delegation token; Mcp-Session-Id and streamed responses pass through unchanged.](/assets/images/iag-mcp-request.svg) The picture is the overview of an MCP request: three gates, then what a list, a call or any other request gets. The paragraphs and the table below have the exact rules, codes and messages. The gateway serves MCP on one path, the path of `service.base_url`, compared with the request path exactly, trailing slash included and after percent-decoding, so a client that writes `gid%3A` still matches. Any other path is answered `404` with `{"message":"Not Found"}` before the token is read, except the two metadata paths of [OAuth discovery](#oauth-discovery); the MCP server's own paths beyond its endpoint, its metadata included, are not reachable through the gateway. Any MCP method on that path is forwarded after the checks pass, to the endpoint URL in `protected_agent.base_url` with the request's query appended, with `Mcp-Session-Id` and the response body passed through unchanged, streamed for SSE. The downstream server's status is returned as is, for example `202` for a notification or `404` for an unknown session. Requests must be on protocol revision `2025-06-18`, `2025-11-25` or `2026-07-28`; the checks run after introspection and before authorization, in this order: | Refusal | Status, JSON-RPC code, message | | --- | --- | | `Content-Encoding` other than `identity` | `415`, `-32600`, `Invalid Request: content coding is not supported` | | Body cannot be read | `400`, `-32700`, `Parse error: cannot read the request body` | | Body over 4 MiB | `413`, `-32600`, `Invalid Request: request body exceeds 4194304 bytes` | | `Mcp-Protocol-Version` present with an unsupported value, including on `initialize` | `400`, `-32022`, `Unsupported protocol version`, with `error.data.supported` and `error.data.requested` | | Header absent on any request other than `initialize`: GET for SSE, DELETE, notifications and client responses included | `400`, `-32020`, `Header mismatch: Mcp-Protocol-Version header is missing` | | JSON-RPC batch | `400`, `-32600`, `Invalid Request: JSON-RPC batching is not supported` | | Body that is not valid UTF-8 | `400`, `-32700`, `Parse error: the request body is not valid UTF-8` | | Body that is not exactly one JSON value: invalid JSON, two messages in one body, or text after the message | `400`, `-32700`, `Parse error: the request body is not one JSON value` | | JSON that is not a JSON-RPC 2.0 message: no `"jsonrpc": "2.0"`, or neither a `method` nor a `result` or `error` | `400`, `-32600`, `Invalid Request: the request body is not a JSON-RPC message` | | A key that can be read in more than one way, in the message itself, in the `params` of an invocation, or in `params.notifications` of a `subscriptions/listen`: a repeated key, a key that is not printable ASCII, or a key that differs from a field the gateway reads (`jsonrpc`, `method`, `params`, `name`, `uri`, `notifications`, `resourceSubscriptions`) only in letter case or in `_` and `-` characters | `400`, `-32600`, `Invalid Request: has a repeated key`, `Invalid Request: has a key that is not printable ASCII` or `Invalid Request: has a key that can be read as `, where `` is `the message`, `params` or `params.notifications` | | A method, tool name, prompt name or resource URI that contains a control character, a lone surrogate or the replacement character `U+FFFD` | `400`, `-32600`, `Invalid Request: the method contains a control character` or `Invalid Request: the method contains a lone surrogate or a replacement character`; the same two messages with `the tool name`, `the prompt name` and `the resource URI` | | An invocation that names nothing: `tools/call` whose `params.name` is missing, empty or not a string; `prompts/get` with such a `params.name`; `resources/read` or `resources/subscribe` with such a `params.uri`; `subscriptions/listen` whose `params.notifications.resourceSubscriptions` cannot be read | `400`, `-32602`, `Invalid params: tools/call names no tool`, `Invalid params: prompts/get names no prompt`, `Invalid params: names no resource URI` or `Invalid params: the resource subscriptions of subscriptions/listen cannot be read` | | On revision `2026-07-28`: an `Mcp-Method` header that differs from the `method` in the body, or an `Mcp-Name` header that differs from the tool name of a `tools/call`, the prompt name of a `prompts/get` or the resource URI of a `resources/read`. A value in the form `=?base64?…?=` is decoded before the comparison, and one that does not decode is refused the same way. A missing header is left to the server. | `400`, `-32020`, `Header mismatch: Mcp-Method header does not match the method in the body`, `Header mismatch: Mcp-Name header does not match the tool name in the body` (or `the prompt name`, `the resource URI`), `Header mismatch: Mcp-Name header is not valid Base64` | An `initialize` without the header is forwarded; if its `protocolVersion` is unsupported it is rewritten to `2025-11-25`. After the revision checks (the first six rows), the gateway reads what each request names: `tools/call` names a tool and `prompts/get` a prompt in `params.name`; `resources/read` and `resources/subscribe` name a resource in `params.uri`; `subscriptions/listen` names every URI in `params.notifications.resourceSubscriptions`; `tools/list`, `resources/list` and `prompts/list` are discovery. Every other message, such as `initialize`, a notification, a client response or a `resources/unsubscribe`, which only gives a resource up, names nothing and is forwarded as it is, as is a request without a body. Tool `arguments` and `_meta` are not checked, and a refusal message never repeats a value the client sent. The error body is a JSON-RPC response; `id` is present only when the request had one and the message could be read, so the two parse errors carry none. Every refusal is audited as `NOT_AUTHORIZED` with reason `MCP request refused: `. The [MCP guide](/guides/guide-mcp) covers the revisions themselves. With capability checks on, a discovery and an invocation then get the capability decision in place of the admission decision: the lists of a `tools/list`, `resources/list` or `prompts/list` answer are filtered to the caller's permitted set, in the server's order and with the cursor untouched, and the filtered list carries `cacheScope: private` and a `ttlMs` no longer than `authzen.cache_ttl`; a caller who may use nothing of the kind gets an empty list from the gateway, without the server, with `"resultType": "complete"` as revision `2026-07-28` requires in every result; an invocation outside the set is answered `403` with the JSON-RPC error `-31403`, `Forbidden: the caller may not use the named tool` (or `resource`, `prompt`) under the id of the request, and a `prompts/get` is tested against the prompts, never against a tool of the same name. A replayed stream (a `GET` with `Last-Event-ID`) keeps the admission decision and always reaches the server, and the lists in it are filtered with the sets of all three kinds. See [Capability checks](#capability-checks-what-the-caller-may-use). With a Token Service, the gateway declares the delegated token extension `com.indykite/delegated-token` in the capabilities of the server, so a client knows it may send its `X-IK-Token` to the server: in the answer to an `initialize` on a revision before `2026-07-28` under `capabilities.experimental`; in the answer to an `initialize` on `2026-07-28` and in the answer to a `server/discover` under `capabilities.extensions`; and in a replayed stream in every result that carries a `protocolVersion`, by the same rule. The gateway adds the declaration and changes nothing else in the answer; an answer it cannot read in one way only is forwarded without it. The MCP server behind the gateway must support one of the three revisions. When it answers an `initialize` with another revision, the client does not get the handshake and a failure at its next request: the gateway answers the `initialize` itself, under its `id` written as it was, with the status of the server's answer and the JSON-RPC error `-32603`, `Internal error: the MCP server supports none of the protocol revisions the gateway forwards`, whose `error.data` holds the revision the server `offered`, left out when it is not safe to repeat, and the `supported` revisions. A message the gateway cannot read before that answer, or a result whose `protocolVersion` cannot be read, is answered with `-32603`, `Internal error: the gateway cannot read the protocol revision the MCP server offered`. A replayed stream (a `GET` with `Last-Event-ID`) can repeat the answer to an `initialize`; every result in it that carries a `protocolVersion` is checked the same way and the same error takes its place, and the stream ends without an answer at a message the gateway cannot read. The gateway logs each such refusal. ### OAuth discovery An MCP client finds out where to get its token the way the MCP authorization specification describes: from the OAuth 2.0 Protected Resource Metadata (RFC 9728) of the resource it called, which is the gateway, not the server behind it. The gateway serves that metadata without a token and links it from every `401` of the endpoint. | Request | Answer | | --- | --- | | `GET /.well-known/oauth-protected-resource` | No token needed. `resource` is `service.base_url`, `authorization_servers` is `[identity_provider.issuer]`, `bearer_methods_supported` is `["header"]`, and with a Token Service `mcp_extensions` is `{"com.indykite/delegated-token": {}}`. For `service.base_url` `https://agents.example.com/mcp/v1/gid:AAAA…` the path is `/.well-known/oauth-protected-resource/mcp/v1/gid:AAAA…`. | | `GET /.well-known/oauth-protected-resource` | The same metadata with the origin of `service.base_url` (scheme, host and port, no trailing slash) as `resource`. When the path of `service.base_url` is `/`, this is the only metadata address and `resource` is the origin. | | `HEAD` or `OPTIONS` on either path | `HEAD`: `200` with the JSON content type and no body. `OPTIONS`: `204` with `Allow: GET, HEAD`, and a CORS preflight from any origin gets `Access-Control-Allow-Origin: *` (see [CORS](#cors)). Any other method: `405` with `Allow: GET, HEAD`. | | Any `401` of the MCP endpoint | `WWW-Authenticate: Bearer resource_metadata="/.well-known/oauth-protected-resource"`, on the gateway's own refusals (missing or inactive token) as well as on a `401` the MCP server returns. | | A `401` or `403` of the MCP server with its own challenge | The server's challenge is kept, `error`, `scope` and `error_description` included; only `resource_metadata` is replaced by the gateway's address in every `Bearer` challenge, or added when the challenge has none, since the server's metadata names the server, which the client did not call. The challenge is written back with its parameters sorted by name and every value quoted. A challenge the gateway cannot read stays as it is and gets the gateway's `Bearer` challenge next to it. A `403` without a challenge is an authorization decision of the gateway and gets none. The body of the server's answer is forwarded as it is, and may hold the server's own metadata address. | What this means for the deployment and the tokens: - **Ingress.** It must not strip a path prefix, since the gateway serves the path of `service.base_url` as it is, and it must route `/.well-known/oauth-protected-resource` to the gateway. The root `/.well-known/oauth-protected-resource` can serve only one gateway per host. Another server may serve the metadata instead, with the same values, but routing the address to the gateway is simpler. - **The token's `resource`.** A client asks the identity provider for its token with `resource` set to the `resource` of the metadata it read: `service.base_url`, or the origin at the root. The token is thus issued for the MCP server under its public URL, which is the gateway. Without `token_service`, the server receives the token the gateway exchanges for it at the identity provider. With `token_service`, the server receives the client's token in `Authorization` as `authorization_header.forward` passes it on, by default when it is issued for this agent, so it must accept the audience the identity provider writes for that `resource`; the IndyKite MCP server does with a Token Introspect configuration for the issuer and that audience. List the same value in `protected_agent.authentication.audiences`. A later hop that reaches the gateway with `X-IK-Token` alone is forwarded without `Authorization`; the IndyKite MCP server then answers `401`, since it requires a bearer token beside the delegation token, so callers of that server keep the user's token on every hop. - **Moving an existing mcp configuration.** A gateway in front of an MCP server needs three settings and does not start without them: `service.base_url`, the public URL of the MCP endpoint at the gateway (set it to the URL your clients already call to keep it); `protected_agent.base_url`, the full URL of the server's endpoint rather than the server's address alone, for example `http://mcp-server:8080/mcp/v1/gid:AAAA…` instead of `http://mcp-server:8080`; and `identity_provider.issuer`. Both paths are written unencoded. A client that used to call other paths of the server through the gateway now gets `404`. ## CORS The gateway answers CORS itself, so a browser client on another origin, such as a web console or a browser-based MCP client, can call it. Which origins a path allows depends on whether the path needs a token: | Mode | Path | Allowed origins | Methods | | --- | --- | --- | --- | | `mcp` | The two metadata paths of [OAuth discovery](#oauth-discovery) | Every origin (`*`) | `GET, HEAD` | | `mcp` | The path of `service.base_url`, the MCP endpoint | `cors.allowed_origins` | `GET, POST, DELETE` | | `mcp` | Any other path | None: the path answers `404` | - | | `a2a` | `/.well-known/agent-card.json`, a `GET` without `Authorization` (the public card) | Every origin (`*`) | `GET` | | `a2a` | `/.well-known/agent-card.json` with `Authorization` (the extended card), and any other path (JSON-RPC calls) | `cors.allowed_origins` | `GET, POST` | - **`OPTIONS`** on one of these paths is answered by the gateway with `204` and `Allow: `, before any token is read; nothing is forwarded. - **A preflight** (`OPTIONS` with `Origin` and `Access-Control-Request-Method`) from an allowed origin also gets `Access-Control-Allow-Origin` (`*` on a public path or when the list is `*`, otherwise the request's origin), `Access-Control-Allow-Methods`, `Access-Control-Max-Age: 7200` and `Access-Control-Allow-Headers: Authorization, X-IK-Token, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID, Mcp-Method, Mcp-Name, A2A-Version, A2A-Extensions`. On the MCP endpoint the allowed headers also include the `Mcp-Param-{Name}` headers the preflight asks for, which a `2026-07-28` client sends for tool parameters marked `x-mcp-header`; those answers carry `Vary: Access-Control-Request-Headers`. On the agent card path, only a preflight for a `GET` that does not ask for `Authorization` counts as one for the public card. - **Any other request** from an allowed origin gets `Access-Control-Allow-Origin` and `Access-Control-Expose-Headers: WWW-Authenticate, Mcp-Session-Id` on every answer: the gateway's own `400`, `401` and `403`, and the answers it forwards, streams included. A browser MCP client can therefore read the `WWW-Authenticate` challenge of a `401` and the `Mcp-Session-Id` of an answer. - **An origin that is not allowed**, or a request without `Origin`, gets no CORS headers on a token-protected path; the request is processed normally and the browser refuses the answer. The gateway does not refuse it with `403`. - **Caching.** Answers on token-protected paths carry `Vary: Origin`. Answers on public paths carry `Access-Control-Allow-Origin: *` even without `Origin`, so a cache may serve them to every origin. - **No credentials mode.** The gateway never sends `Access-Control-Allow-Credentials`: the token travels in `Authorization`, never in a cookie. - **The protected server's own CORS headers are dropped**, since the gateway owns CORS at its public URL. `Origin` is forwarded unchanged, so an MCP server that checks `Origin` must accept the listed origins too. ## Status codes | Status | Body and meaning | | --- | --- | | 200 | Authorized and forwarded; the body is the protected agent's or MCP server's response. In mcp mode any downstream status is passed through, a list answer is filtered to the caller's permitted set, and a list of a kind the caller may use nothing of is answered empty by the gateway itself. With `ibac.enabled`, also the answer the gateway gives in place of the agent when the Intent Agent failed the task: a JSON-RPC `result` holding an agent message in the request's `contextId`, its text the task's error and obligation, its `metadata.intent_error` the `{prompt, error, reason, obligation}` object; for `message/stream`, one event with that message. | | 400 | a2a: the JSON-RPC request could not be parsed (empty body). mcp: one of the refusals above. | | 401 | In mcp mode every `401` also carries `WWW-Authenticate: Bearer resource_metadata="…"` (see [OAuth discovery](#oauth-discovery)). `{"message":"Missing bearer token"}` for a request with neither a bearer token nor, with a Token Service, an `X-IK-Token`; `{"message":"Access token not issued for this agent"}` when a workflow is started with a token whose audience is none of `protected_agent.authentication.audiences`; `{"message":"Unauthorized","errors":["identity provider: the token is not active"]}` or `["token service: the token is not active"]`, the latter also for an identity provider token presented as `X-IK-Token`, since the Token Service reports only its own tokens as active; `{"message":"Invalid token, missing subject"}`, `{"message":"Invalid token, missing act claim"}`, `{"message":"Invalid token, act claim must be an object"}` for a delegation token the exchange produced; `{"message":"Invalid delegated token"}`, `{"message":"Invalid delegated token, missing act claim"}`, `{"message":"Invalid delegated token, missing subject"}`, `{"message":"Invalid delegated token, subject mismatch"}` for an incoming `X-IK-Token`, the last only when a bearer token travels beside it and `same_user_check` is on. A `401` or `403` from the identity provider, the Token Service, ContX IQ or AuthZEN is passed through with the same status and an `errors` entry naming the service, for example `["identity provider: token exchange failed - : "]`, `["identity provider: client credentials grant failed - …"]`, `["ContX IQ whoami failed"]`, `["evaluating admission through AuthZEN failed"]`, the latter also when the platform cannot read the delegation token in `X-IK-Token` for lack of a matching Token Introspect configuration. So an invalid AppAgent credential reaches the caller as `401` or `403`; the audit decision `ERROR` tells it apart from a denial. | | 403 | `{"message":"Authorization check failed"}`: the admission policy answered `false` for this subject, agent and chain, or the chain could not be read. The audit `reason` says which. In mcp mode also a JSON-RPC error under the id of the request, `-31403`, `Forbidden: the caller may not use the named tool` (or `resource`, `prompt`): the invocation names a capability outside the caller's permitted set. With `ibac.enabled` and an intent in the delegation token, also `Forbidden: the named tool has an invalid mapping` and, with `ibac.capabilities.unmapped: deny`, `Forbidden: the named tool has no mapping` (or `resource`, `prompt`); `Forbidden: the named tool does not match the intent`, when no evaluation of the current intent matches a mapping of the capability or the call lacks a value a mapping reads; and `Forbidden: the caller may not access the data the named tool uses`, when the platform denies one of the evaluations resolved from the matched mappings. Neither message names the data or the intent. In a2a mode with a Token Service, `{"message":"Authorization check failed"}` also answers a delegation token the Token Service finds too large, and, with `ibac.enabled`, a message whose intent fits no skill of the agent the caller may use. | | 405 | a2a: unknown JSON-RPC method (empty body). mcp: `{"message":"Method Not Allowed"}` with `Allow: GET, HEAD` for any other method on a metadata path. | | 404 | mcp: `{"message":"Not Found"}` for any path other than the MCP endpoint path and the two metadata paths, before the token is read. | | 404, 409, 415, 424, 501 | a2a: errors returned by the protected agent, translated: task or method not found, task not cancelable, unsupported content type, extended card not configured, unsupported operation. | | 500 | `{"message":"Internal Server Error"}`: the identity provider, the Token Service, ContX IQ, AuthZEN or an A2A agent could not be reached or timed out, or one of them answered `500`; also when the permitted set of the caller could not be read, unless the platform answered another status, which is then passed on. | | 502 | `{"message":"Bad Gateway","errors":[…]}`: in mcp mode the server could not be reached (the transport error is in `errors`) or `base_url` is not a URL (`cannot resolve downstream URL`); in a2a mode the agent returned a JSON-RPC internal error or an unusable response, its agent card cannot be used, or it redirected off the configured host; the identity provider or Token Service answered with a malformed body. With `ibac.enabled`: `["the intent agent cannot be asked"]`, `["the intent agent answered with a message instead of a task"]`, `["the intent agent answered with an intent that cannot be read"]`, `["the intent agent answered with a task neither completed nor failed"]`, `["cannot delegate the token with the intent"]` when the second exchange fails or its token lacks evaluations of the intent; in mcp mode with an intent in the delegation token, `["cannot list the capabilities of the MCP server"]`; in a2a mode with a Token Service, `["cannot read the skills of the agent"]` when the agent card, or its skills with their mappings, cannot be read to compare them with the intent; a `401` from the Intent Agent is retried once with a renewed token, and the identity provider's refusal of the gateway's own token for it is passed through as that provider's status. | | 504 | `{"message":"Gateway Timeout","errors":["the intent agent did not answer in time"]}`: the Intent Agent did not answer within `intent_agent.timeout`. | **Long answers.** The gateway sets no time limit on an answer, in either mode, so a long stream or a slow agent reaches the caller. Only connecting to the agent or the server is still bounded, to 10 seconds. The caller decides how long it waits: when it closes the connection, the gateway stops its call to the agent or the MCP server. Health for orchestrators is on port 9080. The unauthenticated `401` works as an external probe too, but every such probe writes an audit record and, with webhook delivery, one webhook call. # Audit records One record per decision, written before the request is forwarded, so a forward that fails afterwards still shows `AUTHORIZED`. `action` names the question the record answers, `decision` the answer. JSON to the webhook, or the configured file format: ```json { "decision": "AUTHORIZED", "reason": "subject User/millicent may reach Agent/indykiteagent-2 through the delegation chain", "subject": "millicent", "actor": "indykiteagent-2", "action": "ADMISSION", "service": "retriever-iag", "timestamp": "2026-09-30T09:12:00.123456789Z", "traceID": "4bf92f3577b34da6a3ce929d0e0e4736", "cached": { "admission": false }, "actorsChain": [ "indykiteagent", "indykiteagent-2" ] } ``` A capability decision of a gateway in front of an MCP server, here the filtering of a `tools/list`: ```json { "decision": "AUTHORIZED", "reason": "the lists of the server were filtered to the permitted set", "subject": "millicent", "actor": "mcp-agent", "action": "DISCOVERY", "service": "mcp-iag", "timestamp": "2026-11-06T09:12:00.123456789Z", "traceID": "0af7651916cd43dd8448eb211c80319c", "permittedSet": { "tool": ["read_document", "search_documents"] }, "cached": { "tool": true }, "discovery": { "serverCalled": true, "listed": 5, "kept": 2 }, "actorsChain": [ "mcp-agent" ] } ``` | Field | Values | | --- | --- | | `decision` | Read with `action`. On `ADMISSION`, `DISCOVERY` and `INVOCATION` records: `AUTHORIZED`, `NOT_AUTHORIZED`, or `ERROR` when the platform could not be consulted; a cached `ERROR` is a failed platform call kept for `authzen.cache_update_after_error`, and is never a denial. On `noop` records, written for a request refused before any question was asked: `NOT_AUTHORIZED` for a missing token, a token not issued for this agent, an unusable `X-IK-Token`, a subject `whoami` rejects, an MCP request or a delegation chain the gateway cannot read; `ERROR` when the identity provider refuses the gateway's own credentials, when the delegation token lacks `sub` or `act`, when `whoami` fails for another reason, or when the chain names the protected agent with another type than `protected_agent.node_type`. On `INTENT` records: `INTENT_FOUND` when the Intent Agent found the intent, `INTENT_FAILED` when it failed the task, `ERROR` when it could not be asked, answered unreadably or timed out, or when the skills of the agent could not be read. With a Token Service the intent is also compared with the skills of the agent: `NOT_AUTHORIZED` when it fits none of them; and for a message without text, which is not sent to the Intent Agent, `AUTHORIZED` or `NOT_AUTHORIZED` for the intent of its chain. | | `reason` | Token steps: `no bearer token`, `cannot introspect the subject token`, `cannot validate the delegated token`, `invalid delegated token: missing act claim`, `invalid delegated token: missing subject`, `invalid delegated token: subject mismatch`, `the access token is not issued for this agent`, `cannot authenticate protected agent`, `cannot delegate token`, `invalid token: missing subject`, `invalid token: missing act claim`, `invalid token: act claim is not an object`, `MCP request refused: `. Subject: `cannot resolve the subject of the access token`, with decision `NOT_AUTHORIZED` when `whoami` answers `401` and `ERROR` otherwise. Admission: `the delegation chain cannot be read`, `the delegated token names the protected agent , protected_agent.node_type is `, `unable to evaluate the admission of subject /`, `subject / may not reach / through the delegation chain`, `subject / may reach / through the delegation chain`. `/` is the subject from `whoami`, for example `User/millicent`; `/` is the resource of the evaluation, for example `Agent/indykiteagent-2`. Intent (action `INTENT`): `intent with evaluation(s)`, with a Token Service followed by how many fit the skills of the agent, as in `intent with 2 evaluation(s), 1 fit the skills of the agent`, or `intent with 2 evaluation(s), none fits the skills of the agent` on a refusal; for a message without text, `no prompt: the current intent with evaluation(s), fit the skills of the agent`, `no prompt: the current intent with evaluation(s) fits no skill of the agent`, or `no prompt, IBAC did not run: the chain carries no intent`; `cannot read the skills of the agent: …` on an `ERROR`; `no intent: ` followed by `(reason: )` only with `audit.include_prompt`, cut to 4096 bytes with a trailing `…`; when the error is the text the model answered with in place of an intent, which can quote the prompt, the record says only `no intent: the model answered with text` unless `audit.include_prompt` is on; and `cannot get the intent of the prompt` when the Intent Agent could not be asked. Capability decisions: `the lists of the server were filtered to the permitted set`, with `ibac.enabled` `the lists of the server were filtered to the permitted set and the current intent`, `the lists of the server were filtered to the current intent` with capability checks off, or `the lists of the server were filtered to the permitted set; IBAC did not run: the delegated token carries no intent`, `the caller may use nothing of the kind listed, answered with an empty list` `the skills of the card were filtered to the permitted set`, `the skills of the card were filtered to the permitted set and the current intent`, with capability checks off `the skills of the card were filtered to the current intent`, and, with `ibac.enabled` and no intent in the delegation token, `the skills of the card were filtered to the permitted set; IBAC did not run: the delegated token carries no intent` or, with capability checks off, `IBAC did not run: the delegated token carries no intent` on `DISCOVERY`; on an `ERROR` of a card, `the skills of the card cannot be read with their mappings`; `the caller may use the named tool` and `the caller may not use every named tool` (or `resource`, `prompt`) on `INVOCATION`; on an `ERROR`, the failure of the search or of the server. Resolved evaluations (action `RESOLVED_EVALUATIONS`): `the platform allowed every resolved evaluation`, `the platform denied a resolved evaluation`, and on an `ERROR` `the resolved evaluations cannot be checked: …`. | | `subject`, `actor`, `actorsChain` | The user (the token's `sub`; the `whoami` subject appears only in `reason`), the last agent, and the chain oldest first. In records written by the token steps the subject can be empty, `actor` is the upstream agent and `actorsChain` is the incoming chain, so it lacks the protected agent and is `null` on the first hop. On a chain that cannot be read, `actor` is `no-actor` and `actorsChain` is `null`. | | `action` | The question the record answers: `ADMISSION`, may the subject reach the protected agent through the delegation chain; `DISCOVERY`, which capabilities of the listed kind may the caller see, written for a filtered `tools/list`, `resources/list` or `prompts/list`, for the lists of a replayed stream and for the extended card of an A2A agent; `INVOCATION`, may the caller use every capability the request names; `RESOLVED_EVALUATIONS`, does the platform allow the data an MCP call touches, written with `ibac.enabled` for a call the intent matches whose mappings name ids; `INTENT`, the record of each Intent Agent call, written after the request's own record and carrying the same `subject`, `actor` and `actorsChain`; `noop`, no question was asked because the request was refused first. One decision per request, so a request gets either an `ADMISSION` or a capability record, never both. With `ibac.enabled` in mcp mode, an invocation also gets an `IBAC_USAGE` record when its mapping is checked: `IBAC did not run: the delegated token carries no intent`, `IBAC was skipped: the named tool has no mapping` (with `reasonCode` `missing_coaz_mapping`), a refusal (`the named tool has an invalid mapping` or `has no mapping`, with `reasonCode` `invalid_coaz_mapping` or `missing_coaz_mapping`), or `the capabilities of the server cannot be listed: …` as an `ERROR`. A capability checked against the intent gets one more `IBAC_USAGE` record, the result of the IBAC engine, with `reasonCode` `intent_match_authzen_required` (matched, with evaluations for the platform), `intent_match_search` (matched, nothing to ask the platform) or `intent_mismatch` (refused). With `ibac.enabled` in a2a mode, the filtering of an extended card by the current intent also writes `IBAC_DISCOVERY` records, before the `DISCOVERY` record of the card: one for the skills without a mapping, `AUTHORIZED` with `IBAC was skipped: the skills have no mapping` under `allow` or `NOT_AUTHORIZED` with `the skills have no mapping` under `deny`, both with `reasonCode` `missing_coaz_mapping`; one for the skills whose mapping cannot be read, `NOT_AUTHORIZED` with `the skills have an invalid mapping` and `invalid_coaz_mapping`; each with the skill ids in `skillIDs`; and the record of the IBAC engine for the skills with a mapping, one per 64 skills. The intent filter of an MCP list writes `IBAC_DISCOVERY` records the same way, with the entries of the list in `skillIDs`; and with a Token Service, the comparison of a message with the skills of the agent writes one with every evaluation and the skills it matched, where an evaluation that matched no skill was left out of the token. | | `durationMs`, `prompt` | Only on `INTENT` records: how long the Intent Agent call took in milliseconds, and, with `audit.include_prompt`, the prompt that was asked about. Absent from the JSON of every other record. | | `cached` | On decision records: whether the answer came from the gateway's cache or from the platform during the request. An `ADMISSION` record has the one key `admission`; a capability record has one key per kind it decided on, `tool`, `resource`, `prompt` or `skill`; a `RESOLVED_EVALUATIONS` record has the one key `evaluations`. | | `resolvedEvaluations` | On `RESOLVED_EVALUATIONS` records: every evaluation sent to the platform, in the order sent, each with `subjectType`, `subjectID`, `action`, `resourceType`, `resourceID` and the platform's answer `allowed`, which is left out when the platform did not answer. The resource ids come from the arguments of the call. | | `currentIntent`, `originalIntent` | On the records of an MCP request whose delegation token carries an intent, on the `IBAC_DISCOVERY` and `DISCOVERY` records of a card or a list filtered by the intent, and on the `INTENT` and `IBAC_DISCOVERY` records of a message compared with the skills, where the current intent of a message with text is the intent of its prompt: the intent the decision was checked against, the newest in the `act` chain, and the intent of the oldest hop that carries one, each as the evaluations the token carries. | | `capabilities` | On `INVOCATION` records: the identifiers the request named, by kind, for example `{"tool": ["read_document"]}`. | | `permittedSet` | On `DISCOVERY` records: the set the list was filtered to, by kind, as the platform returned it; an empty list when the caller may use nothing of the kind. A denied invocation compared with the permitted set of the last discovery for the same `subject` and `actorsChain` tells probing from a change of permissions; no record carries a flag for it, and the record does not tell apart a caller admitted nowhere, one admitted with nothing permitted and a server with nothing modelled. | | `discovery` | On `DISCOVERY` records: `serverCalled`, whether the server was asked at all (`false` for a list the gateway answered empty); `listed`, how many entries the server's list advertised; `kept`, how many the caller got. For the extended card the agent is always asked, `listed` counts its skills and `kept` the skills the caller got, after the permitted set and, with `ibac.enabled` and an intent, after the current intent. A card filtered with capability checks off has a `DISCOVERY` record without `permittedSet` and `cached`. | | `service` | `service.name`. | | `timestamp`, `traceID` | RFC 3339 UTC with up to nanosecond precision (trailing zeros are dropped), and the trace ID also found in the gateway's JSON logs. | | `tokenID` | Only in Token Service records; the CSV header carries the column so both services can share files. | `cached`, `capabilities`, `permittedSet` and `discovery` appear in the JSON of the webhook and of `json` files only; the `csv` and `txt` layouts below do not carry them. The `txt` format writes one line per record, values unquoted and the chain comma-joined, except `prompt`, `capabilityName` and `skillID`, which are quoted so that a record stays on one line: ```text [2026-09-30T09:12:00.123456789Z] decision=AUTHORIZED reason=subject User/millicent may reach Agent/indykiteagent-2 through the delegation chain subject=millicent actor=indykiteagent-2 actorsChain=indykiteagent,indykiteagent-2 action=ADMISSION service=retriever-iag traceID=4bf92f3577b34da6a3ce929d0e0e4736 tokenID= prompt="" capabilityName="" skillID="" reasonCode= skillIDs= evaluations= durationMs=0 ``` `csv` writes the same columns in that order with a header row per file: after `tokenID` come `prompt`, `capabilityName`, `skillID`, `reasonCode`, `skillIDs`, `evaluations` and `durationMs`, appended at the end so that files written before they existed still read. The gateway fills `durationMs`, and `prompt` with `audit.include_prompt`, on its `INTENT` records; the other five columns, `capabilityName`, `skillID`, `reasonCode`, `skillIDs` and `evaluations`, belong to the `IBAC_DISCOVERY` and `IBAC_USAGE` records of the [IBAC engine](/guides/guide-ibac#audit) and stay empty on every other record. # Telemetry Every step a request waits for is a span in the trace of the request, named `agent-gateway `, and a duration in the histogram `indykite_agent_gateway_step_duration_seconds`. The span and the metric carry the same labels: | Label | Values | | --- | --- | | `step` | The step, see the next table. | | `outcome` | `ok`: the step succeeded. `refused`: the step answered no, such as a denied decision, a token the identity provider or the Token Service reports inactive, an intent that does not match, or a failed task of the Intent Agent. `canceled`: the step failed because its request ended first, such as when the caller went away. `error`: the step failed; an introspection answered with a status, such as `401` for the credentials of the gateway, is an `error`. Only the span of an `error` step has the error status, so an alert on `error` does not fire on what callers do. | | `cache` | `hit`: answered from the cache of the gateway. `miss`: the request made the call. `shared`: the request waited for the same call of another request. `none`: a step without a cache, a value that cannot be kept, or a request that stopped waiting. | | `step` | What it measures | More labels | `cache` | | --- | --- | --- | --- | | `introspection` | An introspection of a token. | `peer` | `none` | | `token_exchange` | A token exchange, the first one or the one with the intent. | `peer`, `exchange` (`first`, `intent`) | `none` | | `actor_token` | The client credentials token of the gateway. | | `hit`, `miss`, `shared`, `none` | | `whoami` | ContX IQ `whoami`. | | `hit`, `miss`, `shared`, `none` | | `kbac_admission` | The AuthZEN admission evaluation. | | `hit`, `miss`, `shared` | | `kbac_permitted_set` | One AuthZEN resource search of the permitted set. | `resource_type` | `hit`, `miss`, `shared` | | `intent_agent` | The call of the Intent Agent. | | `none` | | `ibac_discovery` | Filtering a list or a card by the intent. | | `none` | | `ibac_usage` | Checking a call against the intent. | | `none` | | `platform_checks` | The AuthZEN `evaluations` request with the resolved evaluations. | | `hit`, `miss`, `shared` | | `catalog_fill` | Listing the MCP server, or reading the agent cards, to learn the capabilities and their mappings. | `kind` | `none` | | `agent_card` | Reading the card an A2A agent publishes, for every call to the agent. | `agent` (`protected_agent`, `intent_agent`) | `hit`, `miss`, `shared`, `none` | - `peer` is `identity_provider` or `token_service`. - The count of the histogram by `cache` gives the hits and the misses of each cache. A `whoami` for a token without a subject is not kept, and is `none`. - A caller that gives up because a service is slow is `canceled` too, so watch the duration of a step as well as its errors. - The Intent Agent answers both a prompt without an intent and a failure of its own with a failed task. So an `intent_agent` step that is `refused` can also be an outage of the Intent Agent; only a call that fails, a bad answer or a timeout is an `error`. - `catalog_fill` runs for a capability the gateway has not seen listed. In front of an A2A agent with `ibac.enabled`, a Token Service and capability checks off, it also runs for every message, so its count then follows the messages. - A step can run within another step, so the durations of the steps of a request do not add up to the duration of the request: `agent_card` runs within `intent_agent` and, when the skills of the protected agent are read, within `catalog_fill`. - A call to AuthZEN and ContX IQ carries the trace on, so the IndyKite platform continues the same trace. A call to the identity provider or the Token Service sends no trace header. # Related - The big picture first, on the reference diagram: [Agent Gateway architecture guide](/guides/guide-iag-architecture) - Protect an MCP server step by step: [Agent Gateway MCP tutorial](/tutorials/tutorial-agent-gateway-mcp) - Let policies see the whole agent chain: [Token Service guide](/guides/guide-token-service) - Turn a prompt into AuthZEN evaluations: [Intent Agent guide](/guides/guide-intent-agent) - Match an intent against what a skill or tool declares it does: [IBAC engine guide](/guides/guide-ibac) - Author the admission policy and the `$ik_token` claims it reads: [AuthZEN guide](/guides/guide-authzen) - Working stacks: the `a2a/iag-mcp-demo` and `a2a/iag-token-exchange` folders of the [developer-hub repository](https://github.com/indykite/developer-hub) - Drive the setup from a coding agent: [Agent Skills guide](/guides/guide-skills) - The audit record next to the platform events and the Intent Agent record, and how to correlate them: [Audit Event Formats guide](/guides/guide-audit-formats) --- Source: https://developer.indykite.com/guides/guide-agent-gateway --- # Audit Event Formats: Platform Events, Agent Gateway, Token Service and Intent Agent Records > The three audit record formats IndyKite components produce - the indykite.audit.* CloudEvents of the platform with the payload fields of every event type, the shared record of the Agent Gateway and the Token Service, and the record of the Intent Agent - with examples, file layouts, how to tell them apart and how to correlate them. **Category:** Audit Log ## Summary One reference for every audit record an IndyKite component writes: the CloudEvents envelope and body of the platform's indykite.audit.* events with a payload field table per event type (capture, config, credentials, authorization, ciq, cdc), the flat JSON record shared by the Agent Gateway and the Token Service with its decisions, actions, csv and txt layouts, the Intent Agent record with its outcome values and content-hash versions, which of them are tamper-proof, and the identifiers that correlate them. ## Content Download this guide as a PDF: [guide-audit-formats.pdf](/assets/downloads/guide-audit-formats.pdf). # Which audit formats exist? IndyKite components write three audit record formats. They share no schema: each is read with its own field list. | Format | Written by | Shape | Where you read it | | --- | --- | --- | --- | | [Platform events](#platform-events), `indykite.audit.*` | The Config API, Capture, Token Introspect, AuthZEN, ContX IQ and the graph's change data capture | A CloudEvents 1.0 message whose JSON body carries a typed `data` payload | Pushed to your broker by [Outbound Events](/guides/guide-outbound-events); read back, signed and chained, from the [Audit Log API](/guides/guide-audit-log) | | [Agent record](#agent-gateway-and-token-service-records) | The [Agent Gateway](/guides/guide-agent-gateway) and the [Token Service](/guides/guide-token-service), one shared format | A flat JSON object with camelCase keys | Your webhook, or json, csv or txt files the service rotates | | [Intent Agent record](#intent-agent-records) | The [Intent Agent](/guides/guide-intent-agent) | A flat JSON object with snake_case keys | Your webhook, or json, csv or txt files the service rotates | Only the platform events can be tamper-proof: in a project with an [Audit Signing configuration](/guides/guide-audit-signing) every delivered event is also hashed, signed and chained, and the Audit Log API serves that chain. Agent, Token Service and Intent Agent records are written by services you run, straight to the sink you configure, and are not chained by the platform; keep them in a store with the integrity guarantees you need. The MCP server has no audit output of its own: changes to its configuration appear as `indykite.audit.config.*` events, and calls that pass through an Agent Gateway in `mcp` mode appear as agent records. # Platform events ## The envelope Each event is a CloudEvents 1.0 message. The attributes are the same whichever provider delivers it; what changes is where the provider puts them: Kafka record headers prefixed `ce_` (`ce_specversion`, `ce_type`, `ce_id`, and so on, with the body as the record value), Azure Service Bus application properties prefixed `cloudEvents:`, Azure Event Grid in its CloudEvents schema, and Google Cloud Pub/Sub attributes as defined by the CloudEvents Pub/Sub protocol binding. The body repeats every attribute you need to interpret the event, so a consumer can ignore the transport attributes and read the JSON alone; the Audit Log API serves the body only. | Attribute | Value | | --- | --- | | `specversion` | `1.0` | | `type` | The event type, the same value as `eventType` in the body, for example `indykite.audit.capture.upsert.node`. | | `source` | `https://audit.indykite.com/v1`. The suffix is the version of the body format; every event is `v1` today. | | `id` | Unique per event. Delivery is at least once: deduplicate on it. | | `time` | When the event happened, RFC 3339 UTC. The same instant as `time` in the body. | | `datacontenttype` | `application/json` | | `customerid`, `appspaceid`, `requestid` | Extensions repeating the organization, the project and the request identifier of the body, in lower case as the CloudEvents specification requires of extension names. `appspaceid` names the project whose sinks receive the event. | | `originalsource` | Extension naming the part of the platform that recorded the event. Informational, like `eventSource` in the body. | | `configtype` | Extension on `indykite.audit.config.*` events only: the configuration type the event is about, the same value as `data.type`. | ## The body The body is one JSON object with the same top-level keys for every event type. The [Audit Log guide](/guides/guide-audit-log) shows a complete Capture upsert event inside a signed batch; the fields are: | Field | Meaning | | --- | --- | | `eventType` | One of the `indykite.audit.*` names in the catalogue below. | | `time` | RFC 3339 with nanoseconds, UTC. | | `customerId`, `appSpaceId` | The organization and the project the event happened in; `appSpaceId` is the `project_id` of the request. | | `initiator` | Who made the request, as a flat object of string identifiers whose keys tell the kind of caller apart. An Application Agent carries `applicationId`, `appAgentId` and `appAgentCredentialsId`; a Service Account carries `serviceAccountId` and `serviceAccountCredentialsId`; an end user resolved by Token Introspect carries `digitalTwinId`, `viaApplicationId` and `sessionId`. Every form also carries `customerId` and `appSpaceId`. Empty identifiers are left out. | | `requestId` | The identifier of the request that caused the event, the same value the API returned to the caller. Always present, empty when there was none. | | `data` | The payload, typed by its `@type` member: `type.googleapis.com/indykite.auditsink.v1beta1.`. The catalogue below gives the message and its fields for each event type. | | `context` | String key-value pairs some events attach, for example `soft_delete` on a configuration delete. Present only when there is at least one pair. | | `eventSource` | Which part of the platform recorded the event. Informational. | Inside `data` the field names are the lowerCamelCase form of the message fields, and every field is present even when empty: a string as `""`, a number as `0`, a boolean as `false`, a list as `[]`, a nested message that was not set as `null`. Enumerations are written by name (`OPERATION_TYPE_UPDATE`), durations as a decimal number of seconds with the `s` suffix (`"0.012s"`) and timestamps in RFC 3339. Typed values, such as node properties, use the `{"stringValue": ...}`, `{"integerValue": ...}` family of the Capture API. ## Event type catalogue The complete list of event types a route can filter, with the `@type` payload each carries and the payload's fields. Filter keys, such as `captureLabel` and `label0`, are described in the [Outbound Events guide](/guides/guide-outbound-events). ### Capture | Event type | Payload | | --- | --- | | `indykite.audit.capture.upsert.node` | `UpsertData` with `node`: `id` (the platform identifier), `externalId`, `type`, `isIdentity`, `properties`, each `{type, value, externalValue}`. One event per node of the request. | | `indykite.audit.capture.upsert.relationship` | `UpsertData` with `relationship`: `type`, `source` and `target` as `{externalId, type}`, `properties`. One event per relationship. | | `indykite.audit.capture.delete.node` | `DeleteData` with `node`: `{externalId, type}`. | | `indykite.audit.capture.delete.relationship` | `DeleteData` with `relationship`: `type`, `source`, `target`, `properties`. | | `indykite.audit.capture.delete.node.property` | `DeleteData` with `nodeProperty`: `match` as `{externalId, type}` and `propertyType`. | | `indykite.audit.capture.delete.relationship.property` | `DeleteData` with `relationshipProperty`: `type`, `source`, `target`, `propertyType`. | | `indykite.audit.capture.delete.node.tag` | `DeleteData` with `nodeTags`: `match` and `tags`, a list of strings. | | `indykite.audit.capture.delete.node.property.metadata` | `DeleteData` with `nodePropertyMetadata`: `match`, `propertyType`, `metadataType`. | ### Configuration All seven carry `type`, the configuration type as an enumeration name such as `CONFIG_TYPE_TOKEN_INTROSPECT`, and `containersPath` as `{customerId, applicationSpaceId}`. A configuration object itself appears as a `ConfigDetail`: `name`, `displayName`, `description`, `status`, `tags`, and one member named after the configuration kind holding the stored object, with secrets reduced to their `kid`, `expireTime`, `keyFormat` and `originalKid`. Events about organization-level objects, such as Service Accounts, have no project and are not delivered to project sinks. | Event type | Payload | | --- | --- | | `indykite.audit.config.create` | `CreatedConfig`: `id`, `type`, `location` as `{id, type}`, `containersPath`, `detail`. | | `indykite.audit.config.read` | `ReadConfig`: either `id` or `name` as `{locationId, locationType, name}`, plus `type` and `containersPath`. The object itself is not repeated. | | `indykite.audit.config.update` | `UpdatedConfig`: `id`, `type`, `containersPath`, `before` and `after`. | | `indykite.audit.config.delete` | `DeletedConfig`: `id`, `type`, `containersPath`, `before`, the state right before deletion. `context.soft_delete` says whether the object was soft-deleted. | | `indykite.audit.config.list` | `ListConfig`: `locationId`, `locationType`, `containersPath`, `listed` as a list of `{type, ids}`, the identifiers the caller saw. | | `indykite.audit.config.permission.assign` | `AssignConfigPermissions`: `targetIdentifier` and `targetType` (who receives the role), `role`, `customerId`, `objectId` and `objectType` (what the role is on). | | `indykite.audit.config.permission.revoke` | `RevokeConfigPermissions`, the same fields. | ### Credentials | Event type | Payload | | --- | --- | | `indykite.audit.credentials.token.introspected` | `TokenIntrospected`: `resolvedDigitalTwinId` (the graph node the token was mapped to, empty when none), `configId` (the Token Introspect configuration that matched), `issuer`, `subject` (the `sub` claim or the configured `sub_claim`), `jti`, `tokenHash` (SHA3-256 of the token, base64url without padding). The token itself is never recorded. | ### Authorization The five AuthZEN payloads share a skeleton: `request` as `{body, token}`, where `body` is the request body as the caller sent it, a JSON string, and `token` is `{subjectId}`, the subject of the user token sent with the request, empty when there was none; `response`, the response body as a JSON string; `results`, one entry per policy that took part, each naming the `policy` as `{id, name}`; `errorMessage`, empty on success; and `evaluationTime`. | Event type | Payload | | --- | --- | | `indykite.audit.authorization.evaluation` | `Evaluation`: each result carries `isAllowed` and `advices`, a list of `{values}` maps. | | `indykite.audit.authorization.evaluations` | `Evaluations`: instead of a flat `results` list, an `evaluations` list with one entry per evaluated triple, each holding `request` as `{subjectType, subjectExternalId, resourceType, resourceExternalId, action}` and its `results`, each `{policy, isAllowed, reason, advices}`. | | `indykite.audit.authorization.searchsubject` | `SearchSubject`: each result carries `externalIds`, the subjects the policy returned. | | `indykite.audit.authorization.searchresource` | `SearchResource`: each result carries `externalIds`, the resources the policy returned. | | `indykite.audit.authorization.searchaction` | `SearchAction`: each result carries `actions`. | ### ContX IQ | Event type | Payload | | --- | --- | | `indykite.audit.ciq.execute` | `ExecuteKnowledgeQuery`: `request` as `{query, policy, inputParams}`, where `query` is `{id, status, query}` and `policy` is `{id, status, policy}`, each with the stored definition as a JSON string, and `inputParams` the typed input values of the call; `authorized`, whether the policy let the query run. The rows the query returned are not recorded. | ### Change data capture Delivered only when the event sink has `include_cdc_events` set. One event per changed node or relationship. | Event type | Payload | | --- | --- | | `indykite.audit.cdc.node.create`, `indykite.audit.cdc.node.update`, `indykite.audit.cdc.node.delete`, `indykite.audit.cdc.relationship.create`, `indykite.audit.cdc.relationship.update`, `indykite.audit.cdc.relationship.delete` | `CDCEvent`: `txId` and `seq` (the transaction and the position of the change in it), `operation` (`OPERATION_TYPE_CREATE`, `_UPDATE`, `_DELETE`), `eventType` (`EVENT_TYPE_NODE` or `EVENT_TYPE_RELATIONSHIP`), `elementId`; for a node, `node` as `{labels, labelKeys}` where `labelKeys` maps each label to the keys that identify the node; for a relationship, `relationship` as `{type, start, startElementId, end, endElementId, keys}`; `before` and `after` as `{properties, labels, richProperties}`, where `properties` maps each attribute to its JSON-encoded value and `richProperties` lists IndyKite properties as `{type, value, source, metadata}`; `txCommitTime` and `txStartTime`. | # Agent Gateway and Token Service records The two services write one and the same record, so a webhook or a file directory can receive both and the `service` field tells them apart. One record is written per decision: the gateway writes it before forwarding, so a forward that fails afterwards still shows `AUTHORIZED`; the Token Service writes one per token it looked at and one for the exchange itself. ```json { "decision": "AUTHORIZED", "reason": "subject User/millicent may reach Agent/indykiteagent-2 through the delegation chain", "subject": "millicent", "actor": "indykiteagent-2", "action": "ADMISSION", "service": "retriever-iag", "timestamp": "2026-09-30T09:12:00.123456789Z", "traceID": "4bf92f3577b34da6a3ce929d0e0e4736", "cached": { "admission": false }, "actorsChain": [ "indykiteagent", "indykiteagent-2" ] } ``` | Field | Meaning | | --- | --- | | `decision` | What became of the request, read together with `action`. Gateway: `AUTHORIZED` or `NOT_AUTHORIZED` on its `ADMISSION`, `DISCOVERY` and `INVOCATION` records, `NOT_AUTHORIZED` on a `noop` record, and on its Intent Agent calls `INTENT_FOUND` or `INTENT_FAILED`. Token Service: `TOKEN_EXCHANGED`, `EXCHANGE_REFUSED`, `INTROSPECTED`, `INTROSPECTED_INACTIVE`, `INTROSPECTION_REFUSED`. Both: `ERROR`, when the service or something it depends on failed, so that an outage is never counted as a denial. Issuing or describing a token is never a grant of access, which is why those decisions are not spelled `AUTHORIZED`. | | `reason` | Free text, the same message the caller received where there is one. The gateway's reason strings are listed in the [Agent Gateway guide](/guides/guide-agent-gateway#audit), the Token Service's in the [Token Service guide](/guides/guide-token-service). The workflow a decision was about appears only inside this text. | | `subject` | The end user the request acts for. | | `actor`, `actorsChain` | The immediate caller, and the full delegation chain from the token's `act` claim, oldest first; `actor` is its last entry. | | `action` | Gateway: the question the record answers. `ADMISSION`, may the chain reach the protected agent; `DISCOVERY`, which capabilities of a kind the caller may see, written for a filtered MCP list or extended card; `INVOCATION`, may the caller use every capability the request names; `RESOLVED_EVALUATIONS`, does the platform allow the data an MCP call touches, with the evaluations sent and the answer for each; `INTENT`, the record of each Intent Agent call, one more per message after the request's own; `noop`, the request was refused before any question was asked. Token Service: `TOKEN_EXCHANGE` or `TOKEN_INTROSPECT`. | | `durationMs`, `prompt` | Gateway `INTENT` records only: the duration of the Intent Agent call in milliseconds, and the prompt when the gateway's `audit.include_prompt` is on. Absent from the JSON of every other record. | | `cached`, `capabilities`, `permittedSet`, `discovery` | Gateway decision records only, and only in JSON (webhook and `json` files; the csv and txt layouts do not carry them): whether the answer came from the gateway's cache, by kind; the identifiers an invocation named; the set a discovery was filtered to; and `{serverCalled, listed, kept}` for a discovery. Field by field in the [Agent Gateway guide](/guides/guide-agent-gateway#audit). | | `service` | The `service.name` of the instance that wrote the record; how you tell the hops of a chain apart. | | `timestamp` | RFC 3339 UTC with up to nanosecond precision, trailing zeros dropped. | | `traceID` | The trace identifier also found in the service's JSON logs; the records of one exchange share it. | | `tokenID` | Token Service records only: the `jti` of the token issued or described. Absent from gateway JSON; an empty column in csv and txt. | Over the webhook each record is one JSON request. In files, `json` writes one object per line; `csv` writes a header row per file and the columns `decision, reason, subject, actor, actorsChain, action, service, timestamp, traceID, tokenID, prompt, capabilityName, skillID, reasonCode, skillIDs, evaluations, durationMs` in that order, the chain comma-joined, lists as JSON arrays, each later column appended at the end so that files written before it existed still read; of the seven after `tokenID` the gateway fills `durationMs` and, with `include_prompt`, `prompt` on its `INTENT` records, and the rest, `capabilityName`, `skillID`, `reasonCode`, `skillIDs` and `evaluations`, belong to the `IBAC_DISCOVERY` and `IBAC_USAGE` records described in the [IBAC engine guide](/guides/guide-ibac#audit) and stay empty on every other record. `txt` writes one line per record, values unquoted except `prompt`, `capabilityName` and `skillID`: ```plain [2026-09-30T09:12:00.123456789Z] decision=AUTHORIZED reason=subject User/millicent may reach Agent/indykiteagent-2 through the delegation chain subject=millicent actor=indykiteagent-2 actorsChain=indykiteagent,indykiteagent-2 action=ADMISSION service=retriever-iag traceID=4bf92f3577b34da6a3ce929d0e0e4736 tokenID= prompt="" capabilityName="" skillID="" reasonCode= skillIDs= evaluations= durationMs=0 ``` Files are named `audit--.` and rotated by time, size or both. Both services take the same `audit` configuration section, `delivery: file` or `delivery: webhook`; the webhook authentication and queue keys are `api_key` (`apikey`), `api_key_header` (`apikeyheader`), `mtls_certificate_file_path` (`mtlscertificatepath`), `mtls_private_key_path` (`mtlsprivatekeypath`) and `buffer_size` (`buffersize`), the name in parentheses being the one the current releases read, as the [Agent Gateway guide](/guides/guide-agent-gateway#configuration) details. Without the section nothing is recorded. # Intent Agent records The Intent Agent writes one record per request, in its own format with snake_case keys. The field order below is also the column order of csv and txt files and the key order of the JSON. ```json { "timestamp": "2026-09-07T10:15:04.123456Z", "request_id": "req-1", "subject_id": "user-1", "subject_type": "Customer", "requesting_agent_id": "", "context_id": "ctx-1", "prompt": "rent kitt", "evaluations": [ {"action": {"name": "RENT"}, "resource": {"type": "Car", "id": "kitt"}} ], "schema_version": "abc123", "policy_version": "", "llm_provider": "gemini", "llm_model": "gemini-3.5-flash-lite", "latency_ms": 42, "validation_retries": 0, "policy_fetch_failed": false, "outcome": "success", "message": "" } ``` | Field | Meaning | | --- | --- | | `timestamp` | RFC 3339 UTC with microseconds. | | `request_id` | The caller's `X-Request-ID` when it is non-blank and at most 40 characters, as the Agent Gateway accepts it; otherwise a generated UUID. A longer value is ignored, not truncated. | | `subject_id`, `subject_type` | The end user the prompt is evaluated for, from the message metadata of the call. | | `requesting_agent_id` | Reserved; always empty today. | | `context_id` | The A2A context the message belongs to. | | `prompt` | The natural-language prompt as received. | | `evaluations` | The AuthZEN evaluations derived from the prompt, each `{action, resource}` and, where the prompt named one, `subject`; empty when none were derived. | | `schema_version` | Not a version number: the SHA-256 of the project's data schema as read from `GET /data-schema/v1`, computed over the document with sorted keys, so it changes whenever the schema changes and is stable otherwise. Empty when no schema was available. | | `policy_version` | Likewise the SHA-256 of the subject type's KBAC policies as read from `GET /access/v1/policies`, each policy serialised with sorted keys and the list sorted, so neither key order nor policy order affects it. Empty when there were no policies or no fetch. | | `llm_provider`, `llm_model` | The provider, derived from the model name, and the model that produced the evaluations. | | `latency_ms` | Wall-clock time of the request in milliseconds, authentication included. | | `validation_retries` | How many times the model's answer was rejected and asked for again before this outcome. | | `policy_fetch_failed` | Three states: `null` when no policy fetch was attempted, `false` when it succeeded, `true` when the live fetch failed and the last known-good policies were used. In csv and txt `null` is an empty cell. | | `outcome` | `success` when evaluations were returned; `unmatched` when the prompt yielded no intent or a free-text reply; `validation_failed` when the model's answer never passed validation; `error` for an authentication rejection, a missing or empty schema, a subject type mismatch, a timeout or any other failure. | | `message` | The text the caller received, exactly; empty when the caller received no text. | In files, `json` writes one object per line; `csv` writes the 17 field names as a header row per file, then one row per record with lists and objects as compact JSON, `null` as an empty cell and numbers and booleans as text; `txt` writes `[] request_id= subject_id= ... message=` with the same cell rendering and no quoting, so a space inside `prompt` or `message` is written as is. Files are named `audit--.`, created with mode `0600` in a directory with mode `0750`, and never appended to a file the service did not create. Over the webhook each record is one JSON request with `Content-Type: application/json`; mTLS requires TLS 1.3. Delivery is configured with the `AUDIT_*` variables listed in the [Intent Agent guide](/guides/guide-intent-agent#audit). Unlike the gateway and the Token Service, auditing cannot be switched off: `AUDIT_DELIVERY` has no default and the service refuses to start without it. A failed delivery, to an unreachable webhook or a full disk, is logged and never fails the request; with `AUDIT_ASYNC=true` a full queue drops the record with the warning `audit: dropping payload, async queue is full`. # Telling the formats apart and correlating them A receiver that takes all three on one endpoint can classify a record by its keys: a platform event has `eventType` and `data`; an agent record has `decision` and `actor`; an Intent Agent record has `outcome` and `prompt`. No key is shared by two formats. | To follow | Match | | --- | --- | | One request across the Agent Gateway and the Token Service | `traceID`: the gateway's record and the Token Service's introspection and exchange records of the same hop share it. | | A delegation token from issue to use | `tokenID` of the Token Service's `TOKEN_EXCHANGED` record is the token's `jti`; when the platform later validates that token, its `indykite.audit.credentials.token.introspected` event carries the same value in `data.jti`. | | An Intent Agent request to the client that sent it | `request_id`, when your client sets `X-Request-ID` on the call to the Intent Agent; the Agent Gateway does not set that header on its own calls, so pass it from your side if you need the link. | | A platform API call to its events | `requestId` in the body and the `requestid` extension: every event of one request carries the value the API returned to the caller. | | Who acted | Platform events name the credential in `initiator`; agent records name the user in `subject` and the agents in `actorsChain`; Intent Agent records name the user in `subject_id` and `subject_type`. | # Next Steps - Reading the signed chain, with a complete event inside a batch: [Audit Log guide](/guides/guide-audit-log) - Routing the platform events to your broker and the filter keys per event type: [Outbound Events guide](/guides/guide-outbound-events) - The gateway's reason strings and its `audit` configuration: [Agent Gateway guide](/guides/guide-agent-gateway#audit); the Token Service's decisions: [Token Service guide](/guides/guide-token-service) - The Intent Agent's delivery variables: [Intent Agent guide](/guides/guide-intent-agent#audit) - Reading gateway records live in a demo: [Agent Gateway MCP tutorial](/tutorials/tutorial-agent-gateway-mcp), chapter 8 --- Source: https://developer.indykite.com/guides/guide-audit-formats --- # Tamper-proof audit log: infrastructure for a dedicated deployment > What a dedicated IndyKite deployment needs in your GCP project or AWS account to run the tamper-proof audit log: signing and storage keys, the write-once bucket and its access log, the message bus, three identities with least-privilege permissions, the values to hand over, the one-way decisions and what to monitor. **Category:** Audit Log ## Summary The infrastructure contract for the tamper-proof audit log when the IndyKite platform runs in your own cloud account: keys, storage, messaging, identities, hand-over values, irreversible decisions and operations. ## Content The [Audit Log API](/guides/guide-audit-log) serves a signed, hash-chained trail of the audit events of a project that its Event Sinks delivered, once the project has an Audit Signing configuration. On the shared IndyKite platform the infrastructure behind it is IndyKite's concern. When the platform runs as a **dedicated deployment in your own GCP project or AWS account**, part of that infrastructure lives in your account, is often owned by your key-management or security team, and has decisions only you can take. This guide is the contract for that case: what must exist, what the deployment creates, which choices cannot be undone, what to hand over, and what to watch once it runs. It says nothing about how the service works internally; the [Audit Log guide](/guides/guide-audit-log) and the [audit trail tutorial](/tutorials/tutorial-audit-trail) cover the chain and its verification. # What runs, and what it needs Three workloads make up the audit log, all deployed with the platform in your Kubernetes cluster: | Workload | What it does | Signs | Writes | | --- | --- | --- | --- | | **Audit log service** | Consumes the audit events the platform publishes on the message bus, cuts them into batches, chains and signs them, stores them, and serves the Audit Log API and its JWK Set. | Yes: batches and manifests | Yes | | **Checkpoint generator** | A scheduled job that signs a checkpoint of each chain's current head at intervals, so a truncated chain can be detected later. | Yes: checkpoints | Yes | | **Integrity verifier** | A scheduled job that re-reads the stored chains, recomputes every hash and link and checks every signature, with no write access at all. Its exit code is your tamper alarm. | No | No | Around them, in your account: - An **asymmetric signing key** in Cloud KMS or AWS KMS. Its public half is what the JWK Set publishes and what every verifier trusts. - A **symmetric storage key** that encrypts the buckets. - A **write-once bucket** holding the batches, manifests and checkpoints, plus an **access-log bucket** recording who read or wrote it. - A **message bus** carrying audit events from the platform's ingestion service to the audit log service, with a dead-letter destination. - **Three identities**, one per workload, with the permissions below and nothing more. - A **public API host** exposing `/audit/v1` and `/audit/.well-known`, so exporters and verifiers outside the cluster can reach the trail and the keys. - A cache instance, provided by the deployment itself. It is never a source of truth: the checkpoint generator falls back to the stored manifests when a cache entry is missing. ![The ingestion service publishes audit events to a topic; the audit log service pulls them through a subscription, signs with the KMS signing key and writes to the write-once bucket, which is encrypted with the storage key and logs its accesses to a second bucket; the checkpoint generator signs and writes checkpoints; the integrity verifier only reads the bucket and the public key; undeliverable messages go to a dead-letter topic; the public API host exposes /audit/v1 and the JWK Set](/assets/images/audit-infrastructure.svg) # Keys | | GCP (Cloud KMS) | AWS (KMS) | | --- | --- | --- | | **Signing key** | Purpose `ASYMMETRIC_SIGN`, algorithm `EC_SIGN_P256_SHA256`, protection level `HSM` recommended. | Usage `SIGN_VERIFY`, key spec `ECC_NIST_P256`. | | **Storage key** | Symmetric encryption, `HSM`, rotated every 90 days. Used as the customer-managed encryption key of both buckets, so it must be in the **same location as the buckets**; a key ring in another location (for example a global one) cannot hold it. | Symmetric, automatic rotation every 90 days. Used as the SSE-KMS key of the write-once bucket. The access-log bucket uses SSE-S3, since S3 log delivery does not write to an SSE-KMS destination. | | **Who creates them** | Either the deployment, inside an **existing key ring you name** (when that ring is not in the bucket's region, the deployment creates one regional key ring for the storage key, and nothing else), or your own team, in which case you hand over the two key resource IDs instead. | The deployment creates both, with an alias each, and a key policy that grants the account root full access; you set the deletion window (7 to 30 days). | | **Rotation of the signing key** | Manual: Cloud KMS does not rotate asymmetric keys on its own. Create a new key version and point the deployment at it. Every signature names its key through its `kid`, and the JWK Set keeps publishing the earlier keys, so records signed before the rotation stay verifiable. The key is protected against destruction. | Manual: AWS KMS does not rotate asymmetric keys on its own. Create a new asymmetric key with the same spec and point the deployment at its ARN. Records signed before the rotation stay verifiable, as on GCP. | | **Key identifier (`kid`)** | A string you agree at hand-over, which the deployment stamps on every batch, manifest and checkpoint and publishes in the JWK Set. It is not derived from the key: it may be set to the key version or ARN, or to a name of your own, but it must be unique per key, since a verifier selects the public key by it. | | Which key signs is also visible to API consumers: every batch, manifest and checkpoint carries the `kid`, and the [Audit Signing guide](/guides/guide-audit-signing) explains how a project's configuration relates to it. # Storage | Setting | Write-once bucket | Access-log bucket | | --- | --- | --- | | Contents | Chain batches, chain manifests, project and platform checkpoints. | Access logs of the write-once bucket, delivered by the cloud provider's log-delivery service. | | Location | The deployment's region, the same as the storage key. | Same. | | Versioning | Enabled (required by object lock on AWS). | Enabled. | | Encryption | The storage key. | GCP: the storage key. AWS: SSE-S3. | | Public access | Blocked at the bucket level; uniform bucket-level access on GCP. | Blocked. | | Retention | One year by default. GCP: a retention policy, **unlocked** until you decide otherwise. AWS: Object Lock with a default retention in `GOVERNANCE` mode until you decide otherwise. | None; the logs are kept as long as the bucket they describe. | | Lifecycle rules | None. A rule that expires objects would defeat the purpose. | None. | | Deletion protection | GCP: protected against destruction, and a 7-day soft-delete window. AWS: none, so that a disposable environment can be torn down; see the one-way decisions below. | Same as the write-once bucket. | Two properties together make the bucket write-once. The writers may only create objects, never delete them; and the retention policy, once locked, forbids anyone, the cloud provider included, from shortening it. Until it is locked, a project owner can still remove the policy, which is why locking is a decision rather than a default. # Message bus Audit events reach the audit log service through a queue, never through a direct call, so a slow or restarting service loses nothing. The ingestion service publishes an event to that queue only after an Event Sink of the project delivered it to at least one destination, and only for projects with an Audit Signing configuration; the chain therefore holds exactly what the customer's sinks received. | | GCP (Pub/Sub) | AWS (Kafka) | | --- | --- | --- | | Main path | One topic for audit messages and one pull subscription on it, encrypted with a customer-managed key: acknowledgement deadline 120 s, exponential retry between 10 s and 600 s, at most 10 delivery attempts, message retention 3 hours, acknowledged messages not retained, no ordering, no exactly-once. | One audit messages topic on your Kafka cluster, with the broker list and credentials provided to the deployment as a secret. | | Dead letter | A dead-letter topic with its own pull subscription: 120 s acknowledgement deadline, 3-day retention, acknowledged messages retained so they can be inspected after the fact. | A dead-letter topic. It is **required**: the deployment refuses to start without one. | | Publisher | The platform's ingestion service needs publish rights on the audit topic; the audit log service only subscribes and never publishes. | Produce rights for the ingestion service on the audit topic; for the audit log service, consume rights on the audit topic and produce rights on the dead-letter topic, where it parks what it cannot write. | | Retention rule | Keep the defaults. For four hours the service remembers every event it has written, so a redelivery inside that time is acknowledged without a second write; the subscription's retention (three hours) must stay shorter than that window. Lengthening the retention without lengthening the window lets a late redelivery be written twice. | Same rule for the topic's retention. | Names of the topics and subscriptions are agreed at deployment and appear in the deployment values below. # Identities and permissions Each workload runs under its own identity (a GCP service account bound through Workload Identity, an IAM role bound through IRSA on AWS). The split is the security property of the design: the verifier can prove tampering precisely because it cannot write, and no single identity can both sign and read everything. | Identity | On the signing key | On the write-once bucket | Elsewhere | | --- | --- | --- | --- | | **Audit log service** | GCP: `roles/cloudkms.signer` and `roles/cloudkms.publicKeyViewer` (it serves the JWK Set). AWS: `kms:Sign`, `kms:GetPublicKey`, `kms:DescribeKey`. | GCP: `roles/storage.objectCreator`, `roles/storage.bucketViewer`, `roles/storage.objectViewer`. AWS: `s3:ListBucket`, `s3:GetBucketVersioning`, `s3:GetObject`, `s3:GetObjectRetention`, `s3:PutObject`. | GCP: `roles/pubsub.subscriber` and `roles/pubsub.viewer` on the project; log, metric and trace writer. AWS: `kms:Decrypt`, `kms:Encrypt`, `kms:GenerateDataKey`, `kms:DescribeKey` on the storage key. | | **Checkpoint generator** | Signer and public key viewer, as above. | Object creator, bucket viewer, object viewer, as above (it reads manifests when its cache is empty). | Log, metric and trace writer. | | **Integrity verifier** | Public key viewer only. | Bucket viewer and object viewer only. **No write permission of any kind.** | Log, metric and trace writer. | | **Cloud Storage service agent** (GCP) | | | `roles/cloudkms.cryptoKeyEncrypterDecrypter` on the storage key, so the bucket can use it. Google's log-delivery group gets `roles/storage.objectCreator` on the access-log bucket. | - **Create the identities first.** The infrastructure grants roles to them by name; applying it before they exist fails on the first grant. On GCP, service account IDs are 6 to 30 characters. - **Object creator is not object admin.** A writer can add objects and new generations under an existing name, but cannot delete; the locked retention policy and unique object names do the rest. - **Never grant `s3:PutObjectRetention`** to a workload: with it, any pod could move objects to `COMPLIANCE` mode, which nobody can undo. - **If your IAM is managed centrally**, the deployment can be told not to touch IAM at all; the grants in the table are then yours to make, exactly as listed. - **AWS without per-pod identities** (no IRSA or Pod Identity) means the node role carries all of the above, and every pod on the node shares it. Treat that as a stopgap, not a design. # Values to hand over The deployment is configured with the following values from your side. They are typically outputs of the infrastructure apply. | Value | GCP | AWS | | --- | --- | --- | | Cloud provider | Set explicitly. The service does not detect it; without the setting, start-up probes the cloud metadata service for about 15 seconds and then fails. | | | Signing key | The **full key version** resource name, ending in `/cryptoKeyVersions/`, not the key. | The key **ARN**, never an alias. | | Key identifier | The `kid` to stamp on every signature and publish in the JWK Set, unique per key. | | | Write-once bucket | `gs://` | `s3://?region=`, and the AWS region in the service's environment. | | Message bus | Topic and subscription names. | The Kafka driver with the audit topic to receive from and the dead-letter topic, and the broker secret. | | Identities | The three service account emails, one annotation per workload. | The three IRSA role ARNs, one annotation per workload. | | Public API host | The host name under your domain that serves the platform API, for example `api.example.com`. The deployment exposes `/audit/v1` and `/audit/.well-known` on it. Clients then call it exactly as they would call `https://us.api.indykite.com` on the shared platform. | | | Scheduled jobs | Whether the checkpoint generator and the integrity verifier are enabled (both should be, outside a throwaway environment), each with its own identity. | | # Decisions you cannot undo | Decision | Why it is one-way | When to take it | | --- | --- | --- | | **Locking the retention** (GCP retention lock, AWS `COMPLIANCE` mode) | Once locked, the retention period can never be shortened or removed by anyone, the cloud provider and the account root included. Objects already under `COMPLIANCE` stay until they expire. | After the pipeline has run in that environment and the acceptance tutorial passes. Never in an environment that is torn down on a schedule. | | **Enabling the audit log** on GCP | The signing key, the storage key and the write-once bucket are protected against destruction. Disabling the module later plans their destruction, which the protection blocks; the apply errors instead of disabling anything. | When the environment is meant to keep its trail. Decide the storage split at the same time: a disaster-recovery project can run the service against another project's keys and bucket, but switching that later hits the same protection. | | **Naming the key ring** (GCP) | A key ring cannot be deleted or renamed, so its name is permanent. | Before the first apply. | | **Destroying the signing key** | Every batch, manifest and checkpoint signed with it becomes unverifiable, forever. | Never. There is no rotation path; a new key would start a new, separately verifiable history. | # Operations - **Alert on the integrity verifier's exit code.** Exit code `2` means findings: a hash, link or signature that does not verify, tampering or corruption. Any other non-zero code means the job itself failed (could not read the bucket or the key) and must be investigated before the next run. Page on both; only `0` is good news. A verifier that cannot ask the platform which projects still exist fails the same way as one that cannot read the bucket. - **A deleted project keeps its chain, but the jobs pass it over.** Deleting a project removes nothing from the bucket. On every run, both jobs ask the platform which of the projects in the bucket still exist and skip the rest: the checkpoint generator writes no further checkpoint or key record for a deleted project, and the integrity verifier neither checks its chain nor counts it among the chains checked; it counts such chains separately in its run log. Export a project's trail before deleting it if you need it verified afterwards, since the recorded checkpoints and keys stay valid for an independent verification but no new ones are added. - **Alert on dead-letter depth.** A message in the dead-letter topic is an audit event that was not written to the chain after all attempts. The three-day retention of the dead-letter subscription is the time you have to look at it. - **Keep Cloud KMS data-access audit logs on** (admin read, data read, data write) so every signing operation is itself logged by the provider. Storage and Pub/Sub data-access logs are not required for the design to hold, but the access-log bucket already records bucket access. - **Watch the subscription backlog** against its three-hour retention: a backlog older than that is lost input. - **Export regularly.** The trail in the bucket is yours, but an export taken from the API and kept elsewhere, with the JWK Set of the time, is what lets an outside party verify independently; the [audit trail tutorial](/tutorials/tutorial-audit-trail) shows how. # Acceptance Before locking the retention, prove the deployment end to end: produce events, read them back through the public host, fetch the JWK Set and verify a page offline. The [acceptance tutorial](/tutorials/tutorial-audit-acceptance) does this in five chapters with a single-file verifier. # Related - The chain and its API: [Audit Log guide](/guides/guide-audit-log) - Who manages the signing key, as seen from a project: [Audit Signing guide](/guides/guide-audit-signing) - Export and verify a whole trail: [Audit trail tutorial](/tutorials/tutorial-audit-trail), [export and verification scripts](/resources/audit-log-1) - Where your graph data lives, the other half of data residency: [Data Residency guide](/guides/guide-data-residency) --- Source: https://developer.indykite.com/guides/guide-audit-infrastructure --- # Audit Log API: Read and Export the Tamper-Proof Audit Trail > Page through your project's signed audit-event batches, the chain manifests that link them, and the signed checkpoints with the Audit Log REST API, fetch the public signing keys, and check an export independently of the platform. **Category:** Audit Log ## Summary What the tamper-proof audit chain is (events, batches, manifests, checkpoints, signing keys), the Audit API permission an Application Agent needs, the four endpoints with every parameter, response field and error, worked curl and jq examples for exporting a project's trail, and the exact hashing and signature rules for verifying it. ## Content Download this guide as a PDF: [guide-audit-log.pdf](/assets/downloads/guide-audit-log.pdf). # What is the Audit Log API? The audit events the platform records for a project - Capture upserts and deletes, configuration changes, token introspections, AuthZEN decisions and searches, ContX IQ executions, CDC changes - are appended to that project's **chain** under two conditions: the project has an [Audit Signing](/guides/guide-audit-signing) configuration, and an [Event Sink](/guides/guide-outbound-events) of the project delivered the event to at least one of its destinations. An event that no sink route matched, or that the destination rejected, is not chained; the chain holds exactly what your sinks received. Organization-level configuration events (Service Accounts, credentials, projects) belong to no project and are never chained. Events are collected into **batches**; each batch is hashed and signed, a signed **manifest** links it to the batch before it, and a signed **checkpoint** periodically fixes the chain's head. The **Audit Log API** is the read side of that chain: it pages through the batches, the manifests and the checkpoints of one project, and publishes the keys that signed them, so an export can be kept and checked without an IndyKite account. The events are the same `indykite.audit.*` events that [Outbound Events](/guides/guide-outbound-events) can push to your own Kafka, Event Grid, Service Bus or Pub/Sub. Outbound Events deliver them as they happen; the Audit Log API keeps them, signed and linked. Who manages the signing key - the platform, or your own key store in GCP KMS, AWS KMS or Azure Key Vault - is declared by the [Audit Signing](/guides/guide-audit-signing) configuration; the `kid` on every record names the key that signed it. ![The chain: events are cut into batches, each batch is hashed and signed, a manifest per batch links to the previous one through prev_hash and head_hash, a checkpoint signs the head at a point in time, and every signature names its key by kid in the JWK Set](/assets/images/audit-chain.svg) ## Terms used in this guide | Term | Meaning | | --- | --- | | Chain | One project's audit trail: a sequence of batches numbered from 1, each linked to the previous one by a hash. | | Batch | A JSON array of consecutive audit events, hashed and signed as one unit. Returned by `GET /audit/v1/logs`. | | Manifest | The linking record of one batch: its position, the previous head, the hash of its events, the new head, and a signature over that head. Returned by `GET /audit/v1/manifests`. | | Checkpoint | A signed statement that, at a given time, the chain had reached a given sequence with a given head. Returned by `GET /audit/v1/checkpoints`. | | Sequence | The position of a batch and its manifest in the chain, starting at 1, contiguous. | | Key id (`kid`) | The identifier of the key that made a signature; it matches a `kid` in the JWK Set at `GET /audit/.well-known/jwks.json`. | # What do I need before calling it? - **The project GID** (`gid:…`). Every endpoint takes it as the `project_id` query parameter. - **An Application Agent in that project with the `Audit` API permission**, and one of its credentials. The credential goes into the `X-IK-ClientKey` header, as for every Application Agent API (see the [Credentials guide](/guides/guide-credentials)). No user token, no Service Account token, no request body. - **The regional base URL** of the project: `https://eu.api.indykite.com` or `https://us.api.indykite.com`. `Audit` is a separate permission and is not added to existing agents automatically. Grant it when creating the agent, or add it to an existing one; the [Environment guide](/guides/guide-environment) lists every permission. ```json POST /configs/v1/application-agents { "application_id": "gid:YOUR_APPLICATION_GID", "name": "audit-exporter", "display_name": "Audit exporter", "api_permissions": [ "Audit" ] } ``` The grant is applied asynchronously, so an agent updated a moment ago can still answer `401` `insufficient API access level for appAgent` for a short while. The credential is scoped to exactly one project, and the listing endpoints refuse any other `project_id` with `403`. So `project_id` is always the project the credential belongs to; it is spelled out so the request is explicit. # Which endpoints are there? | Endpoint | Returns | Order | Authentication | | --- | --- | --- | --- | | `GET /audit/v1/logs` | The chain batches, each with its audit events in `data` | Sequence order, from the start of the chain | `X-IK-ClientKey`, `Audit` permission | | `GET /audit/v1/manifests` | The chain manifests: linkage and signatures without the events | Sequence order, from the start of the chain | `X-IK-ClientKey`, `Audit` permission | | `GET /audit/v1/checkpoints` | The signed checkpoints | Newest first | `X-IK-ClientKey`, `Audit` permission | | `GET /audit/.well-known/jwks.json` | The JWK Set of the signing keys | - | None. The keys are public by design. | All four take `project_id`. The three listing endpoints also take `cursor` and `pagesize`, and answer with the same envelope. The OpenAPI document is published at [openapi.indykite.com/api-documentation/audit](https://openapi.indykite.com/api-documentation/audit). ## Query parameters | Parameter | Required | Meaning | | --- | --- | --- | | `project_id` | yes | The project GID. Must be a well-formed project identifier and, on the listing endpoints, the project of the credential. | | `cursor` | no | Opaque page cursor, copied verbatim from the `next_cursor` of the previous response. Omit it for the first page. Listing endpoints only. | | `pagesize` | no | Items per page. Default `50`, maximum `50`; a larger value is capped to 50 without an error. `0`, a negative number or a non-number is a `400`. Listing endpoints only. | Requests carry no body. The request must accept JSON: send `Accept: application/json` or `*/*` (curl does so by default). Any other value, or no `Accept` header at all, is refused with `406`. ## Response envelope ```json { "next_cursor": "NTA", "has_more": true, "items": [ … ] } ``` - `has_more` is `true` while another page exists. Loop until it is `false`. - `next_cursor` is the cursor of the next page and `""` on the last one. Pass it back as it is; never build one yourself. - `items` is the page, `[]` on an empty chain. An empty chain is a `200`, not an error: no audit event has been recorded for the project yet. `/logs` and `/manifests` page in lockstep: a page of each started from the same cursor covers the same sequences, so a manifest cursor can be used on `/logs` and the other way round. Checkpoint cursors are their own family and are not interchangeable with those two. # How do I export a project's trail? The examples below use three shell variables. The order is the one an export is usually taken in: keys first, then the small manifests, then the events, then the checkpoints. ```bash API_URL=https://eu.api.indykite.com # or https://us.api.indykite.com, matching the project's region PROJECT_ID="gid:YOUR_PROJECT_GID" CLIENT_KEY="" ``` ## Step 1: Fetch the signing keys ```bash curl -s "$API_URL/audit/.well-known/jwks.json?project_id=$PROJECT_ID" > jwks.json ``` No credential is sent. The response is a standard JWK Set (RFC 7517) with one or more EC keys: ```json { "keys": [ { "kty": "EC", "crv": "P-256", "x": "…", "y": "…", "use": "sig", "kid": "…" } ] } ``` The keys carry no `alg` member on purpose: the algorithm label travels with each signed item (see [How do I verify an export?](#how-do-i-verify-an-export)). The response is cacheable for 60 seconds (`Cache-Control: public, max-age=60`). Keep the file next to the trail you export: it names the keys the export was signed with, so the export verifies without the API. The set holds every key that has signed for the project, current and retired, so a `kid` of an older record stays in it after a rotation. A project with no signed data yet has an empty set, and the first key of a project, or a key added by a rotation, can take up to 2 minutes to be listed. When too many keys are being loaded at once the endpoint answers `503` with a `Retry-After` header; retry after that many seconds. ## Step 2: Page through the manifests ```bash curl -s "$API_URL/audit/v1/manifests?project_id=$PROJECT_ID&pagesize=50" \ -H "X-IK-ClientKey: $CLIENT_KEY" ``` ```json { "next_cursor": "NTA", "has_more": true, "items": [ { "manifest_id": "0d1a7a6e-6c6c-4a53-9f1c-0e0f4b4a1c2d", "batch_id": "7b3f2b9a-5d1e-4c1b-8a4e-2f6c9d8e7a10", "batch_uri": "…", "project_id": "gid:YOUR_PROJECT_GID", "sequence": 1, "prev_hash": "", "data_hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "head_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", "kid": "…", "alg": "ES256-DER", "signature": "MEUCIQ…", "created_at": "2026-09-30T14:02:11.482913604Z" } ] } ``` | Field | Meaning | | --- | --- | | `manifest_id` | Identifier of this manifest. The batch at the same sequence names it in its `manifest_id`. | | `batch_id` | Identifier of the batch this manifest describes. | | `batch_uri` | An opaque reference to the batch, for correlation only; it is not fetchable by the caller. Use `GET /audit/v1/logs` for the events. | | `project_id` | The project the chain belongs to. | | `sequence` | Position in the chain, starting at 1, contiguous. | | `prev_hash` | The `head_hash` of the previous manifest. Empty for sequence 1. | | `data_hash` | Hex SHA-256 of the batch's `data`; equal to the batch's `hash`, so the content is described without fetching it. | | `head_hash` | The chain head after this batch. The next manifest carries it as `prev_hash`, and the batch carries it as `chain_hash`. | | `kid`, `alg` | The key that signed this manifest and the algorithm label, always `ES256-DER`. | | `signature` | Base64 signature over `head_hash`. | | `created_at` | When the manifest was written, RFC 3339 with nanoseconds, UTC. | To fetch every manifest, follow `next_cursor` until `has_more` is `false`. An HTTP error must stop the loop rather than end it, otherwise a `401` or `500` body would be taken for the last page and the export would be silently truncated; `curl -f` turns such a status into a failure. The same loop writes `logs.jsonl` or `checkpoints.jsonl` when the path and the file name are changed. For the logs, keep the response pages as well (`curl -o`), since the batch `hash` covers the `data` array as served and `jq -c` re-encodes it; the [export and verification scripts](/resources/audit-log-1) do both. ```bash cursor="" : > manifests.jsonl while :; do page=$(curl -fsS "$API_URL/audit/v1/manifests?project_id=$PROJECT_ID&pagesize=50&cursor=$cursor" \ -H "X-IK-ClientKey: $CLIENT_KEY") || { echo "export failed; manifests.jsonl is incomplete" >&2; exit 1; } echo "$page" | jq -c '.items[]' >> manifests.jsonl [ "$(echo "$page" | jq -r '.has_more')" = "true" ] || break cursor=$(echo "$page" | jq -r '.next_cursor') done jq -s 'map(.sequence) | max' manifests.jsonl # the newest sequence recorded ``` ## Step 3: Read the audit events ```bash curl -s "$API_URL/audit/v1/logs?project_id=$PROJECT_ID&pagesize=10" \ -H "X-IK-ClientKey: $CLIENT_KEY" ``` Each item is one signed batch. `data` is the JSON array of the audit events in that batch, in the order the platform received them; the other fields describe and sign it. A batch with one Capture upsert event: ```json { "next_cursor": "MQ", "has_more": true, "items": [ { "batch_id": "7b3f2b9a-5d1e-4c1b-8a4e-2f6c9d8e7a10", "project_id": "gid:YOUR_PROJECT_GID", "sequence": 1, "hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "signature": "MEQCIB…", "kid": "…", "alg": "ES256-DER", "chain_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", "manifest_id": "0d1a7a6e-6c6c-4a53-9f1c-0e0f4b4a1c2d", "data": [ { "appSpaceId": "gid:YOUR_PROJECT_GID", "customerId": "gid:YOUR_CUSTOMER_GID", "data": { "@type": "type.googleapis.com/indykite.auditsink.v1beta1.UpsertData", "node": { "id": "…", "externalId": "millicent", "type": "Person", "isIdentity": true, "properties": [ { "type": "email", "value": { "stringValue": "millicent@email.com" }, "externalValue": "" } ] } }, "eventSource": "…", "eventType": "indykite.audit.capture.upsert.node", "initiator": { "appAgentCredentialsId": "gid:YOUR_APP_AGENT_CREDENTIALS_GID", "appAgentId": "gid:YOUR_APP_AGENT_GID", "appSpaceId": "gid:YOUR_PROJECT_GID", "applicationId": "gid:YOUR_APPLICATION_GID", "customerId": "gid:YOUR_CUSTOMER_GID" }, "requestId": "…", "time": "2026-09-30T14:01:58.113904211Z" } ] } ] } ``` | Batch field | Meaning | | --- | --- | | `batch_id`, `project_id`, `sequence` | As on the manifest at the same sequence. | | `data` | The audit events: a JSON array, one object per event, in the order the platform received them, which is not always the order in which they happened. A batch holds events of one project that arrived together; it can hold one event or many, since batches are cut by size or by time. | | `hash` | Hex SHA-256 of `data`, the value `signature` covers. Equal to the manifest's `data_hash`. | | `signature`, `kid`, `alg` | Base64 signature over `hash`, the key that made it, and the algorithm label `ES256-DER`. | | `chain_hash` | This batch's position in the chain; equal to the manifest's `head_hash`. | | `manifest_id` | The manifest describing this batch. | Every event in `data` has the same top-level shape, whatever its type: | Event field | Meaning | | --- | --- | | `eventType` | The event type, one of the `indykite.audit.*` names listed in the [Outbound Events guide](/guides/guide-outbound-events): `indykite.audit.capture.upsert.node`, `indykite.audit.config.update`, `indykite.audit.config.list`, `indykite.audit.authorization.evaluation`, `indykite.audit.ciq.execute`, `indykite.audit.cdc.node.update` and so on. Reading the trail itself is not an audited operation, but listing policies with `GET /access/v1/policies` is, so a project that is only being inspected still grows a `config.list` event per call. | | `time` | When the event happened, RFC 3339 with nanoseconds, UTC. | | `customerId`, `appSpaceId` | The customer and the project the event happened in. `appSpaceId` is the `project_id` of the request. | | `initiator` | Who initiated the request, as a flat object of string identifiers whose keys tell the kind of caller apart: an Application Agent carries `applicationId`, `appAgentId` and `appAgentCredentialsId`; a Service Account carries `serviceAccountId` and `serviceAccountCredentialsId`; an end user carries `digitalTwinId`, `viaApplicationId` and `sessionId`. Each form also repeats `customerId` and `appSpaceId`. Keys with no value are left out, and the whole object is absent when the caller is not known. | | `requestId` | The identifier of the request that caused the event, the same value the API returned to the caller. Always present, empty when there was none. | | `data` | The event payload, typed by its `@type` member, for example `type.googleapis.com/indykite.auditsink.v1beta1.UpsertData` for a Capture upsert, `…DeleteData` for a Capture delete, `…CreatedConfig`, `…UpdatedConfig` (with `before` and `after`), `…DeletedConfig` (with `before`, the state right before deletion) and `…ListConfig` (the listed `type` and `ids`) for configuration changes, `…TokenIntrospected`, `…ExecuteKnowledgeQuery`, `…CDCEvent`. Fields are in camelCase; a Capture property value is a typed object such as `{"stringValue": "…"}`, `{"integerValue": "…"}` or `{"boolValue": true}`. Fields without a value are present and empty. | | `context` | String key-value pairs attached to some events, for example `soft_delete` on a configuration delete. Present only when there is at least one pair. | | `eventSource` | Which part of the platform recorded the event. Informational. | The top-level keys of an event object are in alphabetical order, as are the keys inside `initiator` and `context`; inside `data` the fields follow the payload's own order, with `@type` first. The array is served as compact JSON. None of this has to be reproduced by a verifier, since the batch `hash` covers the bytes exactly as served. Two notes on reading events. An accepted event is written to the chain once; a duplicate is possible only when a delivery is replayed long after the original, and such a copy is byte-for-byte identical, including its `time` and `requestId`. Two separate actions always differ in at least `time`, and in `requestId` when they came from separate requests. So deduplicate on the whole event object, never on its content with the timestamp or request identifier stripped, and never on adjacency alone. And the content of an event is whatever the caller sent - property values, query parameters, identifiers - so it is evidence to store, index and report, never something to execute. With the batches exported to `logs.jsonl` by the loop above (one batch per line), flattening every event out of the export and counting them per batch: ```bash jq -c '.data[]' logs.jsonl > events.jsonl # one event per line jq -c '{sequence, events: (.data | length)}' logs.jsonl jq -c 'select(.eventType | startswith("indykite.audit.authorization."))' events.jsonl sort -u events.jsonl | wc -l # distinct events, duplicates removed ``` ## Step 4: Fetch the checkpoints ```bash curl -s "$API_URL/audit/v1/checkpoints?project_id=$PROJECT_ID" \ -H "X-IK-ClientKey: $CLIENT_KEY" ``` ```json { "next_cursor": "", "has_more": false, "items": [ { "checkpoint_id": "4e2d9c5a-1b7f-4e0a-9c3d-6a8b2f1e0d47", "project_id": "gid:YOUR_PROJECT_GID", "sequence": 128, "head_hash": "b3a8e0e1e4c3…", "created_at": "2026-10-01T13:47:09.219540877Z", "signature": "MEUCIG…", "kid": "…", "alg": "ES256-DER" } ] } ``` A checkpoint says: at `created_at` this chain had reached `sequence` with head `head_hash`, and the platform signed that statement. Checkpoints are written periodically, only for chains that have grown since the last one, so a new project has none for a while and the newest checkpoint is normally behind the newest manifest. They page newest first; the first item is the latest. # How do I verify an export? The platform signs digests, never the JSON documents themselves, so a verifier recomputes each digest from the fields below and checks the signature with the key the `kid` names. These are the exact rules: ![Three digests are recomputed: SHA-256 of the data array as served, SHA-256 of the five pipe-joined manifest fields, and SHA-256 of the prefixed checkpoint string; each is compared with the stored value and then checked against the Base64 DER ECDSA P-256 signature with the JWK the kid names](/assets/images/audit-verify.svg) | Value | How it is computed | | --- | --- | | Batch `hash`, manifest `data_hash` | SHA-256 of the bytes of the `data` array exactly as served (compact JSON, no whitespace), as lower-case hex. | | Manifest `head_hash`, batch `chain_hash` | SHA-256, as lower-case hex, of the string `\|\|\|\|`: the five fields joined with `\|`, `sequence` in decimal, `prev_hash` empty for sequence 1. | | Batch `signature` | Over the 32-byte digest that `hash` encodes. | | Manifest `signature` | Over the 32-byte digest that `head_hash` encodes. | | Checkpoint `signature` | Over the SHA-256 of the string `project-checkpoint\|\|\|\|`, with `created_at` exactly as returned. | | Signature encoding (`alg` `ES256-DER`) | ECDSA with the P-256 curve over a SHA-256 digest, the signature ASN.1 DER-encoded and then Base64-encoded with the standard alphabet and padding. This is the encoding a KMS produces, not the fixed-size R\|\|S form that JWS `ES256` (RFC 7518) defines; a JWT or JWS library will reject it unless the signature is converted first. | | Key | The JWK in the set whose `kid` equals the item's `kid`: `kty` `EC`, `crv` `P-256`. | Re-serializing `data` can change its bytes (key order, escaping, whitespace), so hash the array as it appears in the response rather than a re-encoded copy. Checking one manifest signature with OpenSSL. The JWK is first converted to a PEM public key; the lines below do it with the same `cryptography` package the verifier uses, so no JWT library is needed: ```bash KID=$(head -n 1 manifests.jsonl | jq -r '.kid') # the key the first exported manifest names python3 - "$KID" <<'EOF' > key.pem import json, base64, sys, glob from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ec keys = {} for path in sorted(glob.glob("jwks*.json")): # the current set and every archived snapshot with open(path, encoding="utf-8") as f: doc = json.load(f) for key in doc["keys"]: keys[key["kid"]] = key k = keys[sys.argv[1]] n = lambda s: int.from_bytes(base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)), "big") pub = ec.EllipticCurvePublicNumbers(n(k["x"]), n(k["y"]), ec.SECP256R1()).public_key() print(pub.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode(), end="") EOF ``` ```bash HEAD_HASH=$(head -n 1 manifests.jsonl | jq -r '.head_hash') # the first exported manifest SIGNATURE=$(head -n 1 manifests.jsonl | jq -r '.signature') echo -n "$HEAD_HASH" | xxd -r -p > digest.bin # the 32 bytes the signature covers echo "$SIGNATURE" | base64 -d > signature.der openssl pkeyutl -verify -pubin -inkey key.pem -in digest.bin -sigfile signature.der # Signature Verified Successfully ``` The chain is intact when every manifest's `prev_hash` equals the previous manifest's `head_hash`, every `head_hash` recomputes from its five fields, every batch's `hash` recomputes from its `data` and equals the manifest's `data_hash`, every signature verifies under its `kid`, and a checkpoint's `head_hash` equals the manifest's at the same `sequence`. An export that holds the manifests, the checkpoints and the logs for one `project_id`, each fetched to `has_more: false`, together with JWKS snapshots that between them contain every `kid` those records reference, is self-contained for that check. Since the set keeps retired keys, a `jwks.json` fetched after the newest record was signed covers every `kid` of the trail; a `kid` signed within the last 2 minutes may not be listed yet, so fetch the set again a little later when one is missing. Keep the set with each export, so that the export verifies without the API. # What errors should I expect? Errors are a JSON body with a `message`, except the `406`, whose body has an `error` member. | Status | Message | Cause and fix | | --- | --- | --- | | `200` | `"items": []` | Empty chain: nothing recorded for the project yet. Not an error. A new project also has no checkpoints until its chain has grown. | | `400` | `project_id is required` | Add `?project_id=`. Applies to the JWKS endpoint too. | | `400` | `project_id is not a valid project identifier` | The value is not a project GID. | | `400` | `invalid cursor: …`, `invalid cursor` | The cursor was edited, truncated, taken from the other endpoint family, or from another project's checkpoints. Copy `next_cursor` verbatim. | | `400` | `pagesize must be a positive integer` | `pagesize` is `0`, negative or not a number. | | `401` | `Missing or malformed AppAgent credential token in X-IK-ClientKey header` | The header is absent or not an Application Agent credential. The JWKS endpoint takes none. | | `401` | `insufficient API access level for appAgent` | The agent lacks the `Audit` permission. Add it to `api_permissions`; the grant is applied asynchronously. | | `403` | `the authenticated credential does not have access to this project` | `project_id` is not the credential's project, even if it is another project of the same customer. Use that project's own agent. | | `406` | `Accept must be application/json or */*` | The `Accept` header is absent or allows neither. Set `Accept: application/json`. | | `500` | `Internal Server Error` | A platform-side failure. Retry; if it persists, report it with the time and the project. | # Next Steps - Step by step from an empty project to a verified export: [Tamper-proof audit trail tutorial](/tutorials/tutorial-audit-trail) - Ready-made export and verification scripts: [Audit Log resource](/resources/audit-log-1) - Running the audit log in your own cloud account, and accepting it: [infrastructure guide](/guides/guide-audit-infrastructure) and [acceptance tutorial](/tutorials/tutorial-audit-acceptance) with a single-file Go verifier - Who holds the signing key: [Audit Signing guide](/guides/guide-audit-signing), and the [Terraform example](/terraform/terraform-8) - The same events pushed to your own broker as they happen, and the full list of event types: [Outbound Events guide](/guides/guide-outbound-events) - The payload fields of every event type, the CloudEvents envelope, and the Agent Gateway, Token Service and Intent Agent records side by side: [Audit Event Formats guide](/guides/guide-audit-formats) - Application Agent permissions: [Environment guide](/guides/guide-environment) and [Credentials guide](/guides/guide-credentials) - Export from a coding agent: the [indykite-audit-logs](/agent-skills/indykite-audit-logs/SKILL.md) skill (see the [Agent Skills guide](/guides/guide-skills)) - API reference: [Audit Log API OpenAPI document](https://openapi.indykite.com/v1/audit.yaml) --- Source: https://developer.indykite.com/guides/guide-audit-log --- # Audit Signing: Control the Key That Signs Your Audit Records > Configure who manages the signing key for your project's audit records - the platform, or your own key in GCP KMS, AWS KMS, or Azure Key Vault - via the Config API. **Category:** Audit Signing ## Summary What an Audit Signing configuration is, the supported key providers, every field and its validation rules, and the full REST lifecycle: create, read, list, update with ETag, and delete. ## Content Download this guide as a PDF: [guide-audit-signing.pdf](/assets/downloads/guide-audit-signing.pdf). # What is Audit Signing? An **Audit Signing configuration** declares who manages the cryptographic key used to sign your project's audit records, making them tamper-evident. You can choose to have the platform manage the signing key for you; with a customer-managed provider, the configuration names a key that lives in **your own** cloud key store - Google Cloud KMS, AWS KMS, or Azure Key Vault - so key custody, rotation, and revocation stay under your control. Today the platform-managed key signs every record. A customer-managed configuration is stored and validated for the upcoming customer-managed key support, and records will carry its `kid` once it is used for signing; until then every record carries the platform key's `kid`. The configuration also switches the chain on. A project without an Audit Signing configuration has no tamper-proof trail: its audit events are delivered to its [Event Sinks](/guides/guide-outbound-events) but never chained, and the [Audit Log API](/guides/guide-audit-log) returns an empty chain for it. With one, every event that an Event Sink of the project delivered is chained; an event no sink route matched, or that the destination rejected, is not. Create the Audit Signing configuration and an Event Sink before the events you want on the trail. The configuration is a project-scoped Config API object, managed with Service Account credentials like other configurations (Token Introspect, MCP Server, Outbound Events). It can also be declared in Terraform with the `indykite_audit_signing` resource (see the [Terraform example](/terraform/terraform-8)). ![Platform-managed: the platform signs digests with its own key. Customer-managed: the configuration names a key in your KMS or Key Vault, the platform sends only the digest and receives a signature, and the private key never leaves. Either way every record carries kid, alg and signature, and a verifier resolves the kid through the JWK Set](/assets/images/audit-signing-key.svg) Every batch, manifest and checkpoint the [Audit Log API](/guides/guide-audit-log) serves carries the `kid` of the key that signed it, and `GET /audit/.well-known/jwks.json` publishes the public keys those `kid` values refer to. A verifier selects the key by the `kid` each record carries and resolves it through that JWK Set. # Which key providers are supported? | Provider | Who holds the key | Requires | | --- | --- | --- | | `PLATFORM_MANAGED` | IndyKite manages the signing key; nothing else has to be supplied. | Nothing beyond `name` and `project_id`. | | `CUSTOMER_GCP_KMS` | Your key in Google Cloud KMS. | `key_resource` + `kid`, plus provider access material in `auth_params`. Stored for the upcoming customer-managed key support; not used for signing yet. | | `CUSTOMER_AWS_KMS` | Your key in AWS KMS. | `key_resource` + `kid`, plus provider access material in `auth_params` (e.g. `role_arn` and `external_id`). Stored for the upcoming customer-managed key support; not used for signing yet. | | `CUSTOMER_AZURE_KEY_VAULT` | Your key in Azure Key Vault. | `key_resource` + `kid`, plus provider access material in `auth_params`. Stored for the upcoming customer-managed key support; not used for signing yet. | ## What must the customer-managed key look like? Audit records are signed with ECDSA on the P-256 curve over a SHA-256 digest (the `alg` label `ES256-DER` on every signed record). A customer-managed key therefore has to be an asymmetric **EC P-256 signing key**, and the platform needs permission to sign with it and to read its public key; the private key never leaves your key store. `key_resource` identifies the key in the provider's own naming scheme: | Provider | `key_resource` | Key requirements | | --- | --- | --- | | `CUSTOMER_GCP_KMS` | The full crypto key **version** resource name, ending in `/cryptoKeyVersions/`: `projects/my-project/locations/europe-west1/keyRings/audit/cryptoKeys/signing/cryptoKeyVersions/1`. The Config API accepts any identifier up to 256 characters; the crypto key name alone, without a version, does not identify a key version to sign with. | Purpose asymmetric sign, algorithm `EC_SIGN_P256_SHA256`. Grant the identity in `auth_params` the `cloudkms.cryptoKeyVersions.useToSign` and `cloudkms.cryptoKeyVersions.viewPublicKey` permissions on the key. | | `CUSTOMER_AWS_KMS` | The key ARN: `arn:aws:kms:eu-west-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab`. The region segment of the ARN selects the KMS region. Prefer the ARN over an alias, so that `kid` always names one fixed key rather than a pointer that can be moved. | Key spec `ECC_NIST_P256`, usage sign and verify, signing algorithm `ECDSA_SHA_256`. Grant `kms:Sign` and `kms:GetPublicKey` on the key. AWS recommends giving a third party an IAM role rather than long-term access keys: a role that trusts the platform's account, with an external ID in its trust policy, passed as its role ARN. | | `CUSTOMER_AZURE_KEY_VAULT` | The Key Vault key identifier: `https://my-vault.vault.azure.net/keys/audit-signing`. | Key type EC, curve P-256, with the `sign` key operation permitted for the identity used. Without a version segment the identifier resolves to the key's latest version. | `auth_params` holds the access material the provider needs to let the platform use that key. The platform does not prescribe the key names: it stores whatever string pairs you send, at most 32, each key and value between 1 and 256 characters, no empty values. The examples in this documentation use the forms each cloud's own guidance recommends for giving a third party access to a key, and that fit that limit: | Provider | `auth_params` keys used in the examples | What they are | | --- | --- | --- | | `CUSTOMER_AWS_KMS` | `role_arn`, `external_id` | An IAM role whose trust policy names the platform's AWS account (IndyKite provides the account ID) and requires the external ID. AWS recommends this over long-term access keys for third-party access. | | `CUSTOMER_GCP_KMS` | `client_email` | The service account to use, granted the two Cloud KMS permissions on the key. Naming it is not enough on its own: on the Google Cloud side the platform's identity (IndyKite provides it) must be allowed to act as that account, either by granting it permission to impersonate the account (`roles/iam.serviceAccountTokenCreator`) or by granting the key permissions to the platform's identity directly. | | `CUSTOMER_AZURE_KEY_VAULT` | `tenant_id`, `client_id`, `client_secret` | A service principal registered in the vault's tenant. | Because each value is capped at 256 characters, a whole key file or a PEM-encoded private key does not fit and cannot be passed here. The values are written once and never returned. # What fields does the configuration have? | Field | Type | Description | | --- | --- | --- | | `name` | string, required | URL-friendly identifier, unique within the project. Immutable - it cannot be changed later. Must start with a lowercase letter, continue with lowercase letters, digits or hyphens, and end with a letter or digit. A project may hold several configurations. | | `project_id` | string (GID), required | Project that owns the configuration. | | `display_name` | string, optional (2-254 chars) | Human-readable name; equals `name` when not set. | | `description` | string, optional (2-65000 chars) | Free-text description. | | `provider` | enum, required | `PLATFORM_MANAGED` (if you want an IndyKite managed provider), `CUSTOMER_GCP_KMS`, `CUSTOMER_AWS_KMS`, or `CUSTOMER_AZURE_KEY_VAULT`. Required on create and on update; there is no default. | | `key_resource` | string (max 256) | Identifies the key in the provider's namespace (for AWS KMS, the key ARN). Required for every customer-managed provider. | | `kid` | string (max 256) | The key ID published on records signed with this key, so verifiers can select the right key. Required for every customer-managed provider. Records will carry it once customer-managed keys are used for signing; today they carry the platform key's `kid`. | | `auth_params` | map of string to string (max 32 pairs, each key and value 1-256 chars) | Provider access material (for AWS KMS, e.g. `role_arn` and `external_id`); the key names are not prescribed, see below. **Write-only**: values are accepted on create/update but come back masked as empty strings on every read. An empty value is rejected with `422` and `missing field auth_params[]`; a non-string value with `400` and `invalid field auth_params.`. Omitted entirely on read when none were set. | # How do I create an Audit Signing configuration? All endpoints authenticate with a Service Account Bearer token, like the rest of the Config API. A project has at most one Audit Signing configuration: a second `POST /configs/v1/audit-signings` for the same `project_id` is refused with `409` and `audit signing config already exists in project`, whatever name or provider it carries. The two examples below are therefore alternatives; moving from one provider to the other is an update of the existing configuration. ## Platform-managed (minimal) ```bash curl -X POST /configs/v1/audit-signings \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SERVICE_ACCOUNT_TOKEN" \ -d '{ "name": "audit-signing-default", "project_id": "gid-of-project", "provider": "PLATFORM_MANAGED" }' ``` ## Customer-managed key (AWS KMS example) ```bash curl -X POST /configs/v1/audit-signings \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SERVICE_ACCOUNT_TOKEN" \ -d '{ "name": "audit-signing-byok", "display_name": "Audit signing with our AWS KMS key", "description": "Signs audit records with the compliance team key", "project_id": "gid-of-project", "provider": "CUSTOMER_AWS_KMS", "key_resource": "arn:aws:kms:us-east-1:123456789012:key/example-key-id", "kid": "audit-2026-q3", "auth_params": { "role_arn": "arn:aws:iam::123456789012:role/indykite-audit-signer", "external_id": "a-value-you-generated" } }' ``` **Response (201 Created):** the new configuration's `id` (GID), `create_time`, `created_by`, `update_time`, and `updated_by`, plus an `ETag` response header for optimistic concurrency on later updates and deletes. Reference: [POST /audit-signings](https://openapi.indykite.com/api-documentation-config#tag/audit-signing/POST/audit-signings) # How do I read and list configurations? Read by GID, or by `name` with the `project_id` query parameter (the former `location` parameter is deprecated, still accepted, and rejected when sent together with `project_id`); an optional `version` query parameter reads a specific version. A read by name without `project_id` fails with `422` and `project_id is required when querying by name`: ```bash curl /configs/v1/audit-signings/?project_id= \ -H "Authorization: Bearer $SERVICE_ACCOUNT_TOKEN" ``` The response includes the configuration fields plus `organization_id`, timestamps, and authorship - and **`auth_params` values come back masked as empty strings**; secrets never round-trip. List every configuration in a project with: ```bash curl /configs/v1/audit-signings?project_id= \ -H "Authorization: Bearer $SERVICE_ACCOUNT_TOKEN" ``` The list response wraps the same objects in a `data` array. Without `full_fetch=true` only the metadata of each configuration is returned: `provider`, `key_resource`, `kid` and `auth_params` are left out of every item. `search=` narrows the list to configurations whose name, display name or description contains the text. For a `PLATFORM_MANAGED` configuration a full read returns `key_resource` and `kid` as empty strings and no `auth_params`. # How do I update a configuration? Send a `PUT` with an `If-Match` header carrying the ETag from the last read or write - a stale ETag returns `412 Precondition Failed`. `provider` is required on update; for `display_name` and `description`, `null` keeps the current value while an empty string removes it: ```bash curl -X PUT /configs/v1/audit-signings/ \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SERVICE_ACCOUNT_TOKEN" \ -H "If-Match: $ETAG" \ -d '{ "provider": "CUSTOMER_AWS_KMS", "key_resource": "arn:aws:kms:us-east-1:123456789012:key/rotated-key-id", "kid": "audit-2026-q4", "auth_params": { "role_arn": "arn:aws:iam::123456789012:role/indykite-audit-signer", "external_id": "a-value-you-generated" } }' ``` Once customer-managed keys are in use, rotating one is exactly this: point `key_resource` at the new key and change the `kid`; a verifier tells keys apart by the `kid` each record carries. # How do I delete a configuration? ```bash curl -X DELETE /configs/v1/audit-signings/ \ -H "Authorization: Bearer $SERVICE_ACCOUNT_TOKEN" \ -H "If-Match: $ETAG" ``` **Response (200 OK):** `{"id": ""}`. The `If-Match` header is optional but recommended - exactly as on update, it prevents deleting a configuration someone else just changed. # What errors should I expect? | Status | Meaning | | --- | --- | | `422 Unprocessable Entity` | Validation failed; the body carries a `message` and an `errors` array with the exact reasons: `missing field provider`, `invalid field provider: "" does not meet rule oneof=PLATFORM_MANAGED CUSTOMER_GCP_KMS CUSTOMER_AWS_KMS CUSTOMER_AZURE_KEY_VAULT`, `key_resource is required for customer-managed providers`, `kid is required for customer-managed providers`, `invalid AuditSigningConfig.KeyResource: value length must be at most 256 runes` (same for `Kid`), `invalid AuditSigningConfig.AuthParams: value must contain no more than 32 pair(s)`, `invalid AuditSigningConfig.AuthParams[]: value length must be between 1 and 256 runes`, `invalid field name: is not valid name, value must start with [a-z] followed by [-a-z0-9] and ends with [a-z0-9]`, `missing field project_id`, `invalid field project_id: identifier is not of PROJECT`. | | `400 Bad Request` | The body is not valid JSON, or an `auth_params` value is not a string (`invalid field auth_params.`). | | `412 Precondition Failed` | The `If-Match` ETag on update or delete no longer matches - re-read the configuration and retry. | | `409 Conflict` | The project already has an Audit Signing configuration; the body is `{"message": "Conflict", "errors": ["audit signing config already exists in project"]}`. Update or delete the existing one instead of creating another. | | `404 Not Found` | No configuration with that ID or name (including one already deleted). The body is `{"message": "Not Found", "errors": ["empty response"]}`. | | `401` / `403` | Missing or insufficient Service Account credentials. | # Next Steps - Worked example: [Audit Signing Resource Example](https://developer.indykite.com/resources/audit-signing-1) - Declare it as code: [Audit Signing Terraform example](/terraform/terraform-8) - End to end, from an empty project to a verified export: [Tamper-proof audit trail tutorial](/tutorials/tutorial-audit-trail) - Reading the signed records back and verifying them: [Audit Log API guide](/guides/guide-audit-log) - Environment setup: [Environment Guide](https://developer.indykite.com/guides/guide-environment) - Credentials: [Credentials Guide](https://developer.indykite.com/guides/guide-credentials) - API reference: [Audit Signing endpoints](https://openapi.indykite.com/api-documentation-config#tag/audit-signing) --- Source: https://developer.indykite.com/guides/guide-audit-signing --- # AuthZEN: Authorization Decisions on the Knowledge Graph > How to ask IndyKite for an authorization decision with the AuthZEN REST API: single and batch evaluations, subject, resource and action searches, the tokens involved, and the KBAC policies that produce the answer. **Category:** KBAC ## Summary A complete worked example (graph, policy, request, response), the full request and response reference for every /access/v1 endpoint, how a decision is computed, the exact errors, and what is IndyKite-specific compared to the AuthZEN specification. ## Content # What is AuthZEN? **AuthZEN** is the OpenID Foundation standard for asking an authorization service a question of the form "may this subject perform this action on this resource?" and getting a yes/no answer. The application that asks is the **Policy Enforcement Point (PEP)**; the service that answers is the **Policy Decision Point (PDP)**. IndyKite is the PDP: it answers from **KBAC policies** evaluated against the IndyKite Knowledge Graph (IKG). Policies are written through the Config API (the **Policy Administration Point**) and the graph is the data the decision is made on (the **Policy Information Point**). The picture above shows these four roles. AuthZEN does for authorization what OpenID Connect did for authentication: it replaces vendor-specific authorization APIs with one request and response format, so any application can ask any AuthZEN-compliant PDP and switch or combine PDPs without rewriting the calls. Every request is built from four entities: - `subject`: who is asking (a user, a service, an agent). - `action`: what they want to do. - `resource`: what they want to do it to. - `context`: anything else the decision needs, such as a purchase amount or a region. Externalizing authorization this way keeps the rules out of application code: they are managed, updated and audited in one place, and a fine-grained question such as "may this person drive this car right now?" is answered per request instead of being approximated by static roles. What IndyKite adds is the answer itself: the decision comes from relationships in the graph, so it changes as the data changes, without redeploying the application. ## Terms used in this guide | Term | Meaning | | --- | --- | | **IKG** | The IndyKite Knowledge Graph: a property graph of nodes and relationships, filled through the Capture API (see the [Data Schema guide](/guides/guide-data-schema)). | | **KBAC** | Knowledge-Based Access Control: a policy is a graph pattern (Cypher) between a subject and a resource; the decision is `true` when the pattern matches (see the [Dynamic Authorization guide](/guides/guide-dynamic-authz)). | | **KBAC policy** | A configuration object with a subject type, a list of actions, a resource type and a condition. Created with `POST /configs/v1/authorization-policies` and Service Account credentials, or with Terraform `indykite_authorization_policy`. Versions `2.0-kbac` and `3.0-kbac` are documented here. | | **Application Agent (AppAgent)** | The credential your application calls the runtime APIs with, sent as `X-IK-ClientKey`. It needs the `Authorization` API permission for the decision and search endpoints (see the [Credentials guide](/guides/guide-credentials)). | | **User token** | The end user's OAuth 2.0 access token, sent as `Authorization: Bearer`. Optional on every AuthZEN endpoint. A [Token Introspect](/guides/guide-token-introspect) configuration validates it and maps its subject to a node. | | **Delegation token** | An optional token in `X-IK-Token`, minted by the [IndyKite Token Service](/guides/guide-token-service), describing the chain of agents acting for a user. | | **Identity node** | A node ingested with `is_identity: true`. Required for the subject of a `2.0-kbac` policy. | | **Input parameter** | A value supplied under `context.input_params` and read by a policy as `$name`. | | **Composite IKG** | A graph split across locations for data residency; only relevant to `3.0-kbac` routing (see the [Data Residency guide](/guides/guide-data-residency)). | # A complete example The graph below is the one the AuthZEN resources of this library ingest. People drive cars, and a person holds a ticket for a bus. **Example graph: Person(knightrider) -DRIVES-> Car(kitt); Person(satchmo) -DRIVES-> Car(cadillacv16); Person(alice) -DRIVES-> Car(cadillacv16); Person(karel) -HAS-> Ticket(listek) -FOR-> Bus(harmonika)** Goal: the application asks whether knightrider may drive kitt. Four steps: ingest, policy, request, response. ## Step 1: Ingest the graph Nodes and relationships go in through the Capture API with AppAgent credentials. The people are identity nodes. The full payload is in resource [authz-1](/resources/authz-1); the relevant part: ```json POST /capture/v1/nodes { "nodes": [ { "external_id": "knightrider", "type": "Person", "is_identity": true, "properties": [ { "type": "email", "value": "knightrider@demo.com" } ] }, { "external_id": "kitt", "type": "Car", "properties": [ { "type": "manufacturer", "value": "pontiac" } ] } ] } ``` ```json POST /capture/v1/relationships { "relationships": [ { "source": { "external_id": "knightrider", "type": "Person" }, "target": { "external_id": "kitt", "type": "Car" }, "type": "DRIVES" } ] } ``` ## Step 2: Write the policy A KBAC policy names a subject type, the actions it grants, a resource type, and the graph pattern that must exist between the two. In the pattern, the variable `subject` is the requesting subject and `resource` is the requested resource; the platform binds both from the request. ```json { "meta": { "policy_version": "2.0-kbac" }, "subject": { "type": "Person" }, "actions": [ "CAN_DRIVE" ], "resource": { "type": "Car" }, "condition": { "cypher": "MATCH (subject:Person)-[:DRIVES]->(resource:Car)" } } ``` Store it through the Config API (Service Account credentials). The policy JSON travels as a string in the `policy` field: ```json POST /configs/v1/authorization-policies Authorization: Bearer { "project_id": "gid:AAAABbbbCCCC...", "name": "person-can-drive-car", "display_name": "A person can drive the cars they drive", "policy": "{\"meta\":{\"policy_version\":\"2.0-kbac\"},\"subject\":{\"type\":\"Person\"},\"actions\":[\"CAN_DRIVE\"],\"resource\":{\"type\":\"Car\"},\"condition\":{\"cypher\":\"MATCH (subject:Person)-[:DRIVES]->(resource:Car)\"}}", "status": "ACTIVE", "tags": [] } ``` ## Step 3: Ask for the decision The application calls the evaluation endpoint with its AppAgent credential. No user token is needed: the subject is identified by `subject.type` and `subject.id`, which are the node's type and `external_id`. ```bash curl -X POST https://eu.api.indykite.com/access/v1/evaluation \ -H "X-IK-ClientKey: $CLIENT_KEY" \ -H "Content-Type: application/json" \ -d '{ "subject": { "type": "Person", "id": "knightrider" }, "resource": { "type": "Car", "id": "kitt" }, "action": { "name": "CAN_DRIVE" } }' ``` ## Step 4: Read the response ```json { "decision": true } ``` The same request for `"id": "cadillacv16"` returns `{"decision": false}`: knightrider has no DRIVES relationship with that car. A denial carries nothing else unless a policy filter attached advice (see [advice](#advice)). # Endpoint reference All endpoints are under `https://eu.api.indykite.com` or `https://us.api.indykite.com`, take `Content-Type: application/json`, and authenticate with `X-IK-ClientKey`. `Authorization: Bearer` and `X-IK-Token` are optional everywhere (see [Tokens](#credentials-and-tokens)). | Endpoint | Question | Answer | | --- | --- | --- | | `POST /access/v1/evaluation` | May this subject perform this action on this resource? | `decision` (boolean) | | `POST /access/v1/evaluations` | Several such questions in one call | One `decision` per question, in order | | `POST /access/v1/search/subject` | Which subjects of a type may perform this action on this resource? | List of subjects | | `POST /access/v1/search/resource` | On which resources of a type may this subject perform this action? | List of resources | | `POST /access/v1/search/action` | Which actions may this subject perform on this resource? | List of action names | | `GET /access/v1/policies` | Which active KBAC policies does my project have? | The policies as stored, with their tags | ## POST /access/v1/evaluation ```json { "subject": { "type": "", "id": "" }, "resource": { "type": "", "id": "" }, "action": { "name": "" }, "context": { "input_params": { "": }, "policy_tags": [ "" ] } } ``` | Field | Required | Rules | | --- | --- | --- | | `subject.type`, `resource.type` | yes | A node type: 2 to 64 characters, a letter or underscore followed by letters, digits or underscores. Selects the policies whose `subject.type` and `resource.type` match. | | `subject.id`, `resource.id` | yes | The node's `external_id`: 1 to 256 characters. | | `action.name` | yes | 2 to 50 characters from letters, digits, `.`, `:`, `_` and `/`; no hyphen. Selects the policies whose `actions` list contains it, compared exactly and case-sensitively. It is not looked up in the graph. | | `context.input_params` | when a policy reads `$name` | Keys: 2 to 20 characters, a letter followed by letters, digits or underscores. String values: 1 to 256 characters. Numbers, booleans, arrays and objects are accepted. Every selected policy must find every parameter it references. | | `context.policy_tags` | no | Each tag 1 to 20 alphanumeric characters. When present, only policies carrying at least one of the tags are evaluated; policies without tags are left out. | Other fields, including `subject.properties`, other keys under `context`, and `options`, are ignored without an error. **Response.** Allowed: ```json { "decision": true } ``` Denied, when a policy's graph pattern matched but its filter attached advice: ```json { "decision": false, "context": { "advice": [ { "error": "insufficient_user_authentication", "error_description": "Authentication is missing or expired", "sub": "$token.exp" } ] } } ``` Denied without advice is `{"decision": false}`. `context` is absent when there is nothing to report. The single evaluation never returns a `reason`: anything that prevents a decision is an HTTP error (see [Errors](#errors)). ## POST /access/v1/evaluations Several evaluations in one call, which saves a round trip per question when one subject is checked against many resources or one resource against many actions. Top-level `subject`, `resource`, `action` and `context` are defaults; each entry of `evaluations` supplies what differs. ```json { "subject": { "type": "Person", "id": "karel" }, "action": { "name": "CAN_DRIVE" }, "evaluations": [ { "subject": { "type": "Person", "id": "knightrider" }, "resource": { "type": "Car", "id": "kitt" } }, { "subject": { "type": "Person", "id": "knightrider" }, "resource": { "type": "Car", "id": "cadillacv16" } }, { "resource": { "type": "Bus", "id": "harmonika" }, "action": { "name": "CAN_RIDE" } }, { "resource": { "type": "Bus", "id": "harmonika" } } ] } ``` ```json { "evaluations": [ { "decision": true }, { "decision": false }, { "decision": true }, { "decision": false } ] } ``` Rules: - **A default is replaced, not merged.** An entry that sets `context` uses only its own `input_params` and `policy_tags`; the default context is not consulted for that entry. The same holds for `subject`, `resource` and `action`. In the example, the third entry keeps the default subject karel and overrides the action; the fourth keeps both defaults and asks whether karel may drive a bus, which no policy grants. - **Results come back in request order**, one per entry, each with the same shape as a single evaluation response. - **One failing entry does not fail the call.** The call returns `200`; the entry gets `"decision": false` and `context.reason` explains it, for example `"reason": "invalid_argument: missing or wrong input params, 'max_price'"`. The same situations are HTTP errors on the single endpoint. - **Field validation still applies to the merged entries.** An entry whose merged subject, resource or action is missing or malformed is refused for the whole call with `400` and the field messages listed under `errors`. ## The three search endpoints A search leaves one side of the question open and returns every graph node, or every action, that would make the decision `true`. The open side gives only a `type`. Results are deduplicated and there is no paging. | Endpoint | Request body | Response | | --- | --- | --- | | `POST /access/v1/search/subject` | `subject.type`, `action.name`, `resource.type`, `resource.id`, optional `context` | `{"results": [{"type": "...", "id": "..."}]}` | | `POST /access/v1/search/resource` | `subject.type`, `subject.id`, `action.name`, `resource.type`, optional `context` | `{"results": [{"type": "...", "id": "..."}]}` | | `POST /access/v1/search/action` | `subject.type`, `subject.id`, `resource.type`, `resource.id`, optional `context` | `{"results": [{"name": "..."}]}` | The three searches on the example graph, all with `X-IK-ClientKey` only. "Who may drive kitt?": ```json POST /access/v1/search/subject { "subject": { "type": "Person" }, "action": { "name": "CAN_DRIVE" }, "resource": { "type": "Car", "id": "kitt" } } ``` ```json { "results": [ { "type": "Person", "id": "knightrider" } ] } ``` "Which cars may knightrider drive?": ```json POST /access/v1/search/resource { "subject": { "type": "Person", "id": "knightrider" }, "action": { "name": "CAN_DRIVE" }, "resource": { "type": "Car" } } ``` ```json { "results": [ { "type": "Car", "id": "kitt" } ] } ``` "What may knightrider do with kitt?": ```json POST /access/v1/search/action { "subject": { "type": "Person", "id": "knightrider" }, "resource": { "type": "Car", "id": "kitt" } } ``` ```json { "results": [ { "name": "CAN_DRIVE" } ] } ``` Only the CAN_DRIVE policy exists at this point, so the action search returns one name. With input parameters, add `context.input_params` to any of the three bodies exactly as on the evaluation (resource [authz-4](/resources/authz-4) does this for a resource and a subject search). Two differences from the evaluation: - **Subject search uses no tokens and no filter.** The user token and the delegation token are not read, and a policy's `condition.filter` is not evaluated. A policy whose filter or Cypher reads a token claim therefore matches no subject in this search; resource and action searches do evaluate the filter and bind the claims. - **An empty result is not an error.** No matching policy, or no matching node, gives `{"results": []}`. Full examples: resource [authz-1](/resources/authz-1). ## GET /access/v1/policies An application agent can list the active KBAC policies of its own project at runtime, for example to show an administrator which rules apply, to pick `policy_tags`, or to let an agent discover which actions and resource types exist for a subject type. The agent needs the `ReadAuthZConfigs` API permission, which is separate from `Authorization` and is not granted to existing agents automatically (see the [Environment guide](/guides/guide-environment)). ```bash curl https://eu.api.indykite.com/access/v1/policies?subject_type=Person \ -H "X-IK-ClientKey: $CLIENT_KEY" ``` ```json { "results": [ { "policy": { "meta": { "policy_version": "2.0-kbac" }, "subject": { "type": "Person" }, "actions": [ "CAN_DRIVE" ], "resource": { "type": "Car" }, "condition": { "cypher": "MATCH (subject:Person)-[:DRIVES]->(resource:Car)" } }, "tags": [] }, { "policy": { "meta": { "policy_version": "2.0-kbac" }, "subject": { "type": "Person" }, "actions": [ "CAN_RIDE" ], "resource": { "type": "Bus" }, "condition": { "cypher": "MATCH (subject)-[:HAS]->(ticket:Ticket)-[:FOR]->(resource)" } }, "tags": [] } ] } ``` - `subject_type` (optional query parameter, a valid node type of 2 to 64 characters) keeps only the policies with that `subject.type`. Omitted: every policy. A type no policy uses returns `{"results": []}`; a value that is not a valid node type is refused with `422`. - `results[].policy` is the `policy` string sent to the Config API, parsed into an object, exactly as authored (including `filter` when present). `results[].tags` are the values matched by `context.policy_tags`; `[]` when the policy has none. - Only KBAC policies with status `ACTIVE`, only the calling agent's project. ContX IQ policies are not listed. Policy IDs, names and timestamps are not returned; use the Config API to manage a policy. - A user token or delegation token sent on this call is still validated and can fail with `401`; it has no other effect. Full example: resource [authz-9](/resources/authz-9). # Credentials and tokens | Header | Required | Effect | | --- | --- | --- | | `X-IK-ClientKey` | always | The AppAgent credential. `Authorization` permission for decisions and searches, `ReadAuthZConfigs` for the policy listing. | | `Authorization: Bearer ` | optional | Validated by Token Introspect. Its claims become `$token.` in policies. On `2.0-kbac` the subject must also be the token's identity, otherwise the decision is `false` without an error. On `3.0-kbac` the token's subject must equal `subject.type` and `subject.id`, otherwise `403`. Not read by the subject search. | | `X-IK-Token: ` | optional | Raw token, no `Bearer` prefix. Validated by Token Introspect like the user token. Its claims become `$ik_token.`. Does not require a user token. When a user token with a `sub` claim is also present, both `sub` claims must be equal. | To see which `subject.type` and `subject.id` a user token resolves to, call `GET /contx-iq/v1/whoami` (see the [ContX IQ guide](/guides/guide-contx-iq#whoami)). The subject is the same for both APIs. The delegation token carries the chain of agents acting for the user: `$ik_token.sub` is the user, `$ik_token.act.sub` the agent that made this call, `$ik_token.act.act.sub` the one before it, and so on. The Token Service sets a `type` on the link it adds (`Agent` unless configured otherwise) and keeps the links of the incoming token unchanged. A policy reads the chain through `$ik_token.act...` in its filter or its Cypher. For a check of the whole chain the platform also derives two lists from the nested `act` claims, oldest hop first: `$ik_token.act_chain`, the `sub` of every hop, and `$ik_token.act_chain_types`, the `type` of every hop, `null` for a hop without one. They are bound as Cypher parameters only and never taken from `input_params`; see [Token claims in the Cypher condition](#token-claims-in-the-cypher-condition). # How a decision is computed 1. **Policies are selected** by exact match of `subject.type`, `resource.type` and `action.name` against each active policy's `subject.type`, `resource.type` and `actions`, and by `policy_tags` when sent. No policy selected: `{"decision": false}`, not an error. 2. **Input parameters are bound.** Every selected policy must find every `$name` its Cypher references in `context.input_params`, even if another policy would already allow. A missing one fails the request with `422` and `missing or wrong input params, ''` (several names are comma-separated). 3. **Each policy's Cypher condition runs** with `subject` and `resource` bound to the requested nodes. The condition holds when the pattern matches. 4. **Its filter runs**, if the policy has one and the Cypher condition held. The filter is evaluated without the graph, against input parameters and token claims. 5. **Any policy that holds makes the decision `true`.** KBAC has no deny rule: a policy can only allow, and a filter can only stop its own policy from allowing. Advice is returned only when the decision is `false`. An error inside any selected policy, such as a missing parameter or a runtime failure, fails the whole decision on the single endpoint and marks that entry with a `reason` in a batch. ## Advice A filter leaf may carry an `advice` object: a free map of string keys and values written by the policy author. When that leaf fails, the graph condition had matched, and no other policy allows, the map is returned under `context.advice`. There is no fixed set of keys; `error` and `error_description` are a convention borrowed from OAuth. This policy denies a service action on a laptop when the user token is older than a moment fixed in the policy, and says why: ```json { "meta": { "policy_version": "2.0-kbac" }, "subject": { "type": "Token" }, "actions": [ "CAN_SERVICE" ], "resource": { "type": "Laptop" }, "condition": { "cypher": "MATCH (subject:Token)-[:_SAME_AS]->(person:Person)-[:OWNS]->(resource)", "filter": { "attribute": "$token.exp", "operator": ">", "value": 1767225600, "advice": { "error": "insufficient_user_authentication", "error_description": "Authentication is missing or expired", "sub": "$token.exp" } } } } ``` Full example: resource [authz-3](/resources/authz-3). With `AND`, the advice of every failing operand is returned; with `OR`, none is returned when one operand succeeds. # KBAC policy reference The policy JSON is the same for both versions; only `meta.policy_version` and the rules below differ. The [Cypher guide](/guides/guide-ciq-cypher) covers how to write the pattern; the [Data Residency guide](/guides/guide-data-residency) covers routing on a composite IKG. ```json { "meta": { "policy_version": "2.0-kbac | 3.0-kbac" }, "subject": { "type": "" }, "actions": [ "" ], "resource": { "type": "" }, "condition": { "cypher": "", "filter": { "operator": "", "attribute": "<$token.claim | $ik_token.path | $param>", "value": , "operands": [], "advice": { "": "" } } } } ``` ## 2.0-kbac and 3.0-kbac | Aspect | `2.0-kbac` | `3.0-kbac` | | --- | --- | --- | | Node labels | The subject must be an identity node; the platform matches `subject` as an identity node of the subject type and every other node pattern as an ingested node. A subject ingested without `is_identity: true` never matches, so the decision is `false` with no error. | The Cypher runs as written; the platform only pins `subject` and `resource` by type and external_id. A node pattern without a label matches any node, including property and trust score nodes. `is_identity` is not required. | | User token | Optional. When sent, the subject must be the token's identity; otherwise `false`. | Optional. When sent, its subject must equal the requested `subject`; otherwise `403` with `bearer token subject differs from requested subject` (evaluation, evaluations, resource and action search). | | `USE graph.byName(...)` and `CALL { }` | Rejected at creation: `USE clause is not allowed`, `CALL { } subquery is not allowed`. | Allowed. Only a `USE` clause needs a composite IKG; a `3.0-kbac` policy without one runs on the default database. A top-level `RETURN` is still rejected. | | Resolver-backed (external) properties in the condition | Allowed. | Rejected at creation: `invalid policy config: external properties cannot be used in data-residency policies`. | | `$subject_id` | May be referenced, but then counts as an input parameter the request must supply. | Rejected at creation: `invalid policy config: parameter "$subject_id" is reserved and cannot be referenced`. | | Platform-bound parameters `$subject_external_id`, `$subject_type`, `$resource_external_id`, `$resource_type` | Bound by the platform. Do not reference them: a policy that does turns them into required input parameters. | Reserved: referencing them is rejected at creation. | A `2.0-kbac` condition is accepted as a `3.0-kbac` condition when it uses none of the rejected items, but it can decide differently: the labels the platform no longer adds, and the token check that becomes an error, are behaviour changes, not just schema changes. Policies with the older `1.0-kbac` version keep working and appear in the listing; this guide does not describe them. ## condition.filter A boolean tree evaluated without the graph, after the Cypher condition held. Attributes are token claims or input parameters; the graph is not visible to it. | Element | Rule | | --- | --- | | `operator` | `AND`, `OR` (two or more `operands`; one gives `invalid field operands: len is 1 and should be >= 2`), `NOT` (exactly one operand), `=`, `<>`, `<`, `<=`, `>`, `>=`, `IN`, `=~`, `STARTS WITH`, `ENDS WITH`, `CONTAINS`, `IS NULL`, `IS NOT NULL`. `operands` only with `AND`, `OR`, `NOT`. | | `attribute` | Required on a leaf, a string: `$token.`, `$ik_token.` (dot paths walk the `act` chain, e.g. `$ik_token.act.act.sub`), `$name` or `$name.path` for an input parameter. | | `value` | Required for every comparison, must be absent for `IS NULL` and `IS NOT NULL`. A literal, a `$` reference as above, an array for `IN`, or a typed object `{"type": "datetime", "value": ""}`. | | `CONTAINS` | The attribute is a whitespace-separated list that contains the value as one of its items, as in an OAuth `scope` claim. Comma-separated lists and case differences do not match; a non-string attribute gives `false`. This differs from Cypher's substring `CONTAINS`. | | `IS NULL` | True for a token claim that is absent, including when the token itself was not sent. A referenced input parameter must exist; `IS NULL` is true when its value is `null`. | | `advice` | A map of string keys and values on a leaf; returned as described under [Advice](#advice). | | Unknown fields | Rejected at creation. | Example, a read that also requires the `cars.read` scope in the user token (resource [authz-6](/resources/authz-6)): ```json "condition": { "cypher": "MATCH (subject:Person)-[:DRIVES]->(resource:Car)", "filter": { "operator": "CONTAINS", "attribute": "$token.scope", "value": "cars.read" } } ``` ## Token claims in the Cypher condition The same claim sets are bound as Cypher parameters, so the pattern itself can compare graph data with a claim: `$token.` and `$ik_token.`, on both versions and on every endpoint except the subject search. ```json { "meta": { "policy_version": "2.0-kbac" }, "subject": { "type": "Person" }, "actions": [ "CAN_DRIVE" ], "resource": { "type": "Car" }, "condition": { "cypher": "MATCH (subject:Person)-[:OWNS]->(resource:Car) WHERE resource.delegated_to = $ik_token.act.sub AND resource.driver = $token.sub" } } ``` A policy can also demand that the delegation chain equals a path in the graph. The lists `$ik_token.act_chain` and `$ik_token.act_chain_types` hold every hop in order, so a variable-length pattern compared with them allows exactly the chain that the graph permits: ```json { "meta": { "policy_version": "2.0-kbac" }, "subject": { "type": "Person" }, "actions": [ "CAN_INVOKE" ], "resource": { "type": "Agent" }, "condition": { "cypher": "MATCH (subject:Person)-[rels:INVOKES*]->(resource:Agent) WHERE [r IN rels | endNode(r).external_id] = $ik_token.act_chain AND [r IN rels | endNode(r).type] = $ik_token.act_chain_types" } } ``` With a graph path karel INVOKES orchestrator INVOKES retriever and a token whose chain is `[orchestrator, retriever]` of types `[Agent, Agent]`, karel CAN_INVOKE retriever is `true`. The same token for orchestrator is `false`, the chain being longer than the path; a token with the hops reversed is `false`; a token whose hops carry no `type` claim yields `[null, null]` and never equals the path's types. The resource search returns, for that token, retriever only. - `token` and `ik_token` are reserved names. They are never input parameters: the platform binds them from the request's tokens and replaces anything the caller sends under those names. - `act_chain` and `act_chain_types` are derived from the token too: an `input_params.act_chain` sent by the caller changes nothing. - A token that was not sent binds an empty claim set. A comparison such as `= $ik_token.act.sub` is then false and the decision is `false`, not an error; `$ik_token.act.sub IS NULL` is true. - Only the exact names are reserved. A misspelt `$iktoken.act.sub` is an ordinary input parameter, refused with `422` and `missing or wrong input params, 'iktoken'`. - A claim cannot route a query: `USE graph.byName($token.region)` is rejected at creation (see below). ## Location routing (3.0-kbac on a composite IKG) A `3.0-kbac` policy may start with `USE graph.byName(...)`, either a string literal or a single parameter such as `$region`. The request supplies the logical location, a key of the project's `alias_mapping`, as an ordinary input parameter: ```json { "subject": { "type": "Person", "id": "knightrider" }, "resource": { "type": "Car", "id": "kitt" }, "action": { "name": "CAN_DRIVE" }, "context": { "input_params": { "region": "east" } } } ``` This works identically on all decision and search endpoints. Rules and their exact messages: - The routing parameter is used nowhere else in the Cypher: `invalid policy config: parameter "$region" routes graph.byName() and cannot be referenced elsewhere`. - The argument is a literal or one bare parameter: `invalid policy config: graph.byName() argument must be a string literal or a single parameter`. This is also what `$token.region` gets. - It cannot be a platform-bound name: `invalid policy config: graph.byName() parameter "$subject_external_id" collides with a platform-bound parameter`, and for the claim sets `invalid policy config: graph.byName() cannot take "$token", the platform binds it to the token claims`. - At request time, `422`: `location parameter "$region" must be a non-empty string`; `unknown location "mars" for parameter "$region"`; `location parameter "$region" requires a composite database, but the app space has none configured`; and for a static `USE` without a composite IKG, `policy requires a composite database, but the app space has none configured`. Full examples: resources [authz-7](/resources/authz-7) and [authz-8](/resources/authz-8). # Errors | Status | Body and cause | | --- | --- | | 400 | `{"message": "Bad Request"}`: the body is not valid JSON. With `"errors": ["invalid field "]`: a field has the wrong JSON type. In a batch, an entry whose merged fields fail validation is reported here with the field messages. | | 401 | `{"message": "Missing or malformed AppAgent credential token in X-IK-ClientKey header"}` or `{"message": "Invalid AppAgent JWT in X-IK-ClientKey header"}`: the AppAgent credential. `{"message": "Invalid token in Authorization header"}` or `{"message": "Invalid token in X-IK-Token header"}`: that token is expired, not accepted by any Token Introspect configuration, sent with a `Bearer` prefix in `X-IK-Token`, or could not be introspected right now; in the last case a retry can succeed. `{"message": "Token in X-IK-Token header is missing the sub claim"}` and `{"message": "Token in X-IK-Token header carries a different sub than the subject token"}`: the two tokens are not about the same user. `{"message": "insufficient API access level for appAgent"}`: the agent lacks the permission the endpoint needs. | | 403 | `{"message": "Forbidden", "errors": ["bearer token subject differs from requested subject"]}`: a `3.0-kbac` policy was selected and the user token's subject is not the requested subject. | | 406 | `{"error": "Accept must be application/json or */*", ...}`: the `Accept` header excludes JSON. | | 415 | `{"error": "Content-Type must be application/json", ...}`: missing or other content type. | | 422 | `{"message": "Unprocessable Entity", "errors": [...]}`. Field validation: `missing field subject`, `missing field subject.type`, `invalid field subject.type: "A" does not meet rule min=2`, `invalid field subject.type: does not match regex "^[a-zA-Z_]\w+$"`, `invalid field context.input_params[key]: string "..." must not be shorter than 1 and longer than 256 characters`. Decision time: `missing or wrong input params, ''` and the location messages above. | | 503 | `{"message": "Unable to verify the AppAgent credential token, retry the request"}`: the AppAgent credential could not be checked right now. Retry with the same credential. | # What is IndyKite-specific compared to the AuthZEN specification - Additional inputs go under `context.input_params` and `context.policy_tags`; no other `context` key is read. - `subject.properties`, `resource.properties`, `action.properties` and `options` (including `evaluations_semantic`) are accepted and ignored. Every batch entry is evaluated; there is no short-circuit semantic. - `subject.id` and `resource.id` are node external_ids, `subject.type` and `resource.type` are node types, and `action.name` is matched against policy action lists, never against the graph. - The searches return complete, deduplicated result lists without paging, and the subject search evaluates no tokens and no filter. - The response adds `context.advice` (policy-authored maps) and, in batches, `context.reason`. - Credentials are IndyKite headers: `X-IK-ClientKey`, optional `Authorization: Bearer`, optional `X-IK-Token`. # Related - Resources: [authz-1](/resources/authz-1) (evaluation and the three searches), [authz-2](/resources/authz-2) (batch), [authz-3](/resources/authz-3) (advice), [authz-4](/resources/authz-4) (input parameters), [authz-5](/resources/authz-5) (permission grid), [authz-6](/resources/authz-6) (token scope), [authz-7](/resources/authz-7) and [authz-8](/resources/authz-8) (3.0-kbac), [authz-9](/resources/authz-9) (policy listing). - Guides: [Dynamic Authorization](/guides/guide-dynamic-authz), [Cypher for policies](/guides/guide-ciq-cypher), [Data Residency](/guides/guide-data-residency), [Token Introspect](/guides/guide-token-introspect), [Token Service](/guides/guide-token-service), [Credentials](/guides/guide-credentials). - OpenID AuthZEN specification: [https://openid.net/wg/authzen/](https://openid.net/wg/authzen/) --- Source: https://developer.indykite.com/guides/guide-authzen --- # Cypher for ContX IQ: Policy and Knowledge Query Patterns > How to write the Cypher used in CIQ policies and Knowledge Queries - the Neo4j-adapted dialect, its rules, and worked examples. **Category:** ContX IQ ## Summary A practical, agent-friendly reference for the Cypher dialect inside CIQ policy condition.cypher: what is supported, how it differs from standard Neo4j Cypher, how Cypher variables bind to a Knowledge Query, and copy-paste examples from simple reads to aggregation. ## Content # What is Cypher in ContX IQ? **Cypher** is the graph pattern-matching language created for Neo4j. ContX IQ (CIQ) embeds a **Neo4j-adapted subset** of Cypher inside a policy's `condition.cypher` field. You use it to describe **the contextual subgraph** a request is allowed to touch: which nodes, which relationships, and how they connect. The most important idea to internalize: in CIQ, Cypher only **matches** context. It does **not** return, create, or delete data. Reads, writes, and deletes are declared separately in the **Knowledge Query** and gated by the policy's `allowed_reads`, `allowed_upserts`, and `allowed_deletes`. Cypher names the pieces; the Knowledge Query decides what to do with them. ![](/assets/images/SubGraphXYZ.png) **Schema example** This guide assumes you already know the CIQ component model (Policy → Knowledge Query → Execution). If not, read [ContX IQ: Context-Aware Data Queries and Policies](/guides/guide-contx-iq) first. For a gentle introduction to graph traversal and Cypher basics, see [Why use a Graph Database?](/guides/guide-graph-database) # Where do I write Cypher? Cypher lives in exactly one place: the `condition.cypher` string of a policy. ```json { "meta": { "policy_version": "1.0-ciq" }, "subject": { "type": "Person" }, "condition": { "cypher": "MATCH (subject:Person)-[r:LIKES]->(track:Track)", "filter": [ ... ] }, "allowed_reads": { "nodes": ["track.property.title"], "relationships": ["r"] } } ``` The **Knowledge Query** then references the variables you named in the Cypher (`subject`, `track`, `r`) - it never re-declares the pattern. # Which policy version does this cover? Everything in this guide targets CIQ **v1** - `policy_version: "1.0-ciq"`, set in the policy's `meta`. This is the default dialect. A **v2** dialect, `policy_version: "2.0-ciq"`, is available too, chosen per policy; its differences are listed under [CIQ v2 in the ContX IQ guide](/guides/guide-contx-iq#ciq-v2). v2 is **not a new query language**. The external API and authentication, the full [filter operator set and value types](#what-can-a-filter-express), every Cypher construct in this guide (`MATCH` / `OPTIONAL MATCH` / `WHERE` / `WITH`, aggregates, variable-length paths, inline `$param`s, `trust_score` and `_Application` handling), and the syntax of Knowledge Queries and execute requests are the **same** as on v1. **The Cypher of every example in this guide is valid on both versions; their filters need the `@` conversion described below.** v2 changes little, in three areas. First, **stricter validation when a policy is created** - it rejects two patterns that v1 quietly accepted: - **No references to anonymous nodes.** Any node referenced from a `filter`, an `allowed_*` list, or the Knowledge Query must be named in the Cypher. Referencing an unnamed node - e.g. the `(:Track)` in `MATCH (subject:Person)-[:LIKES]->(:Track)` - is rejected; write `(track:Track)`. (A node always needs a label in both versions; v2 additionally forbids *referencing* an unnamed one.) - **No untyped relationships in writes or deletes.** A relationship feeding `allowed_upserts` or `allowed_deletes` must declare its type in the Cypher (`[r:PLAYED_AT]`, not bare `[r]`). An untyped relationship is still fine when used only in reads. Both rules are good practice on v1 too, so the Cypher in this guide already satisfies them. Second, **filter attributes carry the `@` prefix**. In a v2 policy's `condition.filter` and in a Knowledge Query's `filter`, an `attribute` that names a variable is written as an [@ reference](#what-can-a-filter-express): `"attribute": "@subject.external_id"`. A bare `"subject.external_id"` is a literal string and matches nothing, so a query bound to the caller returns no rows. Moving a v1 policy to v2 therefore means adding `@` to every such attribute, in the policy and in each of its Knowledge Queries. Token references (`$token.*`, `$ik_token.*`) and input parameters (`$name`) stay as they are, and an `@` reference on the `value` side works in both versions. Third, **a whole relationship in a result**, a relationship variable on its own such as `owns`, comes back as its two endpoints and its properties instead of the database driver object; `owns.` and `owns.*` are unchanged. The [ContX IQ guide](/guides/guide-contx-iq#ciq-v2) lists the exact shapes and the other differences. The two dialects coexist in one project: each policy names its own version. # How is CIQ Cypher different from standard Neo4j Cypher? CIQ Cypher is the **read/traverse core** of Cypher, with the result and mutation clauses removed and replaced by declarative JSON. Keep these adaptations in mind: | Standard Cypher | In CIQ | | --- | --- | | `RETURN` chooses output | No `RETURN`. Output is chosen by the Knowledge Query's `nodes`, `relationships`, and `aggregate_values` - and must be allow-listed in policy `allowed_reads`. | | `CREATE` / `MERGE` / `SET` | Not written in Cypher. Declared in the Knowledge Query's `upsert_nodes` / `upsert_relationships`, gated by policy `allowed_upserts`. | | `DELETE` / `REMOVE` | Not written in Cypher. Declared in the Knowledge Query's `delete_nodes` / `delete_relationships`, gated by policy `allowed_deletes`. | | Any node can be a starting point | Exactly one node must be the **subject** - the variable named `subject`, with a label matching `subject.type`. A policy has a single subject type. | | Anonymous nodes are common | Any node or relationship you reference later **must be named** (give it a variable). Anonymous parts can only be used as connective glue. | | Parameters are `$x` bound by the driver | Parameters are `$x` placeholders resolved at execution from `input_params`. `$token.*` (token claims) and `$_appId` (application identity) are reserved. `$ik_token.*` (claims of the delegation token sent in `X-IK-Token`, e.g. `$ik_token.act.sub`) is reserved the same way; the platform binds both claim sets, ignores caller values sent under `token` or `ik_token`, and binds an empty set for a token that did not arrive, so a comparison against it is `null` and matches nothing. | | Filtering via `WHERE` | Inline `WHERE` works, but execution-time parameters and token claims are best expressed in the structured `filter` array (see below). | # What Cypher syntax is supported? CIQ supports the pattern-matching and projection core. Treat this as the practical surface; validate edge cases by creating the policy through the Config API (it rejects unsupported or invalid constructs). | Feature | Example | | --- | --- | | `MATCH` | `MATCH (subject:Person)-[r:LIKES]->(track:Track)` | | `OPTIONAL MATCH` | `OPTIONAL MATCH (subject)-[:CREATED]->(p:Playlist)` | | Multiple comma / multi-clause patterns (cartesian + join) | `MATCH (subject:Person), (venue:Venue)` | | `WHERE` with comparisons and boolean logic | `WHERE subject.property.karaoke_confidence >= venue.property.min_confidence` | | `WITH` (projection / pipelining; exposes aggregates) | `WITH subject, COLLECT(track.external_id) AS liked` | | Relationship direction | `-[r]->` outgoing, `<-[r]-` incoming, `-[r]-` either | | Relationship type and alternation | `[:SUBSCRIBED_TO\|CREATED]` | | Variable-length paths (bound the depth - see the timeout note) | `[rels:INVOKES*1..5]`, `[:MEMBER_OF*1..3]` | | Inline property maps | `(venue:Venue {name: $venue_name})`, `(cp:Property {type:'role'})` | | Multiple labels and re-using a bound variable | `(n:Label1:Label2)`; close a loop with an already-bound name, e.g. `...<-[:CREATED]-(subject)` | | Aggregate functions | `COUNT(...)`, `COUNT(DISTINCT ...)`, `COLLECT(...)`, `SUM` / `AVG` / `MIN` / `MAX` | | Predicate & list functions | `ALL` / `ANY` / `NONE`, list comprehension `[r IN rels \| endNode(r).external_id]`, `endNode()` / `startNode()` | # How do Cypher variables flow into a Knowledge Query? The variable names in `condition.cypher` are the contract between the policy and everything downstream. A name you bind in Cypher becomes the handle used by: - **Policy `allowed_reads` / `allowed_upserts` / `allowed_deletes`** - the allow-list of what may be read, written, or removed. - **Knowledge Query `nodes` / `relationships` / `aggregate_values`** - what this query actually returns. - **Knowledge Query `upsert_*` / `delete_*`** - the variables to mutate. A read variable must be allow-listed in the policy **and** requested in the query. If the Cypher binds `track` but `allowed_reads.nodes` omits it, the query cannot return it. ### What attribute naming conventions are used? | Pattern | Description | Example | | --- | --- | --- | | `.property.` | A property value on a node | `track.property.title` | | `.external_id` | The external id of a node or relationship | `subject.external_id` | | `.property..metadata.` | Metadata attached to a property | `ln.property.value.metadata.source` | | `.trust_score.` | A Trust Score signal on a node (see the [Trust Score](/guides/guide-trust-score) guide) | `subject.trust_score._final_score` | | `.*` / `.property.*` | Wildcard - all of a node's properties | `subject.*` | | `$token.` | A claim on the requestor's token | `$token.sub`, `$token.acr`, `$token.iat`, `$token.scope` | | `$` | An execution-time parameter from `input_params` | `$venue_name` | | `$_appId` | Reserved - auto-filled with the calling Application's `external_id` | `subject.external_id = $_appId` | # Worked examples (music dataset) Each example shows the policy `condition` (Cypher + filter), the matching Knowledge Query, and the execution `input_params`. They use the IndyKite music sandbox dataset (Artists, Tracks, Albums, Playlists, Venues, People). ## 1. Subject only - read your own profile The simplest pattern: match just the subject and pin it to the caller's token via a `filter`. No relationships needed. ```cypher MATCH (subject:Person) ``` ```json // policy condition "condition": { "cypher": "MATCH (subject:Person)", "filter": [ { "operator": "=", "attribute": "subject.external_id", "value": "$token.sub" } ] } // knowledge query - read selected profile properties { "nodes": [ "subject.property.firstname", "subject.property.email", "subject.property.city" ], "relationships": [] } // execution - no params; identity comes from the token { "id": "kq-person-own-profile-read", "input_params": {} } ``` The `$token.sub` filter guarantees a Person can only ever resolve *their own* node, even though the Cypher matches the label generically. ## 2. One hop - a Person's liked tracks Name the relationship (`r`) so the query can both filter on the connected node and return the relationship. ```cypher MATCH (subject:Person)-[r:LIKES]->(track:Track) ``` ```json "condition": { "cypher": "MATCH (subject:Person)-[r:LIKES]->(track:Track)", "filter": [ { "operator": "AND", "operands": [ { "operator": "=", "attribute": "subject.external_id", "value": "$token.sub" }, { "operator": "=", "attribute": "track.external_id", "value": "$track_external_id" } ] } ] } // knowledge query { "nodes": [ "track.property.title", "track.property.popularity" ], "relationships": [ "r" ] } // execution { "id": "kq-person-liked-tracks-read", "input_params": { "track_external_id": "track-1" } } ``` ## 3. _Application subject with parameters When the subject is `_Application`, bind it and constrain it with `$_appId` (auto-filled). A second `MATCH` brings in the data graph; a named relationship (`r`) lets you read and later mutate it. ```cypher MATCH (subject:_Application) MATCH (track:Track)-[r:PLAYED_AT]->(venue:Venue) ``` ```json "condition": { "cypher": "MATCH (subject:_Application) MATCH (track:Track)-[r:PLAYED_AT]->(venue:Venue)", "filter": [ { "operator": "AND", "operands": [ { "attribute": "venue.property.name", "operator": "=", "value": "$venue_name" }, { "attribute": "subject.external_id", "operator": "=", "value": "$_appId" } ] } ] } // read query { "nodes": [ "track.property.title", "track.property.loudness", "track.property.energy" ], "relationships": [ "r" ] } // execution - X-IK-ClientKey only; $_appId is implicit, never sent { "id": "kq-app-venue-playable-tracks-read", "input_params": { "venue_name": "Shower-Concert-Hall" } } ``` ## 4. Writing and deleting reuse the same Cypher variables The same policy supports mutation Knowledge Queries - no new Cypher. To **create** a relationship, reference the node variables as `source`/`target`; to **delete**, reference the named relationship. The policy must allow these via `allowed_upserts` / `allowed_deletes`. ```json // upsert: link track -> venue with a new PLAYED_AT relationship (gated by allowed_upserts) { "upsert_relationships": [ { "name": "newPlayedAt", "source": "track", "target": "venue", "type": "PLAYED_AT" } ], "nodes": [ "track.external_id", "venue.external_id" ], "relationships": [ "newPlayedAt" ] } // delete: remove the matched PLAYED_AT relationship r (gated by allowed_deletes) { "delete_relationships": [ "r" ], "nodes": [ "track.external_id" ] } ``` Updating a node works the same way - reference the Cypher variable by `name` in `upsert_nodes` (e.g. set new properties on `subject` or `playlist`). Protected properties cannot be deleted: `_service`, `create_time`, `external_id`, `id`, `type`, `update_time`. **Identity nodes.** An `upsert_nodes` entry accepts an optional `is_identity` boolean (default `false`). Set `"is_identity": true` to upsert the node as an identity node - the same result as `is_identity: true` in the Capture API. Adding `"labels": ["DigitalTwin"]` to the entry is equivalent (the flag is shorthand for adding this label; combining both is harmless), but prefer the boolean - unlike a label, it cannot be mistyped. Mark the node whenever it must act as a `2.0-kbac` authorization subject: a non-identity subject makes every `2.0-kbac` decision silently `false` (`3.0-kbac` matches by type and external ID and does not need it). The label goes in `labels` only - never in the policy's `allowed_upserts.nodes.node_types` whitelist, which checks `type`. Label values are not validated, so a typo such as `Digitaltwin` is accepted silently and only surfaces when `2.0-kbac` decisions come back `false` - after creating, verify with a `2.0-kbac` evaluation that uses the new node as subject. Note that CIQ cannot bootstrap its own subject: the execute call authorizes against an existing subject node, so the first identity in a flow - the one the request runs as - must be ingested through the Capture API (`is_identity: true`). **What the write/delete returns.** The response shape depends on what the query *reads*, not on whether it writes or deletes. The examples above list read-back fields (`nodes` / `relationships`), so they return that data. A write or delete that lists **nothing** to read (empty `nodes`, `relationships`, `aggregate_values`) instead returns a single **count** of affected rows under the reserved `result` key: `{ "data": [ { "aggregate_values": { "result": 3 } } ] }`. To get the changed entities back, list them to read. This is the same in both versions. ## 5. Mixed direction and multi-hop Patterns can change direction mid-chain. Here the caller's playlist is reached outgoing (`CREATED`), and its tracks point *into* the playlist (`<-[pf:PART_OF]-`). ```cypher MATCH (subject:Person)-[r:CREATED]->(playlist:Playlist)<-[pf:PART_OF]-(track:Track) ``` ```json "filter": [ { "operator": "AND", "operands": [ { "operator": "=", "attribute": "subject.external_id", "value": "$token.sub" }, { "operator": "=", "attribute": "playlist.external_id", "value": "$playlist_external_id" } ] } ] // knowledge query - read the incoming relationship pf and track titles { "nodes": [ "playlist.property.name", "track.property.title", "track.external_id" ], "relationships": [ "pf" ] } // execution { "id": "kq-person-playlist-tracks-read", "input_params": { "playlist_external_id": "playlist-100" } } ``` ## 6. Relationship alternation and undirected hops A relationship segment can match **any of several types** (alternation with `|`) and can be **undirected** (`-[...]-`, matching either direction). This policy lets a Person read playlists created by a family member, where "family" is any of three relationship types in either direction. ```cypher MATCH (subject:Person)-[:MARRIED_TO|PARTNERS|PARENT_OF]-(family:Person)-[:CREATED]->(playlist:Playlist) ``` ```json "condition": { "cypher": "MATCH (subject:Person)-[:MARRIED_TO|PARTNERS|PARENT_OF]-(family:Person)-[:CREATED]->(playlist:Playlist)", "filter": [ { "operator": "=", "attribute": "subject.external_id", "value": "$token.sub" } ] } // knowledge query { "nodes": [ "family.property.firstname", "playlist.property.name", "playlist.property.mood" ], "relationships": [] } // execution - identity comes from the token, no params { "id": "kq-person-family-playlists", "input_params": {} } ``` An inline `WHERE` is also fine for static thresholds, e.g. `... WHERE subject.property.karaoke_confidence >= 0.8`. ## 7. Aggregation with WITH and aggregate_values Use `WITH` to project aggregates, then expose them via the Knowledge Query's `aggregate_values`. This _Application policy walks a variable-length `INVOKES` chain from a workflow to a target agent (anchored by the agent's indexed `external_id`) and collects the agent ids. The depth is **bounded** (`*1..5`) so the traversal stays fast - see [Will my query time out?](#will-my-query-time-out) below. ```cypher MATCH (subject:_Application) MATCH (wf:Workflow)-[rels:INVOKES*1..5]->(a:Agent {external_id: $agent_id}) WHERE ALL(r IN rels WHERE r.workflow_name = wf.external_id AND endNode(r):Agent) WITH subject, wf.external_id AS workflow, [r IN rels | endNode(r).external_id] AS agent_list ``` ```json // the aliases created by WITH become the readable aggregates "allowed_reads": { "nodes": [], "relationships": [], "aggregate_values": [ "workflow", "agent_list" ] } // knowledge query returns only the aggregates { "aggregate_values": [ "workflow", "agent_list" ] } // execution { "id": "kq-agent-invocation-chain", "input_params": { "agent_id": "agent-42" } } ``` Whatever you alias in the final `WITH` (`... AS workflow`, `... AS agent_list`) is what `aggregate_values` can read - this is how aggregate results leave the query, since there is no `RETURN`. ## 8. OPTIONAL MATCH and counting `OPTIONAL MATCH` includes data that may or may not exist (it yields null rather than dropping the row), and chained `WITH` steps build several aggregates. This _Application policy reports, per venue, how many people will attend and how many playlists are approved. Note the identity is pinned in the `filter` here; you can equally pin it inline, e.g. `MATCH (subject:Person) WHERE subject.external_id = $token.sub`. ```cypher MATCH (subject:_Application) MATCH (venue:Venue) OPTIONAL MATCH (venue)<-[:WILL_ATTEND]-(attendee:Person) WITH subject, venue, COUNT(attendee) AS attendeeCount OPTIONAL MATCH (playlist:Playlist)-[:APPROVED_FOR]->(venue) WITH subject, venue, attendeeCount, COUNT(playlist) AS playlistCount ``` ```json "filter": [ { "operator": "AND", "operands": [ { "operator": "=", "attribute": "subject.external_id", "value": "$_appId" }, { "operator": "=", "attribute": "venue.property.name", "value": "$venue_name" } ] } ] // knowledge query - venue facts plus the two computed counts { "nodes": [ "venue.property.name", "venue.property.description" ], "aggregate_values": [ "attendeeCount", "playlistCount" ] } // execution { "id": "kq-app-venue-attendance-stats", "input_params": { "venue_name": "Shower-Concert-Hall" } } ``` # What can a filter express? A `filter` is a tree of conditions, used in the policy `condition` and, optionally, in the Knowledge Query. A **leaf** has an `attribute`, an `operator`, and (for most operators) a `value`. A **branch** uses `AND` / `OR` / `NOT` with nested `operands` and no `attribute`/`value`. ### Operators | Operator | Meaning | | --- | --- | | `AND` / `OR` | Combine nested `operands` (2 or more). | | `NOT` | Negate a nested operand (at least one; only the first is used). | | `=` / `<>` | Equal / not equal. | | `>` / `<` / `>=` / `<=` | Numeric or datetime comparison. | | `IN` | Attribute is in the supplied array `value`. | | `=~` | Attribute matches a regular-expression `value`. | | `STARTS WITH` / `ENDS WITH` | String prefix / suffix match. | | `CONTAINS` | Substring match, as in Cypher. Only in a policy `token_filter` does `CONTAINS` mean membership in a whitespace-separated list (e.g. OAuth `scope`). | | `IS NULL` / `IS NOT NULL` | Attribute is absent/null or present/non-null. No `value`. | ### Value forms - **Raw scalar** - string, number, or boolean (e.g. `0.8`, `"Upbeat"`, `true`). - **Array** - for `IN` (e.g. `["track-1", "track-2"]`). - **`$param`** - an execution-time parameter supplied in `input_params` (string values 1-256 chars). - **`$token.`** - a claim from the caller's token (`$token.sub`, `$token.acr`, `$token.iat`, `$token.scope`, ...). - **`$_appId`** - reserved; the calling Application's `external_id`, auto-filled for `_Application` subjects. - **Typed value object** - `{ "type": "datetime", "value": "2026-01-15T00:00:00Z" }` or `{ "type": "datetime", "value": "$control_date" }`. `type` defaults to `any`; use `datetime` for RFC 3339 timestamps so comparisons are date-aware. - **`@reference`** - a reference to *another matched attribute, by name*, instead of a constant. This is how you compare one property to another (see below). **Escaping.** The leading `$` and `@` are special. To use a literal string that actually starts with one of them, escape it: `\$rawValue` or `\@user`. Branches nest arbitrarily (`AND` of `OR`s, etc.). A **`token_filter`** is a sibling of `filter` that only references `$token.*` values and can attach step-up `advice` (`error`, `error_description`) returned via the `Www-Authenticate` header when the token is insufficient. See the [ContX IQ guide](/guides/guide-contx-iq) for the full filter, typed-value, and `token_filter` schema. ### Comparing one property to another (`@` references) By default a filter compares an attribute to a *constant* (or a `$param` / `$token` value). To compare it to **another attribute matched by the Cypher** - a property-to-property comparison - prefix that operand with `@` and give the attribute's full name. It is the structured-filter equivalent of an inline `WHERE a.x <= b.y`. ```json // a Track may PLAY at a Venue only if its loudness is within the venue's limit // cypher: MATCH (subject:Track)-[r:PLAYED_AT]->(venue:Venue) { "attribute": "subject.property.loudness", "operator": "<=", "value": "@venue.property.max_loudness" } ``` The `@` name must resolve to a variable and attribute that the Cypher actually binds (any of the attribute forms above - `@venue.property.max_loudness`, `@other.external_id`, `@contract.trust_score._final_score`, `@subject.property.email.metadata.source`). **Version note.** Property-to-property comparison with `@` works in **both versions**; they differ only in which operand may hold the reference. In **v1**, only the `value` side may be an `@` reference (the `attribute` side is the property being tested). In **v2 (Beta)**, *both* the `attribute` and the `value` may be `@` references, so you can compare two referenced attributes directly. # Filter vs inline WHERE - which should I use? - **Use the `filter` array** for execution-time parameters (`$param`), token claims (`$token.*`), and the `$_appId` binding. It is the structured, validated way to express partial filters and supports nested `AND` / `OR` / `NOT`, typed values, and step-up `token_filter` advice. - **Use inline `WHERE`** for static, structural constraints inside the pattern - fixed thresholds, label predicates, list predicates (`ALL` / `ANY` / `NONE`), and relationship conditions that are part of the traversal logic. # Will my query time out? Execution enforces a per-query timeout. The default for read-only queries is **30 seconds**, tuned for fast, interactive queries; a read-only query that legitimately needs longer can set `batch_read: true` in the Knowledge Query to use the extended limit (5 minutes / 300 seconds - see [batch_read](/guides/guide-contx-iq)). The right fix is almost always to make the matched subgraph smaller, not to wait longer. - **Anchor on an indexed identity.** Constrain the subject with `subject.external_id = $token.sub` (users) or `$_appId` (applications), or pin a node by `external_id` (inline `{external_id: $x}` or a filter). Traversal then starts from one node instead of a full label scan. Examples 1-6 and 8 all do this. - **Bound every variable-length path.** Write `[:INVOKES*1..5]`, never a bare `[:INVOKES*]` - an unbounded `*` can traverse the whole graph and loop on cycles, the most common cause of timeouts. This is the only traversal cost in example 7, which is why it bounds the depth. - **Filter to specific entities, not whole labels.** Prefer `playlist.external_id = $playlist_external_id` or `venue.property.name = $venue_name` over matching every `Playlist` or `Venue`. When a pattern does start from a label (e.g. `MATCH (venue:Venue)` in example 8), make sure a filter narrows it before any expansion or aggregation. - **Aggregate over bounded subgraphs.** `COUNT` / `COLLECT` are cheap over one anchored entity's neighbours (example 8 counts a single venue's attendees). Aggregating across an entire label is what warrants `batch_read`. - **Page large result sets.** Use `page_size` and `page_token` on the execute call to fetch results in chunks rather than one oversized response. Every example in this guide is anchored and bounded, so each returns quickly on a realistically sized graph. Reach for `batch_read` only when a read is intentionally broad. One more lever, for a condition that is anchored and bounded yet still slow: the platform adds the `Resource` system label to every named node of your Cypher, and for some patterns that extra label steers the planner to a poor plan, typically a lookup on the `Resource` index that spans the whole graph where a scan of a small node type would have been cheaper. Setting `skip_resource_label` in the policy's `condition` leaves it out, so lookups use the node type's own indexes; results are unchanged. See [condition.skip_resource_label](/guides/guide-contx-iq#condition-skip-resource-label) in the ContX IQ guide. # Checklist: authoring a CIQ Cypher Before submitting a policy, verify each of these. Most rejections at create time trace back to one of them. - **Exactly one subject.** The pattern binds a node to the variable `subject`, and its label matches `subject.type`. One subject type per policy - need two? Write two policies. - **Name everything you reference.** Every node/relationship used in `filter`, `allowed_*`, or the Knowledge Query must have a Cypher variable. Anonymous nodes (e.g. `(:Track)`) can only connect the pattern. - **No `RETURN`, `CREATE`, `MERGE`, `SET`, or `DELETE` in the Cypher.** Results come from the Knowledge Query; mutations from `upsert_*` / `delete_*` gated by `allowed_*`. - **No `USE` clauses or `CALL { }` subqueries.** Database-routing and subquery syntax is rejected at create time for every CIQ policy version and for `2.0-kbac`: a `USE` clause fails with `USE clause is not allowed`, a `CALL { }` subquery with `CALL { } subquery is not allowed` (in KBAC policies the `CALL` keyword is caught by the token filter first: `Cypher contains forbidden clauses: [CALL]`). `use` remains valid as an ordinary variable, label, or property name. The one exception is the raw-Cypher `3.0-kbac` KBAC version, where `USE graph.byName(...)` and `CALL { }` subqueries (with inner `RETURN`s) are legal composite-database routing - see the [data residency guide](https://developer.indykite.com/guides/guide-data-residency). This does not apply to CIQ. - **Allow-list every read.** Each variable/attribute the query returns must appear in `allowed_reads` (and aggregates in `allowed_reads.aggregate_values`). - **Parameters line up.** Each `$x` used must be supplied in `input_params` at execution (string values 1-256 chars). Do *not* send `$_appId` for `_Application` subjects - it is auto-filled. Bind the identity (`subject.external_id = $token.sub` for users) so a query cannot resolve other people's data. - **Expose aggregates via `WITH ... AS alias`** and list the alias in `aggregate_values`. - **Type your relationships for writes.** If a named relationship feeds `allowed_upserts`/`allowed_deletes`, give it an explicit type in the Cypher (e.g. `[r:PLAYED_AT]`, not `[r]`). Required in v2, recommended in v1. - **System-managed elements are off-limits.** A Knowledge Query cannot create, update, or delete the reserved `_Application` identity node, and cannot create system-internal node types. Protected properties cannot be deleted: `_service`, `create_time`, `external_id`, `id`, `type`, `update_time`. - **Keep it inside the timeout.** Anchor on an indexed identity, bound variable-length paths (`*1..N`), and filter to specific entities so the matched subgraph stays small. Set `batch_read: true` only for intentionally large reads. See [Will my query time out?](#will-my-query-time-out) - **Validate by creating it.** Create the policy and query through the public REST Config API - `POST /configs/v1/authorization-policies` and `POST /configs/v1/knowledge-queries` (or use Terraform). The API rejects syntax and reference errors immediately. Full reference: [openapi.indykite.com](https://openapi.indykite.com/). # Quick recipe: from requirement to policy 1. **State the access in one sentence** - "an Application can read tracks playable at a named venue", or "a Person can view a family member's playlist". 2. **Pick the subject** - `Person` (user token) or `_Application` (service). This sets `subject.type` and the auth model. 3. **Draw the path** - write the `MATCH` from `subject` to the target, naming each node/relationship you will read or mutate; set directions (`->`, `<-`, `-`). 4. **Constrain it** - identity (`$token.sub` / `$_appId`) and selectors (`$param`) in the `filter` array; static thresholds inline in `WHERE`. 5. **Declare capabilities** - fill `allowed_reads` / `allowed_upserts` / `allowed_deletes` with the variables from step 3. 6. **Write the Knowledge Query** - choose `nodes` / `relationships` / `aggregate_values` to return, or `upsert_*` / `delete_*` to mutate. 7. **Execute** - `POST /contx-iq/v1/execute` with the query id/name and `input_params`. # Next Steps - CIQ component model and full policy/query/execution syntax: [ContX IQ: Context-Aware Data Queries and Policies](/guides/guide-contx-iq) - Cypher and graph traversal basics: [Why use a Graph Database?](/guides/guide-graph-database) - Fetch external data during a query: [External Data Resolver](/guides/guide-external-data-resolver) - Use trust signals in conditions: [Trust Score](/guides/guide-trust-score) - Author from your AI agent: [MCP Server](/guides/guide-mcp) · [IndyKite from your AI coding agent](/guides/guide-skills) - REST reference: [Config API](https://openapi.indykite.com/api-documentation-config) · [Runtime API](https://openapi.indykite.com/api-documentation) --- Source: https://developer.indykite.com/guides/guide-ciq-cypher --- # Config API conventions > The rules every Config API resource follows: authentication, identifiers, list filters, reads by name or version, ETags, update semantics, statuses and the error contract. **Category:** Environment ## Summary What is the same across every Config API resource, so a resource guide only has to describe its own fields. ## Content Every IndyKite configuration object, from a project down to an audit signing configuration, is managed through the **Config API** with the same handful of rules. The resource guides describe the fields of each object; this guide states, once, what they all share: how to authenticate, how lists, reads, creates, updates and deletes behave, how statuses work, and what every error looks like. # What is the Config API? The Config API is the REST interface for creating and managing configuration. It is served per region under `/configs/v1`: - **EU**: `https://eu.api.indykite.com/configs/v1` - **US**: `https://us.api.indykite.com/configs/v1` Reference: [Config REST API](https://openapi.indykite.com/api-documentation-config). Terraform calls the same API; the [Terraform guide](/guides/guide-terraform) maps its resources to these objects. ### How do I authenticate? Every call carries a **Service Account** token: `Authorization: Bearer `. It is the only credential the Config API accepts; a request without a `Bearer` token in `Authorization`, including one that sends an Application Agent credential only in `X-IK-ClientKey`, is refused with `401` and `Missing or malformed ServiceAccount credential token in Authorization header`; a Bearer token that is invalid, expired or revoked, or an Application Agent JWT sent as Bearer, with `Invalid ServiceAccount JWT in Authorization header`. What the account may do depends on its role: `all_editor` creates, updates and deletes, `all_viewer` reads and lists, and a write by a viewer gets `403`. How to obtain the token, and what to do when the platform answers `503` or `500` instead of judging it, is in the [Credentials guide](/guides/guide-credentials). ### Which headers and formats apply everywhere? - **Bodies are JSON.** `POST` and `PUT` require `Content-Type: application/json`; anything else is refused with `415`. - **Responses are JSON.** The request's `Accept` header must allow `application/json` (or `*/*`); a request without an `Accept` header, or with one that excludes JSON, is refused with `406`. Most HTTP clients send an acceptable default; curl does. - **Identifiers are GIDs**, strings with the `gid:` prefix: `id`, `organization_id`, `project_id`, `created_by`, `updated_by`. A GID encodes its type, so a project GID where an organization GID is expected is refused with `422` and `invalid field organization_id: identifier is not of ORGANIZATION`. - **Timestamps are RFC 3339 in UTC**, `2026-10-12T14:02:11Z`, without fractional seconds in responses. Where you send one, such as a credential's `expire_time`, any RFC 3339 offset is accepted. # Which resources does it manage? Every object has a parent that scopes it, named by the query parameter of its list and the field of its create request: | Path under /configs/v1 | Parent | Operations | | --- | --- | --- | | `/organizations/current` | none | Read only: the organization of the calling Service Account | | `/projects` | `organization_id` | List, create, read, update, delete | | `/service-accounts` | `organization_id` | List, create, read, update, delete | | `/service-account-credentials` | `organization_id` on list, `service_account_id` on create | List, create, read, delete. No update. | | `/applications` | `project_id` | List, create, read, update, delete | | `/application-agents` | `project_id` on list, `application_id` on create | List, create, read, update, delete | | `/application-agent-credentials` | `project_id` on list, `application_agent_id` on create | List, create, read, delete. No update. | | `/token-introspects` | `project_id` | List, create, read, update, delete | | `/authorization-policies` | `project_id` | List, create, read, update, delete | | `/knowledge-queries` | `project_id` | List, create, read, update, delete | | `/external-data-resolvers` | `project_id` | List, create, read, update, delete | | `/trust-score-profiles` | `project_id` | List, create, read, update, delete | | `/event-sinks` | `project_id` | List, create, read, update, delete | | `/entity-matching-pipelines` | `project_id` | List, create, read, update, delete | | `/mcp-servers` | `project_id` | List, create, read, update, delete | | `/audit-signings` | `project_id` | List, create, read, update, delete | The two credential resources differ from the rest in three ways: they have no `name` or `description`, they cannot be updated (issue a new one and delete the old), and their create response carries the credentials file, the only time the private key is returned. The [Credentials guide](/guides/guide-credentials) covers them. # How do lists work? `GET /configs/v1/?project_id=` (or `organization_id` for the three organization-level resources). The parent parameter is required. Two optional parameters apply to every list, and one to policies only: | Parameter | Effect | | --- | --- | | `search=` | Keeps only the objects whose name, display name or description contains the text. | | `full_fetch=true` | Returns every field of each object. Without it the list is metadata only: each item keeps its identifiers, names, timestamps, status and tags, but the heavy configuration fields come back empty, for example `policy` on an authorization policy, `query` on a Knowledge Query, `node_classification` on a Trust Score profile, or the provider details of an audit signing configuration. Read the object by `id` for the same result on one object. | | `type=kbac` or `type=ciq` | `/authorization-policies` only: keeps the policies of one kind. | The response is `{"data": [ … ]}`, each item in the shape of the read response below. There is no paging: a list returns every match in the parent. Lists carry no ETag. # How do reads work? `GET /configs/v1//{id}` returns the object and an `etag` response header. Three things apply to all of them: - **By GID or by name.** `{id}` accepts the object's `name` as well as its GID. A name is unique only within its parent, so a project-scoped object read by name needs `?project_id=`; without it the call fails with `422` and `project_id is required when querying by name`. (The older `location` parameter is deprecated and still accepted, but not together with `project_id`.) Projects and Service Accounts read by name are looked up in the calling account's organization, with no extra parameter. Credentials are read by GID only. - **By version.** Every update creates a new version. `?version=` (an integer from 1) returns that version; without it the latest is returned. Credentials and the organization have no versions. - **Secrets are write-only.** A password, a connection string, a provider credential: whatever you sent as a secret comes back as an empty string, or only as its key name, and a validation error about it masks the value as `********`. Keep your own copy. Every read response starts with the same fields, followed by the object's own: | Field | Meaning | | --- | --- | | `id` | The object's GID. | | `name` | Its URL-friendly identifier, unique within the parent and immutable. | | `display_name` | Human-readable name; equals `name` when never set. | | `description` | Optional text. | | `organization_id`, `project_id` | Where it lives. `project_id` is absent for an object created directly under the organization, such as a Service Account, and on a project itself. | | `create_time`, `created_by`, `update_time`, `updated_by` | When and by which Service Account (its GID) the object was created and last changed. | # How do creates work? `POST /configs/v1/` with the parent field, the common fields and the object's own. The common fields follow one rule set: | Field | Rule | | --- | --- | | `name` (required) | 2 to 63 characters of lowercase letters, digits and hyphens, starting with a letter and ending with a letter or digit. Unique within the parent, and immutable once created. Anything else is refused with `422` and `invalid field name: is not valid name, value must start with [a-z] followed by [-a-z0-9] and ends with [a-z0-9]`; a name already taken in the parent with `409`. | | `display_name` | Optional, 2 to 254 characters. | | `description` | Optional, 2 to 65000 characters. | | Parent field | `project_id`, `organization_id`, `application_id`, `application_agent_id` or `service_account_id`, as in the resource table; a GID of the right type. | Success is `201 Created` with an `etag` header and a body of five fields: `id`, `create_time`, `created_by`, `update_time`, `updated_by`. The object itself is not echoed; read it if you need it. A create is validated in full before anything is stored, so a `422` lists every problem in the body at once. # How do updates work? `PUT /configs/v1//{id}`, by GID. There is no `PATCH`: the object's own configuration fields are sent in full and replace the stored ones, with the required ones of each resource listed in its guide. The common fields and the header behave the same everywhere: - **`display_name` and `description`**: left out or `null`, the stored value is unchanged; an empty string removes it; otherwise the same length limits as on create. A body that changes nothing is refused with `422` and `nothing to change`. - **`If-Match`**: optional, carrying the `etag` value from the last read, create or update of the object. If the object changed since, the update is refused with `412 Precondition Failed` and nothing is written; re-read, decide, retry. A value that is not an ETag at all (fewer than 8 or more than 18 characters) is refused with `400`. Send it whenever two writers could touch the same object. - **Immutable**: `name`, the parent, a Service Account's `role`, and a project's `region`, `replica_region`, `ikg_size` and `ikg_schema_version` are absent from the update bodies. Changing one means creating a new object. Success is `200` with a new `etag` header and the same five-field body as a create. # How do deletes work? `DELETE /configs/v1//{id}`, by GID, with the same optional `If-Match` as an update. Success is `200` with `{"id": ""}`. A read of the object afterwards is `404`. The API states nothing about what a parent's deletion does to its children, so delete the children you know about first, credentials included. # What statuses and switches exist? | Resource | Field | Values | | --- | --- | --- | | Authorization policy, Knowledge Query | `status` (required on create and update) | `ACTIVE`: in force. `INACTIVE`: stored and validated, not applied. `DRAFT`: stored without validation, so a policy or query that is not yet valid JSON can be saved and finished later; it must validate before it becomes `ACTIVE`. | | MCP server | `enabled` (required boolean) | `false` keeps the configuration and refuses connections. | | Project | `ikg_status` (read-only) | The state of the graph database behind the project: `PENDING` while it is provisioned or connected, `ACTIVE` when usable, `FAILED` with the reason, `PAUSED` when stopped; see the [graph database guide](/guides/guide-graph-database). | | Entity matching pipeline | `entity_matching_status`, `property_mapping_status` (read-only) | Progress of the pipeline's runs; see the [Entity Matching guide](/guides/guide-entity-matching). | # What errors should I expect? Two body shapes cover every error. `{"message": "…"}` alone, or `{"message": "…", "errors": ["…", "…"]}` where `message` is the status text and `errors` carries the reasons. An entry in `errors` is either `missing field ` or `invalid field : `, the path naming the JSON field, with an index or key for an array or map element (`providers[azure2].azure_service_bus.connection_string`). | Status | When | Body | | --- | --- | --- | | `400 Bad Request` | The body is not valid JSON, a field has the wrong JSON type, or `If-Match` is malformed. | `{"message": "Bad Request"}` for a body that is not JSON; `{"message": "Bad Request", "errors": ["invalid field "]}` for a wrong type; `{"message": "Bad Request", "errors": ["invalid If-Match: etag value length must be between 8 and 18 characters"]}` | | `401 Unauthorized` | No `Bearer` token in `Authorization`; or one that is invalid, expired or revoked, or an Application Agent JWT. | `{"message": "Missing or malformed ServiceAccount credential token in Authorization header"}` or `{"message": "Invalid ServiceAccount JWT in Authorization header"}` | | `403 Forbidden` | The account's role does not allow the operation, or the object belongs to another organization. | `{"message": "Forbidden", …}` | | `404 Not Found` | No object with that GID or name, including one already deleted. | `{"message": "Not Found", "errors": ["empty response"]}` | | `406 Not Acceptable` | The `Accept` header excludes JSON or is missing. | An `error` field: `Accept must be application/json or */*` | | `409 Conflict` | An object with that `name` already exists in the parent, or a resource-specific uniqueness rule is broken, for example two Token Introspect configurations with the same issuer and audience, or a second Event Sink, MCP Server or Audit Signing configuration in a project that already has one (`audit signing config already exists in project`). | `{"message": "Conflict", "errors": ["…"]}` | | `412 Precondition Failed` | The `If-Match` value is not the object's current ETag. | `{"message": "Precondition Failed", "errors": ["…precondition failed…"]}` | | `415 Unsupported Media Type` | A `POST` or `PUT` without `Content-Type: application/json`. | An `error` field: `Content-Type must be application/json` | | `422 Unprocessable Entity` | Validation failed, at write time, before anything is stored: a missing or malformed field, a GID of the wrong type, a limit exceeded, an invalid URL (`invalid field url: "/some/path" does not meet rule http_url`), a URL the platform could never call (`URL: unsupported URL scheme: must be https` for plain `http`, `URL: destination is not permitted` for a literal private address), a policy that is not valid JSON, a reference to an object that does not exist. A secret that fails validation is never echoed: `invalid field app_agent_token: ******** does not meet rule jwt`. | `{"message": "Unprocessable Entity", "errors": ["missing field …", "invalid field …: …"]}` | | `500 Internal Server Error` | The platform failed; the request was not applied. | `{"message": "Internal Server Error"}`, or `{"message": "Unable to verify the ServiceAccount credential token"}` when the credential check itself failed for a non-transient reason (do not rotate the credential; see the [Credentials guide](/guides/guide-credentials)) | | `503 Service Unavailable` | The token could not be verified for a transient reason; retry with backoff, same credential. | `{"message": "Unable to verify the ServiceAccount credential token, retry the request"}` | A `422` is the only error that reports several problems at once, so fix everything it lists before retrying. Resource-specific messages, such as the audit signing provider rules or the replica region constraint of a project, are in the guide of that resource. # Next Steps - **Hierarchy**: [Environment guide](/guides/guide-environment) - **Tokens**: [Credentials guide](/guides/guide-credentials) - **As code**: [Terraform guide](/guides/guide-terraform) - **Walkthroughs**: [Project, application and credentials](/resources/environment-1), [Organization and Service Accounts](/resources/environment-2) - **Reference**: [Config REST API](https://openapi.indykite.com/api-documentation-config) --- Source: https://developer.indykite.com/guides/guide-config-api --- # ContX IQ: Context-Aware Data Queries and Policies > ContX IQ (CIQ): authorize and run graph reads, writes and deletes on the IndyKite Knowledge Graph with a CIQ policy (1.0-ciq, or 2.0-ciq for CIQ v2), a Knowledge Query and POST /contx-iq/v1/execute. **Category:** ContX IQ ## Summary How ContX IQ works end to end: the policy that authorizes, the Knowledge Query that reads or writes, the execute call that runs it as a user or an application, with a complete worked example, the full field reference, response shapes, and every error., and what CIQ v2 (2.0-ciq) changes: @ filter attributes, 422 for every missing parameter, the relationship result shape, and @ references that write values read from the graph ## Content # What is ContX IQ? **ContX IQ (CIQ)** lets an application read, write, and delete data in the IndyKite Knowledge Graph (IKG) **only through queries a policy has authorized**. A typical use: a car-rental app shows a signed-in customer the contracts and vehicles that belong to them, and nothing else. The graph pattern that defines "belongs to them" lives in a CIQ policy, the fields to return live in a Knowledge Query, and the app runs it with the customer's access token. The platform compiles both into one Cypher query, binds the caller, and returns only what the policy allows. Three objects are involved: | Object | Role | Created with | | --- | --- | --- | | **CIQ policy** | The graph pattern the caller must match, plus what may be read, written, or deleted. | `POST /configs/v1/authorization-policies` (Service Account credentials) or Terraform `indykite_authorization_policy` | | **Knowledge Query** | What to do within that pattern: which fields to return, which nodes and relationships to upsert or delete. It references one policy. | `POST /configs/v1/knowledge-queries` (Service Account credentials) or Terraform `indykite_knowledge_query` | | **Execute request** | Runs a stored Knowledge Query now, with input parameters, as the caller identified by the request's tokens. | `POST /contx-iq/v1/execute` (Application Agent credentials, plus the user's token) | ## Terms used in this guide - **IKG**: the IndyKite Knowledge Graph, a property graph of nodes and relationships (see the [Data Schema guide](/guides/guide-data-schema)). - **Identity node**: a node ingested with `is_identity: true`; the only kind of node that can be the subject of a CIQ query. In Cypher it carries the `DigitalTwin` label. - **Application Agent (AppAgent)**: the credential your application calls the runtime APIs with, sent as `X-IK-ClientKey`. It needs the `ContXIQ` API permission (see the [Credentials guide](/guides/guide-credentials)). - **User token**: the end user's OAuth 2.0 access token from your identity provider, sent as `Authorization: Bearer`. A [Token Introspect](/guides/guide-token-introspect) configuration validates it and maps its subject to an identity node. This guide uses only this one name for it. - **Delegation token**: an optional second token in `X-IK-Token`, minted by the [IndyKite Token Service](/guides/guide-token-service), carrying the chain of agents acting for the user. Covered under [Advanced](#advanced). - **GID**: the platform's globally unique identifier for a configuration object or node, prefixed `gid:`. - **Input parameter**: a value supplied at execute time under `input_params` and referenced in a policy or query as `$name`. # A complete example The example graph below is the one every ContX IQ resource in this library ingests. A `Person` accepts a `Contract` that covers a `Vehicle`; a `Company` owns the vehicles and has an agreement with your `Application`. ![](/assets/images/SubGraphXYZ.png) **Example graph: Person -ACCEPTED-> Contract -COVERS-> Vehicle -HAS-> LicenseNumber; Company -OWNS-> Vehicle; Application -AGREEMENT_WITH-> Company; Person -HAS-> PaymentMethod** Goal: a signed-in person lists their active contracts and the vehicles they cover. Four steps: ingest, policy, Knowledge Query, execute. ## Step 1: Ingest the graph Nodes and relationships go in through the Capture API with AppAgent credentials; the person must be an identity node. The full payload for this graph is in resource [ciq-2](/resources/ciq-2); the relevant part: ```json POST /capture/v1/nodes { "nodes": [ { "external_id": "ryan", "type": "Person", "is_identity": true, "properties": [ { "type": "email", "value": "ryan@yahoo.co.uk" } ] }, { "external_id": "ct123", "type": "Contract", "properties": [ { "type": "status", "value": "Active" }, { "type": "number", "value": "hfgrten123" } ] }, { "external_id": "car1", "type": "Vehicle" } ] } ``` ```json POST /capture/v1/relationships { "relationships": [ { "source": { "external_id": "ryan", "type": "Person" }, "target": { "external_id": "ct123", "type": "Contract" }, "type": "ACCEPTED" }, { "source": { "external_id": "ct123", "type": "Contract" }, "target": { "external_id": "car1", "type": "Vehicle" }, "type": "COVERS" } ] } ``` The person's `external_id` (`ryan`) must equal the `sub` claim of their token, because that is how the policy will tie the two together. ## Step 2: Write the policy ```json { "meta": { "policy_version": "1.0-ciq" }, "subject": { "type": "Person" }, "condition": { "cypher": "MATCH (subject:Person)-[accepted:ACCEPTED]->(contract:Contract)-[:COVERS]->(vehicle:Vehicle)", "filter": [ { "operator": "AND", "operands": [ { "operator": "=", "attribute": "subject.external_id", "value": "$token.sub" }, { "operator": "=", "attribute": "contract.property.status", "value": "Active" } ] } ] }, "allowed_reads": { "nodes": [ "contract.external_id", "contract.property.number", "vehicle.external_id" ], "relationships": [ "accepted" ] } } ``` Three things make this policy work, and each is a rule, not a convention: - **The subject is bound to the caller by the policy, not by the platform.** The line `subject.external_id = $token.sub` is what stops one person from reading another's contracts. Without it, the query would match every person in the graph. The platform never pins `subject` to the token by itself. - **The subject variable must be named `subject`** and carry the label of `subject.type`. The platform adds the identity label to it, so only identity nodes can match. - **Every node the query will use has a variable and a label.** `accepted`, `contract`, `vehicle` are the names `allowed_reads` and the Knowledge Query refer to. Store it with the Config API. The policy JSON travels as a string in the `policy` field: ```json POST /configs/v1/authorization-policies Authorization: Bearer { "project_id": "gid:AAAABbbbCCCC...", "name": "person-active-contracts", "display_name": "A person's active contracts", "policy": "", "status": "ACTIVE", "tags": [] } ``` The response carries the policy's `id` (a GID), needed in the next step. ## Step 3: Write the Knowledge Query ```json { "nodes": [ "contract.external_id", "contract.property.number", "vehicle.external_id" ], "relationships": [ "accepted" ] } ``` ```json POST /configs/v1/knowledge-queries Authorization: Bearer { "project_id": "gid:AAAABbbbCCCC...", "name": "kq-my-active-contracts", "policy_id": "", "query": "", "status": "ACTIVE" } ``` A Knowledge Query may only ask for what its policy lists under `allowed_reads`; anything else is refused when the query is saved. ## Step 4: Execute as the user ```bash curl -X POST https://eu.api.indykite.com/contx-iq/v1/execute \ -H "X-IK-ClientKey: $CLIENT_KEY" \ -H "Authorization: Bearer $USER_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "id": "kq-my-active-contracts", "input_params": {} }' ``` Response for ryan's token (`sub` = `ryan`): ```json { "data": [ { "nodes": { "contract.external_id": "ct123", "contract.property.number": "hfgrten123", "vehicle.external_id": "car1" }, "relationships": { "accepted": { "Id": 1155177702467043300, "ElementId": "5:3a2b09d5-...:1155177702467043332", "StartId": 4, "StartElementId": "4:3a2b09d5-...:4", "EndId": 8, "EndElementId": "4:3a2b09d5-...:8", "Type": "ACCEPTED", "Props": { "id": "gid:AAAAF...", "create_time": "2026-09-01T10:15:23.494Z", "update_time": "2026-09-01T10:15:23.494Z" } } } } ] } ``` Another person's token returns their own contracts; a token whose subject accepted no active contract returns `{"data": []}`. No input parameter was needed because the binding came from the token. The same policy could instead bind through a parameter (`"value": "$subject_external_id"`) for cases where the application itself decides whom to query, at the price of the caller choosing the subject. # CIQ policy reference ## Syntax ```json { "meta": { "policy_version": "1.0-ciq" }, "subject": { "type": "" }, "condition": { "cypher": "", "filter": [ { "operator": "AND", "operands": [ { "operator": "", "attribute": "", "value": } ] } ], "token_filter": { "operator": "", "attribute": "$token.", "value": , "advice": { "error": "", "error_description": "" } } }, "allowed_reads": { "nodes": [ "" ], "relationships": [ "" ], "aggregate_values": [ "" ] }, "allowed_upserts": { "nodes": { "existing_nodes": [ "" ], "node_types": [ "" ] }, "relationships": { "existing_relationships": [ "" ], "relationship_types": [ { "type": "", "source_node_label": "", "target_node_label": "" } ] } }, "allowed_deletes": { "nodes": [ "" ], "relationships": [ "" ] } } ``` Omit any `allowed_*` block, or sub-field, that is empty. `token_filter` is optional. ## meta and subject - `meta.policy_version`: `1.0-ciq`, the dialect this guide describes, or `2.0-ciq` for [CIQ v2](#ciq-v2-20-ciq), which differs in the points listed there. Any other value is refused with `invalid policy version: `. - `subject.type`: the node type of the caller: an identity node type such as `Person`, or `_Application` for the application itself (see [Advanced](#the-application-as-subject)). One type per policy; two subject types need two policies. ## condition.cypher A read-only Cypher pattern: `MATCH`, `OPTIONAL MATCH`, `WHERE`, `WITH`, and aggregate functions such as `COLLECT` and `COUNT` projected with `AS`. The [CIQ Cypher guide](/guides/guide-ciq-cypher) covers the dialect in depth. Rules enforced when the policy is saved: - A node variable named `subject` must exist, labelled with `subject.type`. Missing: `required variables [subject] are not present within the query`. Wrong label: `subject type for policy does not match subject type in cypher`. - Every named node needs a label: `No labels provided for node in cypher.` - Only variables named in the Cypher can be referenced by filters, `allowed_*`, and the Knowledge Query. An anonymous node such as `(:Car)` cannot be referenced; give it a name. - The labels `_AppAgent`, `_API`, `_TrustScore`, `Source`, and the four data schema labels `_DataSchemaNode`, `_DataSchemaProperty`, `_DataSchemaRelationship` and `_DataSchemaMetadata` cannot be matched: `invalid node type `