Skip to main content

Sign every request with AAuth

Give an agent an Ed25519 key and sign each HTTP request with it, so that the receiver knows which agent sent exactly this request.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPHPJavaC# / .NET

What it shows​

  1. The agent signs its own agent token, a JWT that names the key of the agent.
  2. The resource, the API that the agent calls, asks LumoAuth for a resource token for this agent.
  3. The agent sends both tokens to LumoAuth in a signed request, and receives an auth token for the resource.
  4. The agent signs one request to the resource: the method, the address, a digest of the body and the Authorization header.
  5. The resource checks the auth token and the signature. When one byte of the body changes, the resource refuses the request.

Each program plays both parts, the agent and the resource, so that you can read the whole exchange in one file. In your own system, the two parts run on different servers.

Before you start​

AAuth agents and resources are registered in the portal. The Admin API has no call for them.

First run the setup script below. It creates two Ed25519 key pairs, one for the agent and one for the resource. It writes the private keys to files in your home folder and prints the public keys.

Then register the resource:

  1. In the portal, open AI Agents, then Agents, then the AAuth resources tab. Click Register resource.
  2. Enter the Resource name Supplier directory API and the Resource identifier https://suppliers.example.com.
  3. Under Public keys, paste the public key of the resource that the setup script printed.
  4. Under Scopes, add the scope suppliers:read with the description "Read the supplier directory".
  5. Click Register resource.

Then register the agent:

  1. On the Agents page, click Register agent. Enter the Agent name Supplier lookup agent and click Next: how it proves its identity.
  2. Choose AAuth. Enter the Agent identifier https://supplier-lookup.example.com, and paste the key set of the agent into JWKS (inline). Click Next: what it may do.
  3. Under Acting for people, leave User-in-the-loop authorization switched off. Enter suppliers:read in Pre-authorized scopes.
  4. Click Register agent.

The agent acts alone here, so no person is asked. An agent that acts alone receives only the scopes listed in its Pre-authorized scopes.

VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
AGENT_PRIVATE_KEYThe Ed25519 private key of the agent, as PEM. The setup script writes it to a file and prints the command that sets the variable.
RESOURCE_PRIVATE_KEYThe Ed25519 private key of the resource, the API that the agent calls. The setup script writes it to a file as well.
AAUTH_AGENTOptional. The agent identifier that you registered. Default: https://supplier-lookup.example.com.
AAUTH_RESOURCEOptional. The resource identifier that you registered. Default: https://suppliers.example.com.

The setup script creates the two key pairs and prints the public keys for the portal. It calls no API and needs no API key.

node agents/aauth-signed-requests/setup.mjs
setup.mjs
// Creates the two key pairs of this recipe: one for the agent and one for
// the resource, the API that the agent calls. The private keys go to files
// outside the repository. The script prints the public keys, which you
// register in the portal as the page describes. It calls no API.
//
// node agents/aauth-signed-requests/setup.mjs
//
// The files are written to the folder that AAUTH_KEY_DIR names. Without that
// variable, the folder is your home folder. A second run keeps the keys.
import { createPublicKey, generateKeyPairSync } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

const dir = process.env.AAUTH_KEY_DIR ?? homedir();

// Returns the file of a private key and its public half as a JWK.
function key(name) {
const file = join(dir, `aauth-${name}-key.pem`);
if (!existsSync(file)) {
const pem = generateKeyPairSync('ed25519').privateKey.export({ type: 'pkcs8', format: 'pem' });
writeFileSync(file, pem, { mode: 0o600 });
}
const { kty, crv, x } = createPublicKey(readFileSync(file, 'utf8')).export({ format: 'jwk' });
return { file, jwk: { kty, crv, x, use: 'sig', kid: 'key-1' } };
}

const agent = key('agent');
const resource = key('resource');

console.log('Public keys of the agent, for the field "JWKS (inline)":');
console.log(JSON.stringify({ keys: [agent.jwk] }));
console.log('\nPublic key of the resource, for the box under "Public keys":');
console.log(JSON.stringify(resource.jwk));

console.log('\n# Set these before you run the recipe:');
console.log(`export AGENT_PRIVATE_KEY="$(cat '${agent.file}')"`);
console.log(`export RESOURCE_PRIVATE_KEY="$(cat '${resource.file}')"`);

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Each program plays the agent and the resource. The signed request goes to the check of the resource inside the program, not over the network.

agents/aauth-signed-requests/js/aauth.mjs
// An agent gets an AAuth token for one API and signs a request with its own
// key. The API, which AAuth calls the resource, verifies the token and the
// signature. One program plays both parts, so that you can read the whole
// exchange in one file.
//
// node agents/aauth-signed-requests/js/aauth.mjs
import { createPrivateKey, createPublicKey, randomUUID, sign } from 'node:crypto';
import {
AAuthClient,
buildSignatureBase,
contentDigestSha256,
signRequest,
verifyAuthToken,
verifySignatureBase,
} from '@lumoauth/agent';

const AGENT = process.env.AAUTH_AGENT ?? 'https://supplier-lookup.example.com';
const RESOURCE = process.env.AAUTH_RESOURCE ?? 'https://suppliers.example.com';
const KEY_ID = 'key-1';

// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
const agent = new AAuthClient({ agentIdentifier: AGENT, privateKeyPem: process.env.AGENT_PRIVATE_KEY, kid: KEY_ID });
const base64url = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');

// ----- The agent -----

// 1. The agent token says which key signs the requests of the agent. The
// agent signs this JWT itself, with a key of its registered key set.
function agentToken() {
const now = Math.floor(Date.now() / 1000);
const header = { typ: 'agent+jwt', alg: 'EdDSA', kid: KEY_ID };
const claims = {
iss: AGENT,
sub: `${AGENT}/session/main`,
aud: agent.issuer,
iat: now,
exp: now + 300,
jti: randomUUID(),
cnf: { jwk: agent.publicJwk },
};
const input = `${base64url(header)}.${base64url(claims)}`;
const signature = sign(null, Buffer.from(input), createPrivateKey(process.env.AGENT_PRIVATE_KEY));
return `${input}.${signature.toString('base64url')}`;
}

// ----- The resource -----

// 2. The resource asks LumoAuth for a resource token. The token names the
// agent, the key of the agent and the scope that the resource allows.
// The resource signs this request with its own key.
async function resourceToken(agentIdentifier, agentKeyThumbprint) {
const url = `${agent.issuer}/aauth/resource/token`;
const body = JSON.stringify({
resource: RESOURCE,
agent: agentIdentifier,
agent_jkt: agentKeyThumbprint,
scope: 'suppliers:read',
});
const headers = signRequest(process.env.RESOURCE_PRIVATE_KEY, 'POST', url, { body });
const answer = await fetch(url, { method: 'POST', headers, body });
if (!answer.ok) throw new Error(`The resource token was refused: ${answer.status} ${await answer.text()}`);
return (await answer.json()).resource_token;
}

// 5. The resource verifies a request. It checks the auth token, the digest
// of the body, and that the key of the token signed this request.
async function verifyRequest({ method, url, headers, body }) {
let claims;
try {
const token = headers.Authorization.replace(/^Bearer /, '');
claims = await verifyAuthToken(token, { issuer: agent.issuer, resource: RESOURCE });
} catch (error) {
return `refused: ${error.message}`;
}

if (headers['Content-Digest'] !== contentDigestSha256(body)) return 'refused: the body does not match its digest';

// The signature must cover the parts that matter, and it must be recent.
const [, list, created, nonce] = headers['Signature-Input'].match(/^sig1=\(([^)]*)\);created=(\d+);nonce="([^"]+)"$/);
const components = list.split(' ').map((name) => name.replaceAll('"', ''));
for (const name of ['@method', '@authority', '@path', 'content-digest', 'authorization']) {
if (!components.includes(name)) return `refused: the signature does not cover ${name}`;
}
if (Math.abs(Date.now() / 1000 - Number(created)) > 60) return 'refused: the signature is too old';

// Rebuild the text that the agent signed, from the request as it arrived.
const { host, pathname } = new URL(url);
const values = {
'@method': method,
'@authority': host,
'@path': pathname,
'signature-key': headers['Signature-Key'] ?? '',
'content-digest': headers['Content-Digest'],
'content-type': headers['Content-Type'],
authorization: headers.Authorization,
};
const base = buildSignatureBase(components, values, Number(created), nonce);
const signature = headers.Signature.slice('sig1=:'.length, -1);
const key = createPublicKey({ key: claims.cnf.jwk, format: 'jwk' });
if (!verifySignatureBase(base, signature, key)) return 'refused: the signature does not fit the key of the token';

return `accepted, agent ${claims.agent}, scope ${claims.scope}`;
}

// ----- The exchange -----

// 3. The agent sends both tokens to LumoAuth in a signed request, and
// receives an auth token for this resource. The token carries its key.
const authorization = await agent.requestAuthToken({
agentToken: agentToken(),
resourceToken: await resourceToken(AGENT, agent.publicJwkThumbprint),
});
if ('authorizationRequired' in authorization) throw new Error('A person must approve first. See "Before you start".');
console.log(`auth token: ${authorization.tokenType}, valid for ${authorization.expiresIn} seconds`);

// 4. The agent signs one request: the method, the address, the digest of the
// body and the Authorization header.
const url = `${RESOURCE}/v1/suppliers/search`;
const body = JSON.stringify({ name: 'Northwind Labs' });
const bearer = `Bearer ${authorization.authToken}`;
const headers = { Authorization: bearer, ...agent.signRequest('POST', url, { body, authorization: bearer }) };
console.log(`signed: ${headers['Signature-Input'].match(/\(([^)]*)\)/)[1].replaceAll('"', '')}`);

console.log(`request as signed: ${await verifyRequest({ method: 'POST', url, headers, body })}`);

// 6. Somebody changes the body on the way. The signature still covers the
// old digest, so the resource refuses the request.
const changed = body.replace('Northwind Labs', 'Northwind Labz');
console.log(`request after a change: ${await verifyRequest({ method: 'POST', url, headers, body: changed })}`);
node agents/aauth-signed-requests/js/aauth.mjs

Check the result​

Output
auth token: auth+jwt, valid for 3600 seconds
signed: @method @authority @path signature-key content-digest content-type authorization
request as signed: accepted, agent https://supplier-lookup.example.com, scope suppliers:read
request after a change: refused: the body does not match its digest
  • The audit log of the organization records each auth token as aauth.auth_token_issued.
  • Change the scope that the resource asks for to suppliers:write, and run the program again. The resource does not list that scope, so LumoAuth refuses the resource token with invalid_scope.

Limits​

  • AAuth is a draft protocol. LumoAuth follows the current draft, which may change.
  • The check of the resource in these programs accepts a signature for 60 seconds. To refuse a captured request that is sent a second time, the resource must also store each nonce that it has seen.
  • The SDKs sign requests, but they do not create the agent token. Each program signs that JWT itself. LumoAuth can also issue agent tokens to delegates of the agent: see POST /aauth/agent/issue in the AAuth reference.
  • The Python and PHP SDKs have no check for auth tokens. The Python program checks the token with PyJWT. The PHP program asks LumoAuth, through POST /aauth/auth/token/verify, which also reports a revoked token.