Ask a person for a permission, for one task
An agent that lacks a permission asks for it with a reason. A person approves, and the agent gets a token for that task only.
What it shows
- The agent opens a task, "Pay invoice INV-7741".
- It asks for a permission with structured detail: the type
invoices, the actionapproveand the recordINV-7741. It adds a reason for the person who decides. - The agent may only read invoices, so the request waits for a person. It appears in the approvals inbox of the portal.
- A person approves, and the agent collects a token that carries exactly the approved detail.
- The agent completes the task, and LumoAuth revokes the token.
The agent never holds the permission to approve invoices. It holds one token, for one invoice, for a few minutes.
Before you start
- An agent whose capabilities do not cover the request. The setup script registers the agent "Invoice agent" with the single capability
invoices:read. - A person who decides. This person needs the permission
jit.approve, which the administrators of an organization hold. The owner of an agent cannot decide the requests of that agent, and the owner is the person who registered it. The setup script therefore makes a second user, Maya Chen, the owner of the agent. You can then approve as the administrator. - Check that your plan includes just-in-time permissions in the plans matrix.
| 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, admin:agents:write and admin:users:write. The agent itself needs no API key. |
AGENT_CLIENT_ID | The client ID of the agent, which is its agent ID (agt_…). The setup script prints it. |
AGENT_CLIENT_SECRET | The client secret of the agent. The setup script prints it. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node approvals/just-in-time-permission/setup.mjs
setup.mjs
// Creates what the recipe needs: an agent that may read invoices, and a user
// who owns it. Run it again at any time.
//
// node approvals/just-in-time-permission/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write and
// admin:users:write.
import { randomBytes } from 'node:crypto';
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const agent = await ensure('/admin/agents', (a) => a.name === 'Invoice agent', {
name: 'Invoice agent',
description: 'Reads invoices, and asks a person before it approves one.',
identityType: 'client_secret',
// The agent may read invoices. To approve one, it must ask.
capabilities: ['invoices:read'],
});
// LumoAuth shows a secret once, in the answer that creates it. On a second
// run the script therefore asks for a new secret, and the old one stops.
const secret =
agent.clientSecret ??
(await call('POST', `/admin/agents/${agent.agentId}/rotate-credentials`)).data.clientSecret;
// The owner of an agent cannot decide its requests, and the agent belongs to
// the person who created it: you. Give it to another person, so that you can
// approve in the portal.
const owner = await ensure('/admin/users', (u) => u.email === 'maya.chen@example.com', {
email: 'maya.chen@example.com',
name: 'Maya Chen',
// The recipe never signs in as this user, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
await call('PATCH', `/admin/agents/${agent.agentId}`, { ownerId: owner.id });
console.log(`Agent "${agent.name}" is ready. Its owner is ${owner.email}.`);
printEnv({ AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret });
LumoAuth shows a secret once. A second run of the setup script therefore asks for a new secret, and the old one stops at once.
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 was run, and the request was approved in the approvals inbox of the portal. The JavaScript program was also run with a denial.
- Node.js
- Python
- Go
- PHP
- Java
- C#
- curl
// An agent asks a person for a permission that it lacks, for one task.
//
// node approvals/just-in-time-permission/js/agent.mjs
import { LumoAgent } from '@lumoauth/agent';
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
// A task is the frame of the permission: the token works for this task only.
const task = await agent.jit.createTask({ name: 'Pay invoice INV-7741', type: 'finance' });
console.log(`task: ${task.taskId}`);
// The agent may read invoices. Approval is outside its capabilities, so a
// person decides. The call waits for the decision, for 5 minutes at most.
console.log('request: waiting for a person');
const request = await agent.jit.requestPermission(
{ type: 'invoices', actions: ['approve'], identifier: 'INV-7741' },
{ justification: 'The vendor Northwind Labs asked for payment of INV-7741.' },
);
console.log(`request: ${request.status}`);
if (request.status === 'approved') {
// The token carries exactly the approved detail. Send it to the API that approves invoices.
const token = await agent.jit.getToken(request.request_id);
console.log(`token: ${token.slice(0, 12)}… valid for ${request.granted_ttl} seconds`);
}
// The end of the task ends the permission: LumoAuth revokes the token.
await agent.jit.completeTask();
console.log('task: completed');
node approvals/just-in-time-permission/js/agent.mjs
"""An agent asks a person for a permission that it lacks, for one task.
python approvals/just-in-time-permission/python/agent.py
"""
from lumoauth import JITContext, LumoAuthAgent
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent = LumoAuthAgent()
if not agent.authenticate():
raise SystemExit("The agent could not authenticate. Check its ID and its secret.")
jit = JITContext(agent)
# A task is the frame of the permission: the token works for this task only.
task_id = jit.create_task(name="Pay invoice INV-7741", task_type="finance")
print(f"task: {task_id}")
# The agent may read invoices. Approval is outside its capabilities, so a
# person decides. The call waits for the decision, for 5 minutes at most.
print("request: waiting for a person")
request = jit.request_permission(
{"type": "invoices", "actions": ["approve"], "identifier": "INV-7741"},
justification="The vendor Northwind Labs asked for payment of INV-7741.",
)
print(f"request: {request['status']}")
if request["status"] == "approved":
# The token carries exactly the approved detail. Send it to the API that approves invoices.
token = jit.get_token(request["request_id"])
print(f"token: {token[:12]}… valid for {request['granted_ttl']} seconds")
# The end of the task ends the permission: LumoAuth revokes the token.
jit.complete_task()
print("task: completed")
python approvals/just-in-time-permission/python/agent.py
// An agent asks a person for a permission that it lacks, for one task.
//
// go run ./approvals/just-in-time-permission/go
package main
import (
"context"
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
ctx := context.Background()
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
jit, err := lumoauth.NewJITContext(agent)
if err != nil {
log.Fatal(err)
}
// A task is the frame of the permission: the token works for this task only.
task, err := jit.CreateTask(ctx, lumoauth.CreateTaskParams{Name: "Pay invoice INV-7741", Type: "finance"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("task: %s\n", task.TaskID)
// The agent may read invoices. Approval is outside its capabilities, so a
// person decides. The call waits for the decision, for 5 minutes at most.
fmt.Println("request: waiting for a person")
request, err := jit.RequestPermission(ctx,
map[string]any{"type": "invoices", "actions": []string{"approve"}, "identifier": "INV-7741"},
&lumoauth.RequestPermissionOptions{Justification: "The vendor Northwind Labs asked for payment of INV-7741."},
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("request: %s\n", request.Status)
if request.Approved() {
// The token carries exactly the approved detail. Send it to the API that approves invoices.
token, err := jit.Token(ctx, request.RequestID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("token: %s… valid for %v seconds\n", token[:12], request.Raw["granted_ttl"])
}
// The end of the task ends the permission: LumoAuth revokes the token.
if err := jit.CompleteTask(ctx); err != nil {
log.Fatal(err)
}
fmt.Println("task: completed")
}
go run ./approvals/just-in-time-permission/go
<?php
// An agent asks a person for a permission that it lacks, for one task.
//
// php approvals/just-in-time-permission/php/agent.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\LumoAuth;
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID. The agent signs in with its ID and its secret.
$tokens = (new LumoAuth())->auth->clientCredentials(getenv('AGENT_CLIENT_ID'), getenv('AGENT_CLIENT_SECRET'));
$agent = new LumoAuth(tokenProvider: fn () => $tokens['access_token']);
// A task is the frame of the permission: the token works for this task only.
$task = $agent->jit->createTask(name: 'Pay invoice INV-7741', taskType: 'finance');
printf("task: %s\n", $task['task_id']);
// The agent may read invoices. Approval is outside its capabilities, so a
// person decides. The loop waits for the decision, for 5 minutes at most.
echo "request: waiting for a person\n";
$request = $agent->jit->request(
$task['task_id'],
['type' => 'invoices', 'actions' => ['approve'], 'identifier' => 'INV-7741'],
justification: 'The vendor Northwind Labs asked for payment of INV-7741.',
);
$deadline = time() + 300;
while ($request['status'] === 'pending' && time() < $deadline) {
sleep(5);
$request = $agent->jit->status($request['request_id']);
}
printf("request: %s\n", $request['status']);
if ($request['status'] === 'approved') {
// The token carries exactly the approved detail. Send it to the API that approves invoices.
$token = $agent->jit->token($request['request_id']);
printf("token: %s… valid for %d seconds\n", substr($token['access_token'], 0, 12), $token['expires_in']);
}
// The end of the task ends the permission: LumoAuth revokes the token.
$agent->jit->completeTask($task['task_id']);
echo "task: completed\n";
php approvals/just-in-time-permission/php/agent.php
// An agent asks a person for a permission that it lacks, for one task.
//
// java -cp "java/lib/*" approvals/just-in-time-permission/java/Agent.java
import io.lumoauth.JitContext;
import io.lumoauth.LumoAgent;
import io.lumoauth.model.CreateTaskRequest;
import io.lumoauth.model.JitRequest;
import io.lumoauth.model.JitTask;
import java.util.List;
import java.util.Map;
public class Agent {
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
LumoAgent agent = LumoAgent.fromEnvironment();
JitContext jit = new JitContext(agent);
// A task is the frame of the permission: the token works for this task only.
JitTask task = jit.createTask(CreateTaskRequest.named("Pay invoice INV-7741").type("finance"));
System.out.printf("task: %s%n", task.taskId());
// The agent may read invoices. Approval is outside its capabilities, so a
// person decides. The call waits for the decision, for 5 minutes at most.
System.out.println("request: waiting for a person");
JitRequest request = jit.requestPermission(
Map.of("type", "invoices", "actions", List.of("approve"), "identifier", "INV-7741"),
JitContext.RequestOptions.justification("The vendor Northwind Labs asked for payment of INV-7741."));
System.out.printf("request: %s%n", request.status());
if (request.approved()) {
// The token carries exactly the approved detail. Send it to the API that approves invoices.
String token = jit.token(request.requestId());
System.out.printf("token: %s… valid for %d seconds%n", token.substring(0, 12), request.grantedTtl());
}
// The end of the task ends the permission: LumoAuth revokes the token.
jit.completeTask();
System.out.println("task: completed");
}
}
java -cp "java/lib/*" approvals/just-in-time-permission/java/Agent.java
#:package LumoAuth@1.7.0
#:property PublishAot=false
// An agent asks a person for a permission that it lacks, for one task.
//
// dotnet run approvals/just-in-time-permission/csharp/Agent.cs
using LumoAuth;
using LumoAuth.Models;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
using var agent = LumoAgent.FromEnvironment();
var jit = new JitContext(agent);
// A task is the frame of the permission: the token works for this task only.
var task = await jit.CreateTaskAsync(new CreateTaskRequest { Name = "Pay invoice INV-7741", Type = "finance" });
Console.WriteLine($"task: {task.TaskId}");
// The agent may read invoices. Approval is outside its capabilities, so a
// person decides. The call waits for the decision, for 5 minutes at most.
Console.WriteLine("request: waiting for a person");
var request = await jit.RequestPermissionAsync(
new { type = "invoices", actions = new[] { "approve" }, identifier = "INV-7741" },
new JitContext.RequestOptions { Justification = "The vendor Northwind Labs asked for payment of INV-7741." });
Console.WriteLine($"request: {request.Status}");
if (request.IsApproved)
{
// The token carries exactly the approved detail. Send it to the API that approves invoices.
var token = await jit.TokenAsync(request.RequestId);
Console.WriteLine($"token: {token[..12]}… valid for {request.GrantedTtl} seconds");
}
// The end of the task ends the permission: LumoAuth revokes the token.
await jit.CompleteTaskAsync();
Console.WriteLine("task: completed");
dotnet run approvals/just-in-time-permission/csharp/Agent.cs
#!/bin/sh
# An agent asks a person for a permission that it lacks, for one task.
# Needs curl and jq.
#
# sh approvals/just-in-time-permission/http/agent.sh
set -eu
API="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1"
# The agent signs in with its ID and its secret.
AGENT_TOKEN=$(curl --silent --show-error --fail "$API/oauth/token" \
--user "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" \
--data "grant_type=client_credentials" | jq -r .access_token)
post() {
curl --silent --show-error "$API$1" \
--header "Authorization: Bearer $AGENT_TOKEN" \
--header "Content-Type: application/json" \
--data "$2"
}
# A task is the frame of the permission: the token works for this task only.
TASK_ID=$(post /jit/task '{"name": "Pay invoice INV-7741", "type": "finance"}' | jq -r .task_id)
echo "task: $TASK_ID"
# The agent may read invoices. Approval is outside its capabilities, so a
# person decides.
echo "request: waiting for a person"
REQUEST=$(post /jit/request "{
\"task_id\": \"$TASK_ID\",
\"authorization_details\": {\"type\": \"invoices\", \"actions\": [\"approve\"], \"identifier\": \"INV-7741\"},
\"justification\": \"The vendor Northwind Labs asked for payment of INV-7741.\",
\"requested_ttl\": 300
}")
REQUEST_ID=$(printf '%s\n' "$REQUEST" | jq -r .request_id)
STATUS=$(printf '%s\n' "$REQUEST" | jq -r .status)
# Ask for the status every 5 seconds, for 5 minutes at most.
TRIES=0
while [ "$STATUS" = "pending" ] && [ "$TRIES" -lt 60 ]; do
sleep 5
TRIES=$((TRIES + 1))
STATUS=$(curl --silent --show-error "$API/jit/request/$REQUEST_ID/status" \
--header "Authorization: Bearer $AGENT_TOKEN" | jq -r .status)
done
echo "request: $STATUS"
if [ "$STATUS" = "approved" ]; then
# The token carries exactly the approved detail. Send it to the API that approves invoices.
TOKEN=$(post "/jit/request/$REQUEST_ID/token" '{}')
echo "token: $(printf '%s\n' "$TOKEN" | jq -r '.access_token[0:12]')… valid for $(printf '%s\n' "$TOKEN" | jq -r .expires_in) seconds"
fi
# The end of the task ends the permission: LumoAuth revokes the token.
post "/jit/task/$TASK_ID/complete" '{}' > /dev/null
echo "task: completed"
sh approvals/just-in-time-permission/http/agent.sh
Each program stops at "waiting for a person" until somebody decides:
- Open the portal and go to AI Agents, then Approvals.
- The tab Waiting shows the request of "Invoice agent", with the reason, the type
invoicesand the actionapprove. - Open the menu … at the end of the row, and click Approve. To refuse, click Deny and give a reason.
Check the result
task: task_c101cda8d1e5265a8a5fb36c31a05cbe
request: waiting for a person
request: approved
token: eyJ0eXAiOiJK… valid for 300 seconds
task: completed
- After Deny, the second
request:line saysdenied. The program gets no token, and it still completes the task. - When nobody decides within 5 minutes, the line says
pendingorexpired. A request that has expired cannot be approved. - In the portal, the tab Approved of the Approvals page shows the request and the name of the person who approved it.
- Open Audit logs under Security. The run adds the events
jit.permission_approvedandjit.task_completed.
Limits
- The token is valid for 300 seconds here. A request can ask for up to 900 seconds, and a token never lives longer than its task.
- The detail has a fixed form:
type,identifier, and the listsactions,privileges,locationsanddatatypes. LumoAuth refuses any other member, so an amount cannot be part of the detail. - A request inside the capabilities of the agent, with read-only actions, is approved at once and no person sees it. Approve routine requests by rule shows which requests a rule can approve.
- The token says what was approved. The API that receives it must still compare the detail with the call: see Accept a just-in-time token in your API.
- A token of the agent cannot approve a request. The decision needs a person: in the portal, or in your own app with an approvals inbox.