Box credential resolution, Client Credentials Grant, JWT server auth,
the per-run token cache, and the store-backed keeper for Box's
single-use OAuth refresh tokens. Usually used indirectly through
::box::api/request.
Credential sources. Per-call opts win over context. When opts
carries a primary credential (token, account, refresh-token,
jwt-config or client-secret), context credentials are ignored for
that call, except that box.client.id / box.client.secret (your
app's own keys) and box.oauth.store still fill in. Otherwise context
is used, with opts.user-id / opts.enterprise-id applied on top.
Within one source the order is: access token, OAuth (keeper or
on-refresh), JWT, CCG.
| Credential | opts keys | Context variables |
|---|---|---|
| Access token | token | box.access.token |
| OAuth, store keeper | account (+ optional seed refresh-token), token-store | box.oauth.account, box.oauth.refresh-token (seed), box.oauth.store |
| OAuth, you persist | refresh-token + on-refresh (a Fn) | - |
| JWT server auth | jwt-config, private-key, user-id / enterprise-id | box.jwt.config, box.jwt.private-key, box.user.id / box.enterprise.id |
| Client Credentials Grant | client-id, client-secret, user-id / enterprise-id | box.client.id, box.client.secret, box.user.id / box.enterprise.id |
OAuth refresh needs the app's client-id and client-secret too
(from opts or box.client.id / box.client.secret).
as-user (or box.as-user) adds the As-User header to every call:
an admin or service account acting as a managed user.
Single-use refresh tokens. Box access tokens last about 60 minutes; a refresh token lasts 60 days and works once. Every refresh returns a new pair, and the old refresh token is dead. Losing the new one means the user must consent again. Two ways to keep it:
- The keeper (
account): tokens live in a::hot::storeMap (box-oauth-tokensunlesstoken-store/box.oauth.storenames another), one entry per account. A refresh first claims a short lease on the entry with::hot::store/put-if(compare-and-set), so two runs never spend the same refresh token, then writes the new pair withput-ifagainst the claimed value. The run that loses the race gets the winner's access token, or, while the winner is still refreshing, aTokenErrorwitherror-code: "refresh_in_progress"that::box::api/is-retryabletreats as retryable. Store a pair once withsave-tokensafter::box::oauth/exchange-code; a contextbox.oauth.refresh-tokenonly seeds an empty entry (put-if-missing) and is ignored after that.on-refreshis still called after each refresh, as a notification. - You persist (
refresh-token+on-refresh): each refresh callson-refresh(tokens)with Box's token response (access_token,refresh_token,expires_in); savetokens.refresh_tokenbefore the run ends. A failing callback fails the call. Within a run the rotated pair is cached, so later calls never reuse the spent token. Concurrency is then yours to handle. Or call::box::oauth/refresh-tokensyourself and passtokenper call.
A refresh-token in opts with neither account nor on-refresh
is refused: its replacement would be lost.
Per-call rules. A credential key (token, account,
refresh-token, client-id, client-secret, jwt-config,
private-key) that is in opts but blank or null is an error naming
the key, never a fallback to context. Credentials from opts,
including the secrets inside a jwt-config, are marked as secrets
(::hot::ctx/mark-secret), so call records mask them; they are never
written to context. The API roots are context-only (box.api-root,
box.upload-root), so a call cannot redirect credentials.
Token cache. Minted tokens are cached in the run's execution
context (::hot::ctx, stored as secrets) under a key derived from the
credential identity and subject, until expires_in minus 60 seconds.
The cache lives for one run. Explicit access tokens are never cached.
Every token Box returns, and every token the keeper hands back, is
marked as a secret before it leaves this package.
Context Vars
box.access.tokenbox.client.idbox.client.secretbox.enterprise.idbox.user.idbox.jwt.configbox.jwt.private-keybox.oauth.refresh-tokenbox.oauth.accountbox.oauth.storebox.as-user
Values
BLANK_CHECKED_KEYS
BLANK_CHECKED_KEYS: Vec [
"token",
"account",
"refresh-token",
"client-id",
"client-secret",
"jwt-config",
"private-key"
]
CACHE_PREFIX
CACHE_PREFIX: Str "box.token-cache."
CREDENTIAL_KEYS
CREDENTIAL_KEYS: Vec [
"token",
"account",
"token-store",
"on-refresh",
"refresh-token",
"client-id",
"client-secret",
"jwt-config",
"private-key",
"enterprise-id",
"user-id",
"as-user",
"retry",
"force-refresh"
]
DEFAULT_ACCOUNT
DEFAULT_ACCOUNT: Str "default"
DEFAULT_EXPIRES_IN
DEFAULT_EXPIRES_IN: Int 3600
DEFAULT_STORE
DEFAULT_STORE: Str "box-oauth-tokens"
EXPIRY_MARGIN_SECONDS
EXPIRY_MARGIN_SECONDS: Int 60
JWT_GRANT
JWT_GRANT: Str "urn:ietf:params:oauth:grant-type:jwt-bearer"
JWT_LIFETIME_SECONDS
JWT_LIFETIME_SECONDS: Int 45
LEASE_SECONDS
LEASE_SECONDS: Int 30
RECORD_SECRETS
RECORD_SECRETS: Vec [
"access-token",
"refresh-token"
]
REFRESH_TOKEN_TTL_SECONDS
REFRESH_TOKEN_TTL_SECONDS: Int 5184000
RESOLVED_SECRETS
RESOLVED_SECRETS: Vec [
"token",
"refresh-token",
"seed-refresh-token",
"client-secret",
"private-key"
]
SECRET_KEYS
SECRET_KEYS: Vec [
"token",
"refresh-token",
"client-secret",
"private-key"
]
TOKEN_RESPONSE_SECRETS
TOKEN_RESPONSE_SECRETS: Vec [
"access_token",
"refresh_token"
]
Functions
access-token
fn (): Str
fn (opts: Map): Str
Resolve an access token from opts and context. Returns the bearer
token Str, or a TokenError when no credentials are configured or
the token request fails. CCG, JWT and refreshed tokens are cached for
the run.
token ::box::auth/access-token()
// As one managed user, through the CCG app in context
token2 ::box::auth/access-token({user-id: "12345"})
app-keys
fn (opts: Map): Map
The app's {client-id, client-secret} for a call (the same resolver as
credentials): opts.client-id / client-secret first, else
box.client.id / box.client.secret. A TokenError when either is
missing.
Example
app ::box::auth/app-keys({})
app.client-id
as-user
fn (opts: Map): Str?
The As-User user id for a call: opts.as-user, else the box.as-user
context variable, else null.
Example
::box::auth/as-user({as-user: "123"}) // "123"
bearer
fn (creds: Map, opts: Map): Map
Resolve a bearer token for resolved credentials, using the per-run
cache. Returns {token, cache-key, cached} (cached is true when the
token was not minted by this call, so a 401 should evict and retry),
or a TokenError. opts.force-refresh skips cached and stored tokens.
Example
creds ::box::auth/resolve-credentials()
auth ::box::auth/bearer(creds, {})
auth.cached
blank-credential
fn (opts: Map): Str?
The first credential key opts has with a blank or null value, else
null (pure).
Example
::box::auth/blank-credential({account: ""}) // "account"
::box::auth/blank-credential({account: "tenant-42"}) // null
cache-entry
fn (tokens: Map, now: Int): Map
The cached form of a token response (pure): {access-token, expires-at}
(epoch ms, EXPIRY_MARGIN_SECONDS early), plus the rotated
refresh-token when the response carries one.
Example
::box::auth/cache-entry({expires_in: 3600}, 1000).expires-at // 3541000
ccg-body
fn (client-id: Str, client-secret: Str, subject: Map): Map
The Client Credentials Grant form body (pure):
grant_type=client_credentials, client_id, client_secret,
box_subject_type (enterprise or user), box_subject_id.
Example
body ::box::auth/ccg-body(::hot::ctx/get("box.client.id"), ::hot::ctx/get("box.client.secret"), {type: "enterprise", id: "12345"})
body.box_subject_type
claim-record
fn (record: Map, now: Int, lease-id: Str): Map
A record with a refresh lease (pure): lease-until (now + 30 s) and a
unique lease-id.
Example
::box::auth/claim-record({expires-at: 0}, 1000, "lease-1") // {expires-at: 0, lease-until: 31000, lease-id: "lease-1"}
coded-error
fn (message: Str, code: Str): TokenError
A TokenError with one of box's own error-codes.
Example
::box::auth/coded-error("box: no stored tokens", "no_tokens").error-code // "no_tokens"
credentials-from
fn (source: Map): Map
Turn a credential source Map (the opts shape) into resolved
credentials (pure): {kind: "token" | "keeper" | "refresh" | "jwt" | "ccg", ...}. Returns a TokenError when nothing usable is set or a
piece is missing.
Example
creds ::box::auth/credentials-from({token: ::hot::ctx/get("box.access.token")})
creds.kind
ctx-source
fn (): Map
The credential source read from context, in the same shape as opts. A
context refresh token without box.oauth.account belongs to the keeper
account "default".
Example
source ::box::auth/ctx-source()
source.account
evict-token
fn (cache-key: Str?): Bool
Drop a cached token (e.g. after a 401). No-op for a null key.
Example
creds ::box::auth/resolve-credentials()
::box::auth/evict-token(::box::auth/token-cache-key(creds))
forget-tokens
fn (account: Str): Bool
fn (account: Str, opts: Map): Bool
Delete the keeper record for account (e.g. on disconnect, after
::box::oauth/revoke-token). Returns true when one existed.
Example
::box::auth/forget-tokens("tenant-42")
::box::auth/forget-tokens("tenant-42", {token-store: "tenant-tokens"})
has-primary-credential
fn (source: Map): Bool
True when source carries a primary credential: token, account,
refresh-token, jwt-config or client-secret.
Example
::box::auth/has-primary-credential({account: "tenant-42"}) // true
::box::auth/has-primary-credential({user-id: "123"}) // false
is-blank-value
fn (value: Any): Bool
True for null, "", and whitespace-only strings (context placeholders
wire "" for unset env vars).
Example
::box::auth/is-blank-value(" ") // true
::box::auth/is-blank-value("abc") // false
is-fresh
fn (entry: Any, now: Int): Bool
True when an entry (cache or keeper record) has an access token that has not reached its margin-adjusted expiry.
Example
// No access-token, so nothing to reuse
::box::auth/is-fresh({expires-at: 2000}, 1000) // false
::box::auth/is-fresh(null, 1000) // false
jwt-body
fn (assertion: Str, client-id: Str, client-secret: Str): Map
The JWT-bearer grant form body (pure): grant_type, assertion,
client_id, client_secret.
Example
claims ::box::auth/jwt-claims("app-id", {type: "enterprise", id: "123"}, Str(Uuid()), ::jwt/now-seconds())
assertion ::box::auth/sign-assertion(claims, "key-1", ::hot::ctx/get("box.jwt.private-key"))
body ::box::auth/jwt-body(assertion, ::hot::ctx/get("box.client.id"), ::hot::ctx/get("box.client.secret"))
body.grant_type
jwt-claims
fn (client-id: Str, subject: Map, jti: Str, now: Int): Map
The Box JWT assertion claims (pure): iss (client id), sub
(enterprise or user id), box_sub_type, aud (the token URL), jti
(16-128 chars, unique), exp (now + 45 s; Box allows at most 60).
Example
claims ::box::auth/jwt-claims("app-id", {type: "enterprise", id: "123"}, "a-unique-jti-1234", 1000)
claims.exp // 1045
claims.box_sub_type // "enterprise"
jwt-config-secrets
fn (config: Any): Vec
The secret values in a Box app config (a JSON Str or a Map): the whole
Str, boxAppSettings.clientSecret, appAuth.privateKey and
appAuth.passphrase. A malformed config gives just the Str.
Example
secrets ::box::auth/jwt-config-secrets(::hot::ctx/get("box.jwt.config"))
::box::auth/mark-values(secrets)
jwt-header
fn (key-id: Str?): Map
The JWT header (pure): {alg: "RS256", typ: "JWT", kid}, kid being
the app's public key id (omitted when null).
Example
::box::auth/jwt-header("key-1") // {alg: "RS256", typ: "JWT", kid: "key-1"}
::box::auth/jwt-header(null) // {alg: "RS256", typ: "JWT"}
keeper-access-token
fn (creds: Map, force: Bool): Map
The keeper's access token for resolved keeper credentials: the
stored one while fresh, else a refresh under a compare-and-set lease
(see the namespace doc). Returns {access-token, expires-at, refreshed} or a TokenError (refresh_in_progress is retryable;
no_tokens, refresh_token_expired and invalid_grant need the
user to consent again).
Example
creds ::box::auth/resolve-credentials({account: "tenant-42"})
kept ::box::auth/keeper-access-token(creds, false)
kept.refreshed
keeper-plan
fn (record: Any, now: Int, force: Bool): Str
Decide what the keeper does with a stored record (pure): "use" its
fresh access token, "refresh", wait for another run ("busy": a
refresh lease is live), or give up ("missing": no record or no
refresh token; "expired": past the 60-day refresh lifetime).
force skips a fresh access token (after a 401).
Example
::box::auth/keeper-plan(null, 1000, false) // "missing"
// Another run holds the refresh lease
::box::auth/keeper-plan({expires-at: 0, lease-until: 5000}, 1000, false) // "busy"
keeper-record
fn (tokens: Map, now: Int): Map
The keeper's stored form of a Box token response (pure):
{access-token, expires-at, refresh-token, refresh-expires-at, updated-at} (epoch ms). refresh-expires-at is 60 days out, Box's
refresh-token lifetime.
Example
record ::box::auth/keeper-record({expires_in: 3600}, 1000)
record.updated-at // 1000
load-tokens
fn (account: Str): Map?
fn (account: Str, opts: Map): Map?
The keeper record for account ({access-token, expires-at, refresh-token, refresh-expires-at, updated-at}), or null. It holds live
secrets, which are marked here: never log it.
Example
record ::box::auth/load-tokens("tenant-42")
record.refresh-expires-at
// From a named store
other ::box::auth/load-tokens("tenant-42", {token-store: "tenant-tokens"})
is-null(other)
mark-fields
fn (m: Map, names: Vec): Map
Mark the values of names in m as secrets and return m unchanged.
Example
tokens {access_token: ::hot::ctx/get("box.access.token"), expires_in: 3600}
::box::auth/mark-fields(tokens, ["access_token"])
mark-opts
fn (opts: Map): Map
Mark the credentials in a call's opts as secrets and return opts
unchanged.
Example
::box::auth/mark-opts({token: ::hot::ctx/get("box.access.token"), limit: 10})
mark-values
fn (values: Vec): Vec
Register the non-blank values as secrets for this run's call records
(::hot::ctx/mark-secret).
Example
::box::auth/mark-values([::hot::ctx/get("box.access.token"), ::hot::ctx/get("box.client.secret")])
merge-sources
fn (opts: Map, ctx: Map): Map
Pick the credential source for a call (pure): opts (over the app's
client-id / client-secret / token-store from context) when it
carries a primary credential, otherwise context with the opts subject
applied. resolve-credentials passes the live context.
Example
::box::auth/merge-sources({account: "tenant-42"}, {client-id: "app-id"}) // {client-id: "app-id", account: "tenant-42"}
::box::auth/merge-sources({user-id: "1"}, {enterprise-id: "9"}) // {enterprise-id: "9", user-id: "1"}
mint-token
fn (creds: Map): Map
Mint a fresh token response for CCG or JWT credentials (no cache).
Example
creds ::box::auth/credentials-from({client-id: ::hot::ctx/get("box.client.id"), client-secret: ::hot::ctx/get("box.client.secret"), enterprise-id: "12345"})
tokens ::box::auth/mint-token(creds)
tokens.expires_in
normalize-pem
fn (pem: Str): Str
Undo the \\n escaping a PEM picks up in env vars and JSON-in-JSON
(pure); real newlines pass through.
Example
::box::auth/normalize-pem("line1\\nline2") // "line1\nline2"
parse-jwt-config
fn (config: Any, private-key: Any, source: Map): Map
Parse a Box app config (the JSON the Developer Console downloads, as a
Str or Map) into JWT credentials (pure): {kind: "jwt", client-id, client-secret, key-id, private-key, subject}. private-key
(nullable) overrides the config's key; it must be an unencrypted
PKCS#8 (or PKCS#1) PEM. Returns a TokenError when something is
missing or the key is encrypted.
Example
creds ::box::auth/parse-jwt-config(::hot::ctx/get("box.jwt.config"), ::hot::ctx/get("box.jwt.private-key"), {enterprise-id: "12345"})
creds.subject
pem-problem
fn (pem: Str?): Str?
Why a PEM cannot sign Box JWT assertions (pure), or null when it looks
usable. Encrypted keys (the privateKey in a Box-generated config)
cannot be decrypted in Hot.
Example
::box::auth/pem-problem("not a key") // "the private key is not a PEM (expected a BEGIN PRIVATE KEY block)"
present
fn (value: Any): Str?
value as a trimmed Str, or null when blank.
Example
::box::auth/present(" abc ") // "abc"
::box::auth/present("") // null
refresh-token-grant
fn (client-id: Str, client-secret: Str, refresh-token: Str): Map
Spend a refresh token: returns Box's token response with the new
refresh_token (the old one is now dead), or a TokenError
(error-code: "invalid_grant" when it was already used, revoked or
older than 60 days).
Example
tokens ::box::auth/refresh-token-grant(::hot::ctx/get("box.client.id"), ::hot::ctx/get("box.client.secret"), ::hot::ctx/get("box.oauth.refresh-token"))
// The old token is dead: save this one before anything else
tokens.refresh_token
request-token
fn (body: Map): Map
POST a grant body to the Box token endpoint. Returns Box's token
response, with its tokens marked as secrets, or a TokenError (the
error never echoes the body you sent).
Example
body ::box::auth/ccg-body(::hot::ctx/get("box.client.id"), ::hot::ctx/get("box.client.secret"), {type: "enterprise", id: "12345"})
tokens ::box::auth/request-token(body)
tokens.expires_in
resolve-credentials
fn (): Map
fn (opts: Map): Map
Resolve the credentials for a call from opts and context (see the
namespace doc for precedence). Credentials from opts are marked as
secrets first, and never written to context.
Example
creds ::box::auth/resolve-credentials()
creds.kind
// One tenant, through the keeper
tenant ::box::auth/resolve-credentials({account: "tenant-42"})
tenant.kind
resolve-from
fn (opts: Map, ctx: Map): Map
The one resolver, pure: credentials for a call from opts first, then
ctx (a source Map, see ctx-source). An Err when a credential key is
in opts but blank or null; otherwise as
credentials-from(merge-sources(opts, ctx)). Exposed for testing;
resolve-credentials feeds it the context.
Example
creds ::box::auth/resolve-from({account: "tenant-42"}, ::box::auth/ctx-source())
creds.kind
save-tokens
fn (account: Str, tokens: Map): Bool
fn (account: Str, tokens: Map, opts: Map): Bool
Store a token response for account in the keeper, replacing what was
there. Call it after ::box::oauth/exchange-code (and after any
re-consent). Returns true.
tokens ::box::oauth/exchange-code(::hot::ctx/get("box.client.id"), ::hot::ctx/get("box.client.secret"), "code-from-the-callback-query", "https://app.example.com/oauth/box")
::box::auth/save-tokens("tenant:42", tokens)
// later, in any run
me ::box::api/json("GET", "https://api.box.com/2.0/users/me", {}, "", {account: "tenant:42"})
seed-record
fn (refresh-token: Str, now: Int): Map
A keeper record holding only a refresh token (pure), for seeding an empty account. Its refresh expiry is unknown.
Example
record ::box::auth/seed-record(::hot::ctx/get("box.oauth.refresh-token"), ::hot::time/epoch-millis(::hot::time/now()))
record.expires-at
sign-assertion
fn (claims: Map, key-id: Str?, private-key: Str): Str
Sign Box JWT claims with RS256 and the app's kid header. Returns the
compact JWT, or an Err when the key cannot sign. (::jwt/sign has no
header option, so the kid-bearing header is built here; the signature
is the same RSASSA-PKCS1-v1_5 / SHA-256 that ::jwt uses.)
Example
claims ::box::auth/jwt-claims("app-id", {type: "enterprise", id: "123"}, Str(Uuid()), ::jwt/now-seconds())
assertion ::box::auth/sign-assertion(claims, "key-1", ::hot::ctx/get("box.jwt.private-key"))
length(split(assertion, "."))
store-name
fn (value: Any): Str
The keeper store's name for a token-store value (a Str, a
::hot::store/Map, or null for box-oauth-tokens).
Example
::box::auth/store-name("tenant-tokens") // "tenant-tokens"
::box::auth/store-name(null) // "box-oauth-tokens"
subject-of
fn (source: Map, default-enterprise: Any): Map?
The {type, id} subject for CCG or JWT (pure): user-id gives user,
else enterprise-id (or default-enterprise) gives enterprise; null
when neither is set.
Example
::box::auth/subject-of({user-id: "123"}, null) // {type: "user", id: "123"}
::box::auth/subject-of({}, "456") // {type: "enterprise", id: "456"}
::box::auth/subject-of({}, null) // null
token-cache-key
fn (creds: Map): Str?
The context key a minted token is cached under, or null for explicit access tokens. Keyed by a hash of the credential identity and subject; no secret appears in the key.
Example
key ::box::auth/token-cache-key({kind: "ccg", client-id: "app-id", subject: {type: "enterprise", id: "123"}})
starts-with(key, "box.token-cache.") // true
::box::auth/token-cache-key({kind: "token"}) // null
token-error
fn (message: Str): TokenError
fn (prefix: Str, payload: Any): TokenError
Build a TokenError. The 1-arity form wraps a plain message; the
2-arity form prefixes the payload of a failed ::oauth2 call ({status, body} or a transport error).
Example
::box::auth/token-error("box: no credentials").message // "box: no credentials"
error ::box::auth/token-error("box: token request failed", {status: 400, body: {error: "invalid_grant", error_description: "Expired"}})
error.message // "box: token request failed: invalid_grant (Expired)"
error.error-code // "invalid_grant"
token-store
fn (value: Any): Map
The ::hot::store/Map the keeper uses for a token-store value (Str
name, store Map, or null for box-oauth-tokens).
Example
store ::box::auth/token-store("tenant-tokens")
::hot::store/get(store, "tenant-42")
token-url
fn (): Str
The OAuth token endpoint: https://api.box.com/oauth2/token, or under
the box.api-root override.
Example
::box::auth/token-url() // "https://api.box.com/oauth2/token"
with-subject
fn (source: Map, opts: Map): Map
Apply opts.user-id / opts.enterprise-id to a source (pure). An
enterprise subject clears the user subject, so the call runs as the
enterprise's service account.
Example
::box::auth/with-subject({user-id: "1"}, {enterprise-id: "9"}) // {user-id: null, enterprise-id: "9"}
Types
TokenError
TokenError type {
message: Str,
status: Int?,
error-code: Str?,
error-description: Str?,
body: Any?
}
A credential or token-endpoint failure. message is readable, e.g.
"box: token request failed: invalid_grant (Refresh token has expired)".
error-code and error-description carry Box's OAuth error /
error_description when the token endpoint answered, or one of
box's own codes: "refresh_in_progress" (retryable),
"no_tokens", "refresh_token_expired", "encrypted_private_key".
No token or secret is ever included.