An agent that signs in with a key
Give an agent a private key in place of a secret. Nothing that can be copied out of a log is sent.
What it shows
- The setup script creates an EC P-256 key pair. It registers an agent with the identity type
private_key_jwtand the public key. LumoAuth never receives the private key. - The agent loads the private key and its key ID into a signer of the SDK.
- For each token request, the SDK signs a client assertion: a JWT that is valid for 60 seconds and for one use.
- LumoAuth verifies the signature with the registered public key and answers with a token. No secret is sent.
- To rotate, you register a new key next to the old one, give the agent the new key, and then remove the old key.
Before you start
- An API key with the scopes
admin:agents:readandadmin:agents:write, for the setup script. - For Python, the SDK needs the
cryptographypackage to sign.pip install "lumoauth[dpop]"installs it, and so does therequirements.txtof the recipes.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | For the setup script only: an API key with the scopes admin:agents:read and admin:agents:write. The agent itself needs no API key. |
AGENT_KEY_FILE | For the setup script only, and optional: the file that holds the private key. Default: nightly-reconciler-key.pem in your home folder. |
AGENT_CLIENT_ID | The agent ID (agt_…). The setup script prints it. |
AGENT_PRIVATE_KEY | The private key of the agent, as PEM text. The setup script prints a line that reads it from the key file. |
AGENT_KEY_ID | The ID (kid) of the registered public key. The setup script prints it. |
The setup script creates a key pair, writes the private key to a file outside the repository, and registers the agent with the public key. Run it with rotate to start a rotation, and once more without it to end the rotation.
node agents/key-instead-of-secret/setup.mjs
setup.mjs
// Registers an agent that signs in with a private key, and rotates that key.
//
// node agents/key-instead-of-secret/setup.mjs registers the agent, or ends a rotation
// node agents/key-instead-of-secret/setup.mjs rotate starts a rotation
//
// The private key is written to the file that AGENT_KEY_FILE names. Without
// that variable, the file is nightly-reconciler-key.pem in your home folder.
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { createHash, createPublicKey, generateKeyPairSync } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const keyFile = process.env.AGENT_KEY_FILE ?? join(homedir(), 'nightly-reconciler-key.pem');
// The public half of a private key, as a JWK. LumoAuth stores only this
// half. The key ID is the thumbprint of the key (RFC 7638).
function publicJwk(privateKeyPem) {
const { kty, crv, x, y } = createPublicKey(privateKeyPem).export({ format: 'jwk' });
const kid = createHash('sha256').update(JSON.stringify({ crv, kty, x, y })).digest('base64url');
return { kty, crv, x, y, kid, alg: 'ES256', use: 'sig' };
}
// The key that the agent holds now, if any. A rotation adds a new key after
// it, and the new key replaces the old one in the file.
const keys = [];
if (existsSync(keyFile)) keys.push(publicJwk(readFileSync(keyFile, 'utf8')));
if (keys.length === 0 || process.argv[2] === 'rotate') {
const pem = generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ type: 'pkcs8', format: 'pem' });
writeFileSync(keyFile, pem, { mode: 0o600 });
keys.push(publicJwk(pem));
}
const agent = await ensure('/admin/agents', (a) => a.name === 'Nightly reconciler', {
name: 'Nightly reconciler',
description: 'Compares the ledger with the bank statement each night.',
identityType: 'private_key_jwt',
capabilities: ['ledger:read', 'ledger:reconcile'],
jwks: { keys },
});
// An update replaces the whole key set. During a rotation the set holds the
// old key and the new key. A plain run leaves only the key of the file, and
// LumoAuth then revokes the tokens that the agent holds.
await call('PATCH', `/admin/agents/${agent.agentId}`, { jwks: { keys } });
console.log(`Agent "${agent.name}" accepts ${keys.length === 1 ? 'one key' : 'two keys: the old one and the new one'}.`);
printEnv({
AGENT_CLIENT_ID: agent.agentId,
AGENT_KEY_ID: keys.at(-1).kid,
AGENT_PRIVATE_KEY: `$(cat '${keyFile}')`,
});
The line for AGENT_PRIVATE_KEY reads the key file when your shell runs it. In production, keep the private key in a secrets manager and give it to the agent in the same variable.
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.
- Node.js
- Python
- Go
// An agent signs in with a private key in place of a secret.
//
// node agents/key-instead-of-secret/js/agent.mjs
import { ClientAssertionSigner, LumoAgent } from '@lumoauth/agent';
// The signer holds the private key. The key ID tells LumoAuth which of the
// registered public keys verifies the signature.
const signer = ClientAssertionSigner.fromPem(process.env.AGENT_PRIVATE_KEY, { keyId: process.env.AGENT_KEY_ID });
console.log(`key: ${signer.keyId} (${signer.algorithm})`);
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and AGENT_CLIENT_ID.
const agent = new LumoAgent({ privateKey: signer });
// For each token request the agent signs a new assertion, a JWT that is
// valid for 60 seconds and for one use. No secret is sent.
await agent.authenticate();
console.log(`token scope: ${agent.tokenScopes.join(' ')}`);
// The token works like the token of any other agent.
const me = await agent.getCurrentAgent();
console.log(`agent: ${me.identity.agent_id} (${me.identity.status})`);
node agents/key-instead-of-secret/js/agent.mjs
"""An agent signs in with a private key in place of a secret.
python agents/key-instead-of-secret/python/agent.py
"""
import os
from lumoauth import ClientAssertionSigner, LumoAuthAgent
# The signer holds the private key. The key ID tells LumoAuth which of the
# registered public keys verifies the signature.
signer = ClientAssertionSigner.from_pem(os.environ["AGENT_PRIVATE_KEY"], key_id=os.environ["AGENT_KEY_ID"])
print(f"key: {signer.key_id} ({signer.alg})")
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and AGENT_CLIENT_ID.
agent = LumoAuthAgent(private_key=signer)
# For each token request the agent signs a new assertion, a JWT that is
# valid for 60 seconds and for one use. No secret is sent.
if not agent.authenticate():
raise SystemExit("The agent could not get a token. Check AGENT_PRIVATE_KEY and AGENT_KEY_ID.")
print(f"token scope: {' '.join(agent.token_scopes)}")
# The token works like the token of any other agent.
identity = agent.get_identity()["identity"]
print(f"agent: {identity['agent_id']} ({identity['status']})")
python agents/key-instead-of-secret/python/agent.py
// An agent signs in with a private key in place of a secret.
//
// go run ./agents/key-instead-of-secret/go
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
// The signer holds the private key. The key ID tells LumoAuth which of the
// registered public keys verifies the signature.
signer, err := lumoauth.LoadClientAssertionSigner(os.Getenv("AGENT_PRIVATE_KEY"),
lumoauth.ClientAssertionOptions{KeyID: os.Getenv("AGENT_KEY_ID")})
if err != nil {
log.Fatal(err)
}
fmt.Printf("key: %s (%s)\n", signer.KeyID(), signer.Algorithm())
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and AGENT_CLIENT_ID.
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{PrivateKey: signer})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
// For each token request the agent signs a new assertion, a JWT that is
// valid for 60 seconds and for one use. No secret is sent.
if _, err := agent.Authenticate(ctx); err != nil {
log.Fatal(err)
}
fmt.Printf("token scope: %s\n", strings.Join(agent.TokenScopes(), " "))
// The token works like the token of any other agent.
me, err := agent.Identity(ctx, false)
if err != nil {
log.Fatal(err)
}
fmt.Printf("agent: %v (%v)\n", me.Identity["agent_id"], me.Identity["status"])
}
go run ./agents/key-instead-of-secret/go
Check the result
key: 0D1wizrYqpdb7vhdzB_eYah0OpKg3zFpGrcyscDupBo (ES256)
token scope: ledger:read ledger:reconcile
agent: agt_95a58e465cdf2486 (active)
Then rotate the key, and keep the variables of the old key in this shell:
- Run
node agents/key-instead-of-secret/setup.mjs rotate. The agent now accepts two keys, and the key file holds the new one. - Run the program again in this shell. The old key still works, so an agent that runs now is not interrupted.
- Open a second shell, set the variables that the setup script printed, and run the program. It prints the new key ID.
- Run
node agents/key-instead-of-secret/setup.mjswithoutrotate. The agent accepts only the new key. - Run the program in the first shell once more. LumoAuth answers 401
invalid_client, because the old key is no longer registered.
In the portal, open Audit logs under Security. The refused request is an entry with the event agent.client_assertion_rejected.
Limits
- The identity type of an agent is fixed at registration. To move an agent from a secret to a key, register a new agent with the same capabilities.
- A key set holds 1 to 10 keys, and each key needs a
kidwhen the set holds more than one. - When you remove a key from the set, LumoAuth revokes the tokens that the agent holds. Adding a key revokes nothing.
- The assertion protects the token request. The access token is still a bearer token: Bind an agent token to the agent adds DPoP.
- The Java, .NET and PHP SDKs have no signer for client assertions. In those languages, sign the JWT with a JWT library as the docs page describes.