# Valiron trust gate on AWS API Gateway

Run the Valiron trust gate as a Lambda authorizer in front of an API Gateway
REST API or HTTP API. It makes the same decisions as the Node middleware and
the [Cloudflare Worker](./CLOUDFLARE-GATE-MIDDLEWARE.md): it identifies the
agent, checks that the agent signed this exact request, reads its live trust
profile, and lets the request through only if it meets your policy. Your
backend code does not change.

The template is `examples/aws-api-gateway-authorizer` in the `@valiron/sdk`
package from version 2.1.2. It uses only APIs that 2.1.1 already exports, so
it runs on `@valiron/sdk` 2.1.1 or later.

## Who this is for

API providers on API Gateway who want agent ownership and trust checks before
requests reach their integrations. You deploy one Lambda function and one
DynamoDB table, then attach the authorizer to the methods you want to gate.
Existing API keys, usage plans and other authorizers keep working.

## How a request is checked

```text
Agent request
  -> API Gateway calls the authorizer (caching off, every request)
  -> authorizer reads x-agent-id or x-agent-address
  -> no identity: deny, or allow as "anonymous" if you chose that
  -> reads the agent's current owner wallet from Valiron (shared 30 s cache)
  -> verifies the signature over method + exact public URL + empty body
  -> claims the nonce in DynamoDB (conditional write; replay = reject)
  -> trust decision from the same profile (prod / prod_throttled and score >= minScore)
  -> Allow policy with decision context, or Deny / 401 / 503
```

| Condition | REST API | HTTP API | Code |
| --- | --- | --- | --- |
| Allowed | integration runs | integration runs | context `valironDecision: allow` |
| No identity headers, anonymous allowed | integration runs | integration runs | context `valironDecision: anonymous` |
| No identity headers (default) | 401 | 403 | `MISSING_AGENT_IDENTITY` |
| Missing, stale, replayed or invalid proof | 401 | 403 | `AGENT_OWNERSHIP_REQUIRED` |
| Owner lookup failed | 401 | 403 | `AGENT_OWNERSHIP_REQUIRED` |
| Score below `minScore` or route not production | 403 | 403 | `TRUST_GATE_DENIED` |
| New agent, sandbox evaluation running (default) | 403 | 403 | `AGENT_EVALUATION_PENDING` |
| New agent, pending allowed | integration runs | integration runs | context `valironDecision: pending` |
| Identified request with a body (POST, PUT, ...) | 403 | 403 | `REQUEST_BODY_NOT_VERIFIABLE` |
| Valiron evaluation failed after a valid proof, or bad configuration | 503 with the template's gateway responses, else 500 | 500 | `TRUST_GATE_UNAVAILABLE` |

Every failure is closed: the integration never runs.

## What API Gateway changes

These limits come from API Gateway, not from Valiron. Read them before you
choose which routes to gate.

- **Authorizers never see the request body.** The proof signs a digest of the
  body, so the authorizer can only verify `GET` and `HEAD`. Identified
  requests with any other method get `REQUEST_BODY_NOT_VERIFIABLE`. Do not
  attach this authorizer to body-carrying routes. Verify those inside the
  integration with `createEdgeWalletProofVerifier` from
  `@valiron/sdk/edge-gate`, where the body is available.
- **REST APIs do not pass the raw query string.** They pass decoded
  parameters. The authorizer rebuilds the URL the agent most likely signed,
  in up to three encodings (as typed, `encodeURIComponent`, and
  `URLSearchParams`), and accepts the first that matches. Agents that build
  URLs with `fetch`, `encodeURIComponent` or `URLSearchParams` verify. A query
  encoded any other way, such as lowercase percent-escapes, cannot be
  recovered and fails closed with `AGENT_OWNERSHIP_REQUIRED`. HTTP APIs pass
  `rawQueryString`, which is used exactly.
- **REST APIs cannot return a specific 401 body from a Lambda authorizer.**
  Missing identity and invalid proofs both return the `UNAUTHORIZED` gateway
  response. The exact reason is in the authorizer log.
- **Gateway responses apply to the whole API.** The template can replace
  `ACCESS_DENIED`, `UNAUTHORIZED`, `AUTHORIZER_FAILURE` and
  `AUTHORIZER_CONFIGURATION_ERROR` with Valiron bodies, and map authorizer
  failures to 503 with `Retry-After`. That affects every method on the API,
  so it is off by default (`ManageGatewayResponses=false`).
- **HTTP API simple responses are always 403 on deny,** and authorizer errors
  are 500. They cannot be customized.

## Deploy on a REST API

You need the AWS SAM CLI, Node.js 22 and a Valiron operator API key (Free or
Pro). Profile reads used by the gate do not count against the monthly
request allowance; sandbox evaluations of new agents do.

1. **Store the operator key in Secrets Manager.** The secret's value is the
   key itself, or JSON `{"apiKey": "val_op_..."}`.

   ```bash
   aws secretsmanager create-secret --name valiron/operator-key \
     --secret-string 'val_op_...'
   ```

2. **Copy the template and install it.**

   ```bash
   cp -R node_modules/@valiron/sdk/examples/aws-api-gateway-authorizer ./valiron-authorizer
   cd valiron-authorizer && npm install
   ```

3. **Build and deploy.** `sam deploy --guided` asks for the parameters
   below. The stack creates the function, the nonce table, the authorizer on
   your existing REST API and the invoke permission.

   ```bash
   sam build
   sam deploy --guided
   ```

   | Parameter | Value |
   | --- | --- |
   | `RestApiId` | Your existing REST API ID |
   | `PublicOrigin` | The origin agents call and sign, such as `https://api.example.com` |
   | `PublicBasePath` | Empty to auto-detect. Set it (for example `/v1`, or `/` for none) to pin the public path to base path + resource path |
   | `ValironApiKeySecretArn` | ARN from step 1 |
   | `ValironChain` | Chain for on-chain agent lookups, such as `solana` or `base` |
   | `MinScore` | Default 65 |
   | `TrustSignals` | Empty for the server default, or a list such as `sandbox,wallet` |
   | `AnonymousCallers` | `deny` (default) or `allow` |
   | `PendingAgents` | `deny` (default) or `allow` |
   | `ManageGatewayResponses` | `false` (default) or `true`; see above |

4. **Attach the authorizer to each method you want to gate, then redeploy
   the stage.** Use the `AuthorizerId` stack output.

   ```bash
   aws apigateway update-method --rest-api-id $API --resource-id $RESOURCE \
     --http-method GET --patch-operations \
     op=replace,path=/authorizationType,value=CUSTOM \
     op=replace,path=/authorizerId,value=$AUTHORIZER_ID
   aws apigateway create-deployment --rest-api-id $API --stage-name prod
   ```

   If the API is defined in CloudFormation, SAM, CDK or Terraform, set
   `AuthorizationType: CUSTOM` and the authorizer ID there instead, so the
   next deploy does not remove it.

Do not set an identity source or turn on authorizer caching. Every request
carries a fresh nonce, so a cached result would be wrong. Without caching, no
identity source is needed, and anonymous callers reach the authorizer instead
of getting an automatic 401.

## Deploy on an HTTP API

The function and table are the same. Create the authorizer yourself, with
payload format 2.0, simple responses and caching off:

```bash
aws apigatewayv2 create-authorizer --api-id $API --name valiron-trust-gate \
  --authorizer-type REQUEST --authorizer-payload-format-version 2.0 \
  --enable-simple-responses --authorizer-result-ttl-in-seconds 0 \
  --authorizer-uri arn:aws:apigateway:$REGION:lambda:path/2015-03-31/functions/$FUNCTION_ARN/invocations
```

Grant `apigateway.amazonaws.com` permission to invoke the function, and
attach the authorizer to the routes to gate.

## Configuration

The template sets these Lambda environment variables from its parameters.

| Variable | Default | Meaning |
| --- | --- | --- |
| `VALIRON_PUBLIC_ORIGIN` | required | Origin agents sign. Must be bare `https://host`. |
| `VALIRON_NONCE_TABLE` | required | DynamoDB table for nonces. |
| `VALIRON_API_KEY_SECRET_ARN` | required in the template | Secrets Manager secret with the operator key. `VALIRON_API_KEY` works for local tests. |
| `VALIRON_ENDPOINT` | `https://valiron-edge-proxy.onrender.com` | Valiron operator API. |
| `VALIRON_CHAIN` | server default | Chain for on-chain agent lookups. |
| `VALIRON_PUBLIC_BASE_PATH` | auto | See `PublicBasePath`. |
| `VALIRON_MIN_SCORE` | `65` | Minimum combined score. |
| `VALIRON_TRUST_SIGNALS` | server default | `8004,sandbox,world,self,wallet,icebreaker`. Social Graph (`icebreaker`) needs Pro. |
| `VALIRON_ANONYMOUS` | `deny` | `allow` passes callers without identity headers. |
| `VALIRON_PENDING` | `deny` | `allow` passes new agents while their sandbox evaluation runs. |
| `VALIRON_CACHE_TTL_MS` | `30000` | Profile and decision cache per Lambda instance. `0` disables. |
| `VALIRON_SANDBOX_COOLDOWN_MS` | `60000` | Minimum gap between sandbox triggers for one new agent, per instance. |
| `VALIRON_TIMEOUT_MS` | `3000` | Timeout for each Valiron API call. |
| `VALIRON_NONCE_TIMEOUT_MS` | `1500` | Timeout for each DynamoDB write. |
| `VALIRON_TELEMETRY` | `on` | `off` disables SDK usage telemetry. |
| `VALIRON_DEBUG` | unset | `1` logs the URL candidates checked, which may include query values. |

Invalid values are rejected when the function starts. Until they are fixed,
every request fails closed and the error is logged as
`valiron.authorizer_config_error`.

## What your integration receives

On allow, the authorizer context carries the decision. Clients cannot set
these values.

| Key | Example |
| --- | --- |
| `valironDecision` | `allow`, `anonymous` or `pending` |
| `valironAgentId` | `25459` |
| `valironScore` | `88` |
| `valironTier` | `A` |
| `valironRiskLevel` | `GREEN` |
| `valironRoute` | `prod` or `prod_throttled` |

Lambda proxy integrations read them from `event.requestContext.authorizer`
(REST) or `event.requestContext.authorizer.lambda` (HTTP API). Other
integrations can map them into headers with `$context.authorizer.<key>`. Read
them from the context, never from request headers, which clients control.
The `principalId` is the agent identifier, or `anonymous`.

A common policy is to serve `prod` agents normally, apply tighter limits to
`prod_throttled` and `pending`, and keep `anonymous` traffic on your free plan.

## Rolling out without breaking existing callers

Start with `AnonymousCallers=allow`. Callers that send no identity headers
behave exactly as before, so existing customers and their API keys are
unaffected. Agents that do identify themselves are verified and scored, and
your integration sees which is which. Once the agents you care about sign
their requests, switch to `deny` route by route.

## Latency and limits

A request from a known agent costs, inside the authorizer:

- one signature check, done locally: under a millisecond for Solana
  (Ed25519), a few milliseconds for EVM (EIP-191 recovery, about 1.4 ms on a
  laptop and slower on a 512 MB Lambda);
- one DynamoDB conditional write in your region;
- one Valiron profile read per agent per 30 seconds per Lambda instance. Cache
  hits make no network call.

A new agent's first requests also start a sandbox evaluation, at most once a
minute per instance, and wait up to 2 seconds for it to be accepted.

The Valiron API allows about 120 requests per minute from one client IP. If
the function runs in a VPC behind one NAT gateway, all instances share that
limit. With the default 30-second cache this is about 2 reads per minute per
agent per instance. Tell us before a high-volume launch so we can raise it.

DynamoDB TTL removes old nonces, but deletion can lag by days. The condition
checks expiry itself, so late deletion never blocks a request. Each request is
one on-demand write.

To measure the authorizer, query its log lines in CloudWatch Logs Insights:

```text
fields @timestamp, outcome, code, totalMs, verifyMs
| filter msg = "valiron.authorizer"
| stats count() as requests, pct(totalMs, 50) as p50, pct(totalMs, 95) as p95,
        pct(verifyMs, 95) as verify_p95 by outcome
```

`totalMs` is time inside the handler. Cold starts and API Gateway's own
overhead are extra. REST API access logs can record
`$context.authorizer.latency` for the full authorizer time.

## Agent side

Agents sign every request with the registry owner's key in the
`valiron-wallet-request-v2` scheme. For a `GET`, the body digest is the
SHA-256 of the empty string.

```typescript
import { createHash, randomBytes } from "node:crypto";
import { privateKeyToAccount } from "viem/accounts";

const owner = privateKeyToAccount(process.env.AGENT_OWNER_PRIVATE_KEY as `0x${string}`);
const agentId = "25459";                     // same value sent as x-agent-id
const chain = "base";                        // chain.network from the agent's Valiron profile
const url = "https://api.example.com/v1/chain?symbol=SOL"; // exact public URL

const timestamp = String(Date.now());
const nonce = randomBytes(24).toString("base64url");
const payload = [
  "valiron-wallet-request-v2",
  `agent:${agentId}`, `chain:${chain}`, "method:GET", `url:${url}`,
  `body-sha256:${createHash("sha256").update("").digest("hex")}`,
  `timestamp:${timestamp}`, `nonce:${nonce}`,
].join("\n");

await fetch(url, {
  headers: {
    "x-agent-id": agentId,
    "x-agent-timestamp": timestamp,
    "x-agent-nonce": nonce,
    "x-agent-request-signature": await owner.signMessage({ message: payload }),
  },
});
```

Solana owners sign the same UTF-8 payload with Ed25519 and send the
signature base64url-encoded. Key-based agents send `x-agent-address` instead
of `x-agent-id`, sign with that address's key and use chain `key`. Sign a
fresh nonce and timestamp for every request and every retry.

## Security notes

- **Gate every route that needs it.** The authorizer only protects methods it
  is attached to. Check the stage after every deploy.
- **The owner can be up to one cache period old.** Ownership is verified on
  every request, but the owner wallet comes from a profile cached for
  `VALIRON_CACHE_TTL_MS`. After a registry transfer, the previous owner's
  signatures are accepted for at most that long. Set `0` to read the owner on
  every request, at the cost of an extra Valiron call.
- **Proofs work across stages of the same API.** The public URL is rebuilt
  from `PublicOrigin` and the path, so a proof for `/v1/chain` is valid on any
  stage that shares the authorizer and table. Each nonce still works once.
- **Logs never contain signatures, keys or query values,** unless
  `VALIRON_DEBUG=1`.
- **IAM is minimal:** `dynamodb:PutItem` on the nonce table and
  `secretsmanager:GetSecretValue` on the one secret.

## How it is tested

The template is tested by bundling the function the way `sam build` does and
running it with real EIP-191 and Ed25519 signatures, a mock Valiron API and a
local DynamoDB through the real AWS SDK. The tests cover allow and deny on
REST and HTTP APIs, replay across instances, stale and wrong-key proofs, URL
reconstruction, anonymous and pending modes, fail-closed outages, the shared
profile cache, and 25 concurrent nonce claims with exactly one winner.

That does not replace a deployment test. Deploy to a test stage first and
send signed requests through the real API Gateway URL.
