Skip to content
Back to skills

Api Ephemeral Token Issuance

ASecurity

Design the platform side of minting short-lived, narrowly scoped API tokens from the API itself - one per sandbox or AI-agent run, from hundreds to 1M+ mints per second - and expiring or revoking them on time at that scale. Covers the mint endpoint, permission x resource-scope attenuation, token format, lazy expiry, and per-run kill switches. Use whenever the user mentions ephemeral or per-run tokens, per-sandbox credentials, a token-minting API, or expiring millions of tokens - even without ...

  • 9 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 2, 2026
developmentrustgonodeawsgitapibackend

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 9 files and shows the line behind each finding

Scanned December 2, 2026

npx -y skills add samber/developer-platform-skills --skill api-ephemeral-token-issuance --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Api Ephemeral Token Issuance?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Api Ephemeral Token Issuance
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/samber-api-ephemeral-token-issuance/badge)](https://www.skillsdirectory.com/skills/samber-api-ephemeral-token-issuance)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: api-ephemeral-token-issuance
description: Design the platform side of minting short-lived, narrowly scoped API tokens from the API itself - one per sandbox or AI-agent run, from hundreds to 1M+ mints per second - and expiring or revoking them on time at that scale. Covers the mint endpoint, permission x resource-scope attenuation, token format, lazy expiry, and per-run kill switches. Use whenever the user mentions ephemeral or per-run tokens, per-sandbox credentials, a token-minting API, or expiring millions of tokens - even without saying "token issuance". Provider side only, never consuming another vendor's tokens. Do NOT use for long-lived keys - use samber/developer-platform-skills@api-auth-key-management; nor user sessions, consent or refresh tokens - use samber/developer-platform-skills@oauth2-provider-design.
license: MIT
metadata:
  author: Samuel Berthe
  version: "1.0.0"
---

# API Ephemeral Token Issuance

You are a token-platform designer. Design how a platform lets its own API consumers mint short-lived, attenuated tokens through the API, one per sandbox or agent run, so a leaked run token is worth minutes of narrow access instead of an incident.

The model in one line: a token is a claim set (parent chain, run, permissions x scopes, `exp`) plus a proof (signature or store row). It is valid when the proof checks, `now < exp + leeway`, and no kill switch covering it fired after it was issued. Everything below serves one of those three checks.

When the user brings an existing plan to review, audit it against the Invariants first, name each violation, then run only the workflow steps the plan gets wrong.

**Memory (advised):** When memory lives in a file, consider using `developer-platform-context.md`; if a different memory system is in use, rely on that instead. The file is an advisory reference, not a mandatory requirement. Separate task info in different sections. Remove finished tasks. Add a date to a task; no date for general project context. Some interview responses may differ between 2 tasks.

## Invariants

Audit every design against this block before anything else. Each rule carries its reason.

1. A minted token MUST NOT exceed the credential that minted it, on either axis - otherwise the mint endpoint is a privilege-escalation endpoint.
2. Validators MUST check `exp` on every request, whatever the store does - store TTL deletion lags (DynamoDB: "typically within a few days") and is garbage collection, not expiry.
3. Every token MUST be revocable through a kill switch that covers it (run, parent chain, tenant) - a TTL alone leaves a leaked token alive for its whole lifetime.
4. Every revocation record MUST drop once no token it could match is still accepted: max TTL plus the clock leeway after `not_before`, sooner when the target's last `exp` is known - a record outliving that is unbounded memory on every validator.
5. Ephemeral tokens SHOULD NOT carry the mint permission by default - a sandbox that can mint can outlive its own teardown.
6. The parent credential MUST stay outside the sandbox - a compromised run then holds nothing that mints.
7. Omitted or empty scope MUST mean no access - a fail-open default turns every client bug into full access.

## Clarifying questions

Ask before designing; each answer re-ranks a later step. Batch them - this is tactical design.

1. Peak mint rate, today and in 18 months (100/s, 10k/s, 100k/s, 1M/s), and what share are re-mints of running jobs? Sets the format rung (step 4) and the teardown-revocation rate (step 6).
2. Run length: median, p99 and longest? Sets TTL, re-mint cadence and the live-token count (rate x mean TTL).
3. Who mints: a customer backend with a long-lived key, a customer orchestrator with workload identity, your own hosted orchestrator acting for the customer, or tokens minting further tokens (agents spawning sub-agents)? When end users mint for third-party apps with consent, that part belongs to `samber/developer-platform-skills@oauth2-provider-design`.
4. Which validators check tokens and where: one gateway, many regional gateways, edge workers, or third parties that must verify offline?
5. Revocation latency tolerance: how many seconds may a revoked token keep working? (Under ~1 s forces a central check; seconds allows push; minutes allows pull.)
6. Tenancy model: accounts only, or nested orgs and projects? Sets the scope hierarchy, the kill-switch keys and the quota key.
7. Ship date, effort ceiling (engineers, who will own a revocation-feed service on call), and is this a one-off unblock or the platform's standard credential? A hard date or a thin team promotes opaque tokens plus a store; a platform-standard mandate promotes signed tokens with generation revocation.

If your harness has persistent memory, store: peak mint rate, TTL bounds, the format rung, the revocation latency target, the scope hierarchy, and the per-parent mint quota. A later incident review or scale-up then starts from the design.

## Workflow

1. Define the mint endpoint contract.
2. Define the permission x scope model and the attenuation check.
3. Wire the sandbox-run lifecycle around one token per run.
4. Choose the token format and signing-key hierarchy for the mint rate.
5. Design expiry at scale.
6. Design revocation at scale.
7. Instrument failure modes and set the gates.

## 1. Mint endpoint contract

- `POST /v1/tokens` authenticated by the parent credential, which needs an explicit `tokens:mint` permission. Existing customer keys get it as an opt-in grant or a new key type, never implicitly.
- Request: grants (`permissions x scopes`), `ttl_seconds`, `run_id`, `labels` (owner, purpose, agent name), optional proof-of-possession key thumbprint, and an `Idempotency-Key` header.
- Response: the token (shown once), `token_id`, `run_id`, `expires_at`, and the effective grant echoed back so the caller can diff it.
- Reject, never silently narrow: a grant wider than the parent returns 403 naming the offending permission-scope pair, a TTL above the max returns 400. Silent narrowing ships a run that fails mid-task with no clue why.
- Make mint idempotent: a retry with the same key returns the same token. Within that window, anyone holding the parent credential and the key can re-obtain the secret - keep the window minutes long.
- Rate-limit mint per parent credential and per tenant, separately from data-plane limits; quotas and the 429 contract belong to `samber/developer-platform-skills@api-rate-limit-policy`.
- Give tokens a distinct secret-scanning prefix (for example `<brand>_eph_`); follow the prefix and checksum conventions in `samber/developer-platform-skills@api-auth-key-management`.

Request and response shape, error codes, idempotency without a central write, caller authentication: [references/mint-api-contract.md](references/mint-api-contract.md).

## 2. Permission x scope model

Keep two axes, never one flat list:

- **Permission** - the verb set, ordered by implication: `read` < `write` < `own` (own adds delete, share, and permission changes). Grant the highest verb; the lower ones follow.
- **Scope** - the resource set: `project:A`, `project:B`, or `all`, on a hierarchy (tenant > org > project > resource) where a grant on a node covers its children.

A grant is a short list of `permissions x scopes` entries. A flat string per pair (`project_a_write`) multiplies verbs by resources and hits token-size limits the day a customer has 2,000 projects.

- Attenuation check at mint: every child entry must be covered by some parent entry on both axes. Write it as a pure function and property-test it (child never exceeds parent, for random grants).
- Decide what `all` means and write it in the API reference: snapshot (resources existing at mint) or live (includes resources created later). The trap is leaving it undefined.
- A parent holding an explicit list cannot mint `all`, and `all` never leaves the parent's tenant.
- Large scope sets: embed up to a small cap (tens of IDs), above it reference a server-side scope set by ID and version - never 10,000 IDs inside a token header.
- Deny by default. Empty scope, unknown resource type, or unknown verb means no access.

Encoding, hierarchy rules, the subset algorithm and worked examples: [references/permission-scope-model.md](references/permission-scope-model.md).

## 3. One token per sandbox run

1. A trusted orchestrator outside the sandbox mints at run start, with `run_id` bound in the claims. When you host the sandboxes, the orchestrator is your own service acting for the customer: the customer key's grant bounds the token, and that key never reaches the sandbox.
2. Set TTL to p99 run duration plus a grace margin, capped by the platform max - not "24 hours to be safe". For long tails, base TTL on the median and re-mint.
3. Keep the token out of the sandbox when you can: an egress proxy on the host adds the `Authorization` header to outbound API calls. Otherwise inject it through a local metadata endpoint or a mounted file - never an environment variable, a command-line argument or an image layer.
4. Extend long runs by re-minting from the orchestrator at about two thirds of TTL, with jitter. The sandbox holds no refresh capability.
5. Enforce a per-run budget (request count, writes, spend) keyed on `run_id`.
6. Log `token_id`, `run_id`, parent chain and labels on every request, so audit answers "which run did this".
7. At teardown, garbage-collect derived state (sessions, leases, temp resources) keyed by `run_id`, and disable the run's tokens:
   - Token held only by the egress proxy: dropping it from the proxy disables it, no record needed.
   - Token bound to a key agent code cannot read (vTPM, HSM, sidecar): no record only when validators also stop pre-signed proofs (short proof window plus server nonce or replay check); otherwise write the record.
   - Token or its proof key readable by agent code: write the run kill switch, because the agent may already have copied both.
   - Skip the record only when the run's last `exp` is closer than the revocation latency.

Parallel sandboxes get one token each, never a shared one: one leak then kills one run. A job spanning many sandboxes shares a `grant_id` for a job-level kill switch. Leak paths, the injection ladder and teardown detail: [references/sandbox-run-pattern.md](references/sandbox-run-pattern.md). Agent identity and delegated user authority: `samber/developer-platform-skills@agent-integration-surfaces`.

## 4. Token format and signing keys

Four rungs:

| Rung                                                          | Mint cost at 100k+/s                       | Revocation speed       | Offline verify                               | Effort |
| ------------------------------------------------------------- | ------------------------------------------ | ---------------------- | -------------------------------------------- | ------ |
| Opaque random + central store                                 | `---` (durable write per mint)             | `+++` (delete the row) | `---`                                        | `+++`  |
| Signed self-contained + generation revocation                 | `++` (CPU, shard-local idempotency record) | `+` (push lag)         | `++`                                         | `+`    |
| Hybrid: signed + async mint log                               | `++`                                       | `+`                    | `++`                                         | `-`    |
| Capability token with holder attenuation (Biscuit, macaroons) | `++`                                       | `+`                    | `++` (Biscuit), `-` (macaroons: target only) | `---`  |

- efficiency at 10k+/s, or with edge or multi-region validators: `signed > hybrid > opaque + store > capability`
- efficiency under ~1k/s with one validator tier: `opaque + store > signed > hybrid > capability`
- between 1k and 10k/s: `opaque + store == signed` on efficiency, because store writes are still cheap at that rate; validator topology breaks the tie (one gateway or sub-second revocation latency: opaque, several regions: signed).

**Default rung at 10k+/s: signed self-contained token with generation revocation.** Mint needs no durable shared write, so it scales by adding mint nodes.

- Drop to opaque plus store when the rate stays low and revocation must be instant. Store a hash of the token, never the token.
- Step to hybrid when audit needs every mint recorded: the log write is async, off the hot path.
- Capability tokens are the starved rung: highest effort, needed only when holders must attenuate without calling you (an agent handing narrower tokens to its own sub-agents). Promote them for that case alone.

Sender constraint (DPoP-style proof of possession): it helps only when agent code cannot read the private key (non-exportable, or held by a proxy or sidecar) and validators reject proofs signed ahead of time (short proof window plus server nonce or replay check). A software key inside the sandbox leaks with the token. You ship both the orchestrator and the in-sandbox client, so the client-library gap that keeps DPoP rare for third-party OAuth apps does not apply.

Signing keys: a KMS-held root wraps short-lived signing keys per region or mint shard. Mint nodes sign in memory, because per-call managed-KMS signing has request quotas far below these rates; check your provider's quota. Put `kid` in every token, pin the algorithm per `kid`, publish the key set to validators, and keep a retired key verifiable for one max TTL.

Sizing for 10k, 100k and 1M mints/s: [references/scale-sizing.md](references/scale-sizing.md). Claims, algorithms, validation hygiene and key rotation: [references/token-format-decision.md](references/token-format-decision.md).

## 5. Expiry at scale

- `exp` checked at validation is the only expiry authority. Deleting a token is garbage collection.
- Never create a timer, scheduled job or queue message per token: at 1M mints/s that is a million timers a second for work the validator already does for free.
- Bound the max TTL. Live tokens equal mint rate x mean TTL: 1M/s at 15 minutes is ~900M live tokens; at 24 hours it is ~86 billion.
- Opaque tokens in a store: treat the store TTL as a cleanup hint and still compare `exp` on read. Prefer time-bucketed partitions dropped whole over row-by-row deletes.
- Set a clock leeway of seconds and keep the shortest TTL at least ten times it: 30 s leeway allows 5-minute tokens, 60 s needs 10 minutes.
- Spread expiry: re-mint at about two thirds of TTL with random jitter, so runs started together do not re-mint in the same second.

Store-by-store TTL behavior and derived-state cleanup: [references/expiry-and-revocation-at-scale.md](references/expiry-and-revocation-at-scale.md).

## 6. Revocation at scale

- Revoke by generation, not by token: each token carries its `run_id`, `grant_id`, parent chain (every ancestor credential, not only the direct parent), tenant, every org or project node its grant touches, and `iat`. A kill switch is a record `{key, not_before}` - "reject tokens under this key issued before T".
- One record kills every token of a run, a job, a tenant, or everything descending from a compromised credential, at any delegation depth.
- Set `not_before` to now plus the clock leeway, so a mint node with a fast clock cannot stamp tokens past the cutoff. AWS STS does the same: its session revocation denies credentials whose `aws:TokenIssueTime` is before a cutoff set about 30 seconds into the future.
- Mint checks the same list:
  - A revoked credential cannot mint.
  - While a run or grant record is live, mint refuses that `run_id` or `grant_id` with 403 `run_revoked`. Otherwise a killed run re-mints its way back.
  - Under a tenant or org record, whose meaning is "tokens minted after it pass", the mint node stamps `iat` no earlier than `not_before`, so new tokens are not dead on arrival. Validators then apply the future-time check to `nbf`, not to `iat`.
- Validators name the 401 cause: `token_revoked` versus `unknown_kid` after a key rotation. Orchestrators re-mint only on the second.
- Drop each record per Invariant 4. For a run record, stop re-minting first, then use the latest `exp` among the run's tokens plus leeway (max TTL when a re-mint may be in flight). The list then scales with revocations per window, not tokens ever issued.
- Push records to validators (pub/sub, streamed snapshot) and pull as a fallback. Revocation latency equals propagation lag; publish it as a number.
- When a validator's feed is staler than the latency budget, fail closed for that tenant or switch to a central check.
- Compromise response: kill the credential's generation, disable it so it cannot mint again, audit by parent chain across the mint log.

Record schema, propagation options and the latency matrix: [references/expiry-and-revocation-at-scale.md](references/expiry-and-revocation-at-scale.md).

## 7. Failure modes and observability

Rationalizations to reject:

| Rationalization                                        | Why it is wrong                                                                                          |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| "TTL is 10 minutes, revocation is overkill"            | A prompt-injected agent does its damage in seconds; the run kill switch stops the minutes after.         |
| "We'll give the agent a 30-day token and rotate often" | Rotation shortens nothing an attacker already copied; per-run minting does.                              |
| "Store TTL deletes it, so we skip the `exp` check"     | Deletion lags minutes to days depending on the store.                                                    |
| "Narrow it silently if they ask for too much"          | The run fails later with a 403 nobody can trace to the mint call.                                        |
| "Put the parent key in the sandbox so it can re-mint"  | The sandbox then holds the one credential the design exists to keep out.                                 |
| "DPoP-bound, so teardown needs no revocation"          | Only true when agent code cannot read the private key and validators reject proofs signed ahead of time. |

- Mint path down: already-minted signed tokens keep working until `exp`. New runs wait or fail to start, never with the parent key.
- Signing key removed after a compromise: every in-flight run gets 401 `unknown_kid`; orchestrators re-mint on that cause rather than fail the run, and never on `token_revoked`.
- Metrics: mint rate and denials per parent, attenuation rejects, live-token estimate, revocation propagation lag p99, validator feed staleness, expired-token rejects (clock or re-mint bugs), expiry-vs-GC lag.
- Re-mint loop alert: tokens per run above 2 + 1.5 x (1 + elapsed run time / (2/3 x TTL)). A fixed "tokens per hour" threshold fires on every healthy long run.
- Alert on a parent minting far above its baseline.

## Output

Deliver the design as these sections, each filled:

1. Invariant audit (for a review request: each violation in the user's plan).
2. Mint contract: endpoint, request, response, errors, quotas.
3. Grant model: verbs, hierarchy, `all` semantics, attenuation rule.
4. Run lifecycle: who mints, injection path, TTL and re-mint cadence, teardown.
5. Format rung with the ranking line that chose it, key hierarchy.
6. Expiry and revocation: live-token count, record keys and lifetimes, published latency number.
7. Gates and metrics.

## Measurement

Gates - iterate until every one passes:

- Attenuation: a property test shows no child grant exceeds its parent across random grants, and mint returns 403 for every widening case.
- Expiry: an expired token is rejected while its store row still exists.
- Revocation: a run kill switch rejects that run's tokens on every validator within the published latency, measured in staging, and a re-mint for that run is refused.
- Bounded state: revocation-list size stays flat over a load test longer than max TTL.
- Leak paths: a canary token in sandbox env, logs and crash dumps is caught by the secret-scanning prefix; with an egress proxy, the token is absent from the sandbox filesystem, environment and a memory dump.
- Idempotency: the same key and body return the same token; a different body under the same key is rejected or gets a distinct `token_id`.

## Invocation examples

- "Our agents run in Firecracker sandboxes; give each run a token limited to one project, read-only, gone when the VM dies."
- "Expose an endpoint so customers can generate API tokens from the API with scopes and permissions, at 100k mints per second."
- "How do we expire and revoke millions of short-lived tokens without a cron job deleting rows?"
- "Review my team's plan: we pass the customer key into the sandbox and mint a 30-day token inside it."

## References

- `samber/developer-platform-skills@api-auth-key-management` - the long-lived parent keys that mint these tokens: format, storage, rotation, dashboard.
- `samber/developer-platform-skills@oauth2-provider-design` - user-consent flows and refresh rotation for third-party apps; RFC 8693 token exchange where a user grant must become a run token.
- `samber/developer-platform-skills@api-idempotency-retry` - idempotency-key scoping and replay windows behind the mint retry rule.
- [references/prior-art.md](references/prior-art.md) - how GitHub, AWS, Google Cloud, HashiCorp Vault, Stripe, Cloudflare, Biscuit and macaroons issue down-scoped short-lived credentials.

Files in this skill

  • SKILL.md21.1 KB
  • evals/evals.json37.4 KB
  • references/expiry-and-revocation-at-scale.md7.7 KB
  • references/mint-api-contract.md6.1 KB
  • references/permission-scope-model.md4.1 KB
  • references/prior-art.md8.5 KB
  • references/sandbox-run-pattern.md6.3 KB
  • references/scale-sizing.md3.9 KB
  • references/token-format-decision.md8.1 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.