An approvals inbox in your own app
Show pending requests to approvers inside your product, and send their decisions to LumoAuth.
What it shows
- An approver signs in to your app. The app asks for the scope
jit:approve. - Your server lists the requests that wait for a person, with the access token of that approver.
- The approver clicks approve or deny, and your server sends the decision to LumoAuth with the same token.
- LumoAuth checks who may decide, and the agent gets its answer.
Your server never decides with an API key: an API key cannot hold jit:approve. Each decision is made by a person, and the audit log names that person.
Before you start
- An application through which approvers sign in, with the scope
jit:approve. The setup script registers the application Approvals desk, with the redirect addresshttp://localhost:3000/auth/callback. - A person who decides. This person needs the permission
jit.approve. The setup script creates the role Agent reviewer, which holds only this permission. WithAPPROVER_EMAIL, it gives the role to that person. Administrators hold the permission already. - The approver must not own the agent: the owner of an agent cannot decide the requests of that agent.
- An agent that asks. The agent of Ask a person for a permission, for one task does, and its setup gives the agent to another owner.
- 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:clients:read, admin:clients:write, admin:roles:read, admin:roles:write and admin:users:read. The inbox itself uses the token of the approver. |
APPROVER_EMAIL | Optional, for the setup script: the email address of a person who gets the role "Agent reviewer". |
LUMOAUTH_CLIENT_ID | The client ID of the application "Approvals desk". The setup script prints it. |
PORT | Optional. The port of the server, and of the redirect address that the setup script registers. Default: 3000. |
SESSION_SECRET | Optional. The secret that signs the session cookie. Without it, every start of the server signs everybody out. |
APPROVER_ACCESS_TOKEN | For inbox.sh only: the access token of a signed-in approver, with the scope jit:approve. Your app gets it at sign-in. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
APPROVER_EMAIL=riley.park@example.com node approvals/inbox-in-your-app/setup.mjs
setup.mjs
// Creates what the inbox needs: the application through which approvers sign
// in, and a role that lets a person decide the requests of agents. Run it
// again at any time.
//
// node approvals/inbox-in-your-app/setup.mjs
// APPROVER_EMAIL=riley.park@example.com node approvals/inbox-in-your-app/setup.mjs
//
// The API key needs the scopes admin:clients:read, admin:clients:write,
// admin:roles:read, admin:roles:write and admin:users:read.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';
const redirectUris = [`http://localhost:${process.env.PORT ?? 3000}/auth/callback`];
const application = await ensure('/admin/clients', (c) => c.name === 'Approvals desk', {
name: 'Approvals desk',
redirectUris,
// A public application signs in with PKCE and has no secret to keep.
isConfidential: false,
// jit:approve lets the token of an approver list and decide requests.
scopes: ['openid', 'profile', 'email', 'jit:approve'],
});
// A second run with another port replaces the redirect address.
await call('PATCH', `/admin/clients/${application.clientId}`, { redirectUris });
// An approver needs the permission jit.approve, and nothing else.
const role = await ensure('/admin/roles', (r) => r.slug === 'agent-reviewer', {
name: 'Agent reviewer',
slug: 'agent-reviewer',
description: 'May approve and deny the requests of agents.',
});
await call('PUT', `/admin/roles/${role.id}/permissions`, { permissions: ['jit.approve'] });
// Adds the role to one person, and keeps the other roles of that person.
const email = process.env.APPROVER_EMAIL;
if (email) {
const approver = (await list('/admin/users')).find((u) => u.email === email);
if (!approver) throw new Error(`No user with the email address ${email}.`);
await call('POST', `/admin/roles/${role.id}/users`, { userId: approver.id });
console.log(`${email} holds the role "${role.name}".`);
}
console.log(`The application "${application.name}" and the role "${role.name}" are ready.`);
printEnv({ LUMOAUTH_CLIENT_ID: application.clientId });
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 version was run with the agent of the recipe for just-in-time permissions. An approver signed in, saw the request, and approved or denied it. A person without the role got 403.
- Node.js
- Python
- curl
// The server side of an approvals inbox in your own app. An approver signs
// in, and the server lists and decides the requests of agents with the token
// of that person.
//
// node approvals/inbox-in-your-app/js/server.mjs
import { randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import express from 'express';
import session from 'express-session';
import { LumoAuthBackend, lumoAuthMiddleware, requireAuth } from '@lumoauth/express';
const baseUrl = process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev';
const orgId = process.env.LUMOAUTH_ORG_ID;
const port = process.env.PORT ?? 3000;
const app = express();
app.use(express.json());
app.use(
session({
// Use a fixed secret and a real session store outside a test.
secret: process.env.SESSION_SECRET ?? randomBytes(32).toString('hex'),
resave: false,
saveUninitialized: false,
// A browser does not send a lax cookie with a form that another site
// posts. So no other site can approve a request in the name of the approver.
cookie: { httpOnly: true, sameSite: 'lax' },
}),
);
// Adds /auth/login, /auth/callback and /auth/logout. The scope jit:approve
// makes the token of the approver valid for the calls below.
app.use(
lumoAuthMiddleware({
baseUrl,
organization: orgId,
clientId: process.env.LUMOAUTH_CLIENT_ID,
scope: 'openid profile email jit:approve',
}),
);
// The token of the signed-in approver. The middleware keeps it in the session.
const approverToken = (req) => req.session.__lumoAuth.tokens.access_token;
const approver = requireAuth({ scopes: ['jit:approve'] });
app.get('/', (req, res) => {
if (!req.user) return res.redirect('/auth/login');
res.sendFile(fileURLToPath(new URL('../inbox.html', import.meta.url)));
});
// The queue: the requests that this person may decide.
app.get('/api/approvals', approver, async (req, res) => {
const lumo = new LumoAuthBackend({ baseUrl, orgId, secretKey: approverToken(req) });
try {
res.json(await lumo.jit.listPendingRequests());
} catch (error) {
// A person without jit.approve gets 403, unless a request waits for their own consent.
res.status(error.statusCode ?? 500).json(error.body ?? { error: error.code });
}
});
// A decision. The SDK has no call for it, so this is plain HTTP.
app.post('/api/approvals/:id/:decision', approver, async (req, res) => {
const { id, decision } = req.params;
if (decision !== 'approve' && decision !== 'deny') return res.status(404).end();
if (!req.is('application/json')) return res.status(415).end();
const note = req.body?.note || undefined;
const answer = await fetch(`${baseUrl}/orgs/${orgId}/api/v1/jit/${decision}/${encodeURIComponent(id)}`, {
method: 'POST',
headers: { Authorization: `Bearer ${approverToken(req)}`, 'Content-Type': 'application/json' },
// Notes and reasons stay inside the organization. The agent does not see them.
body: JSON.stringify(decision === 'approve' ? { notes: note } : { reason: note }),
});
const result = await answer.json();
console.log(`${id}: ${result.status ?? result.error}`);
// LumoAuth checks who may decide. Pass its answer on, also a refusal.
res.status(answer.status).json(result);
});
app.listen(port, () => console.log(`inbox: http://localhost:${port}`));
<!doctype html>
<!-- A bare page for a first test of the server. In a React app, the
approvals inbox pattern shows the same list. -->
<meta charset="utf-8">
<title>Approvals</title>
<h1>Approvals</h1>
<ul id="list"></ul>
<script>
async function load() {
const rows = await (await fetch('/api/approvals')).json();
const items = rows.map((row) => {
const item = document.createElement('li');
const { type, actions = [], identifier = '' } = row.authorization_details;
// An agent writes these texts, so the page shows them as text, never as HTML.
item.textContent = `${row.agent_name}: ${actions.join(', ')} ${type} ${identifier} (${row.risk_level}). ${row.justification ?? ''} `;
for (const decision of ['approve', 'deny']) {
const button = document.createElement('button');
button.textContent = decision;
button.onclick = async () => {
await fetch(`/api/approvals/${row.request_id}/${decision}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ note: 'Decided in the approvals desk.' }),
});
load();
};
item.append(button);
}
return item;
});
document.getElementById('list').replaceChildren(...items);
}
load();
</script>
node approvals/inbox-in-your-app/js/server.mjs
"""The server side of an approvals inbox in your own app. An approver signs
in, and the server lists and decides the requests of agents with the token
of that person.
python approvals/inbox-in-your-app/python/server.py
"""
import os
import secrets
from pathlib import Path
import requests
import uvicorn
from fastapi import Body, Depends, FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from lumoauth import LumoAuth, LumoAuthApiError
from lumoauth.fastapi import get_current_user, lumo_auth_router, require_auth
from starlette.middleware.sessions import SessionMiddleware
base_url = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev")
org_id = os.environ["LUMOAUTH_ORG_ID"]
port = int(os.environ.get("PORT", "3000"))
app = FastAPI()
# Use a fixed secret outside a test. A browser does not send the lax cookie
# with a form that another site posts. So no other site can approve a request
# in the name of the approver.
app.add_middleware(
SessionMiddleware,
secret_key=os.environ.get("SESSION_SECRET") or secrets.token_hex(32),
same_site="lax",
)
# Adds /auth/login, /auth/callback and /auth/logout. The scope jit:approve
# makes the token of the approver valid for the calls below.
app.include_router(
lumo_auth_router(
base_url=base_url,
organization=org_id,
client_id=os.environ["LUMOAUTH_CLIENT_ID"],
scope="openid profile email jit:approve",
),
prefix="/auth",
)
approver = require_auth(scopes=["jit:approve"])
def approver_token(request: Request) -> str:
"""The token of the signed-in approver. The router keeps it in the session."""
return request.session["__lumoauth"]["tokens"]["access_token"]
@app.get("/")
def page(request: Request):
if get_current_user(request) is None:
return RedirectResponse("/auth/login")
return FileResponse(Path(__file__).parent.parent / "inbox.html")
@app.get("/api/approvals", dependencies=[Depends(approver)])
def approvals(request: Request):
"""The queue: the requests that this person may decide."""
lumo = LumoAuth(base_url=base_url, org_id=org_id, token_provider=lambda: approver_token(request))
try:
return lumo.jit.pending()
except LumoAuthApiError as error:
# A person without jit.approve gets 403, unless a request waits for their own consent.
return JSONResponse(error.body or {"error": error.code}, status_code=error.status_code or 500)
@app.post("/api/approvals/{request_id}/{decision}", dependencies=[Depends(approver)])
def decide(request: Request, request_id: str, decision: str, body: dict = Body(default={})):
"""A decision. The SDK has no call for it, so this is plain HTTP."""
if decision not in ("approve", "deny"):
raise HTTPException(status_code=404)
if request.headers.get("content-type", "").split(";")[0] != "application/json":
raise HTTPException(status_code=415)
note = body.get("note") or None
answer = requests.post(
f"{base_url}/orgs/{org_id}/api/v1/jit/{decision}/{request_id}",
headers={"Authorization": f"Bearer {approver_token(request)}"},
# Notes and reasons stay inside the organization. The agent does not see them.
json={"notes": note} if decision == "approve" else {"reason": note},
timeout=30,
)
result = answer.json()
print(f"{request_id}: {result.get('status') or result.get('error')}", flush=True)
# LumoAuth checks who may decide. Pass its answer on, also a refusal.
return JSONResponse(result, status_code=answer.status_code)
if __name__ == "__main__":
print(f"inbox: http://localhost:{port}", flush=True)
uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
<!doctype html>
<!-- A bare page for a first test of the server. In a React app, the
approvals inbox pattern shows the same list. -->
<meta charset="utf-8">
<title>Approvals</title>
<h1>Approvals</h1>
<ul id="list"></ul>
<script>
async function load() {
const rows = await (await fetch('/api/approvals')).json();
const items = rows.map((row) => {
const item = document.createElement('li');
const { type, actions = [], identifier = '' } = row.authorization_details;
// An agent writes these texts, so the page shows them as text, never as HTML.
item.textContent = `${row.agent_name}: ${actions.join(', ')} ${type} ${identifier} (${row.risk_level}). ${row.justification ?? ''} `;
for (const decision of ['approve', 'deny']) {
const button = document.createElement('button');
button.textContent = decision;
button.onclick = async () => {
await fetch(`/api/approvals/${row.request_id}/${decision}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ note: 'Decided in the approvals desk.' }),
});
load();
};
item.append(button);
}
return item;
});
document.getElementById('list').replaceChildren(...items);
}
load();
</script>
python approvals/inbox-in-your-app/python/server.py
#!/bin/sh
# The calls of an approvals inbox, with the access token of an approver.
# Needs curl and jq.
#
# sh approvals/inbox-in-your-app/http/inbox.sh the queue
# sh approvals/inbox-in-your-app/http/inbox.sh approve jit_… a decision
# sh approvals/inbox-in-your-app/http/inbox.sh deny jit_…
set -eu
API="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1"
if [ $# -eq 0 ]; then
# The queue: the requests that this person may decide.
curl --silent --show-error "$API/jit/pending" \
--header "Authorization: Bearer $APPROVER_ACCESS_TOKEN" |
jq -r '(.pending_requests // [])[] | .authorization_details as $d |
"\(.request_id) \(.agent_name): \($d.actions // [] | join(", ")) \($d.type) \($d.identifier // "") (\(.risk_level))"'
exit 0
fi
# A decision: "approve" or "deny", and the ID of the request. A note or a
# reason stays inside the organization. The agent does not see it.
case "$1" in
approve) body='{"notes": "Decided in the approvals desk."}' ;;
deny) body='{"reason": "Decided in the approvals desk."}' ;;
*) echo "usage: inbox.sh [approve|deny jit_…]" >&2; exit 2 ;;
esac
curl --silent --show-error --request POST "$API/jit/$1/$2" \
--header "Authorization: Bearer $APPROVER_ACCESS_TOKEN" \
--header "Content-Type: application/json" \
--data "$body" | jq -r --arg id "$2" '"\(.request_id // $id): \(.status // .error)"'
sh approvals/inbox-in-your-app/http/inbox.sh
The two servers do the same: they add the routes for sign-in, GET /api/approvals for the list, and POST /api/approvals/{id}/approve or /deny for a decision. inbox.html is a bare page for a first test. In a React app, the approvals inbox pattern shows the same list. The curl script shows the same calls of the API, for a server in another language.
To try it:
- Start a server, and open
http://localhost:3000. Sign in as the approver. - In a second terminal, run the agent of the recipe for just-in-time permissions. It stops at "waiting for a person".
- Reload the page. It shows the request of "Invoice agent": the action
approve, the typeinvoices, the recordINV-7741and the reason. - Click approve or deny.
Check the result
inbox: http://localhost:3000
jit_4655efb5727b7a9748026588321611f3: approved
- The agent prints
request: approvedand collects its token. After deny, it printsrequest: denied. - The request leaves the list. A second decision on it, from any approver, gets
invalid_requestwith "Request is not pending approval". - A person without
jit.approvegets the status 403 andinsufficient_permissionsfor the list. - Open Audit logs under Security in the portal. The event
jit.permission_approvednames the approver. sh approvals/inbox-in-your-app/http/inbox.shprints one line for each waiting request, such asjit_4655… Invoice agent: approve invoices INV-7741 (low).
Limits
- The list does not change by itself. To learn of a new request at once, subscribe a webhook to the event
jit.approval_required, and reload the list when it arrives. Receive webhooks shows a receiver. - The list holds the 50 newest requests that the person may decide. Expired requests are left out.
- LumoAuth allows 60 calls in a minute for each approver, separately for the list, for approve and for deny.
- A note of the approver stays in the organization: the audit log and the inbox of the portal show it, the agent does not.
- The portal and the mobile app can decide several requests at once. The API decides one request in each call.