Initial Release
API authorization for IRIS-to-IRIS integrations, packaged as an IPM module.
ApiKeys.Issuer) — the system that receives API calls. It issues opaque bearer tokens (<prefix>_<40 hex>) with scopes and an expiry date, stores only their SHA-256 hash, supports revocation, and checks Authorization: Bearer and the required scope in a REST controller. Scopes are declared in code; a REST class that lacks a scope check does not compile.ApiKeys.Outbound) — the system that makes API calls. It stores tokens issued to it by other systems encrypted (AES-256-CBC + HMAC-SHA256) with a master key that lives outside the database, in an environment variable, and adds the token to an outgoing %Net.HttpRequest.Both packages are always installed; the part you don’t use stays as empty tables and classes nobody refers to.
The module is meant for system-to-system integrations only. It does not distinguish between services and users, and it has no UI: the admin front end for issuing tokens is built by each application on top of the module’s REST endpoints.
Contents:
zpm "install iris-api-keys"
Classes ├── ApiKeys.Issuer.* receiving side │ ├── Client, Token, Event persistent: API clients, their tokens, audit log │ ├── ScopeRegistry base class for the application's scope registry │ ├── Service operations on clients and tokens │ ├── Auth checks the bearer token and scope of a request │ ├── Scoped, REST scope declaration for REST classes, ready-made REST base class │ └── Admin REST endpoints for an admin front end └── ApiKeys.Outbound.* calling side ├── Credential persistent: encrypted tokens for outgoing requests └── Cipher encryption with the master keyInclude └── ApiKeys.inc $$$ApiKeysToken, $$$RequireScope
SQL tables ├── ApiKeys_Issuer.Client, ApiKeys_Issuer.Token, ApiKeys_Issuer.Event └── ApiKeys_Outbound.Credential
Globals ├── ^ApiKeys.Issuer., ^ApiKeys.Outbound. table data and indices ├── ^ApiKeys.Config settings, set by the application └── ^ApiKeys.DenyCount daily counter that limits denial entries in the audit log
All globals start with ApiKeys., so a single global mapping covers the module’s data.
The module creates no web applications: the application creates its own and plugs the module in:
Include ApiKeys in classes that use the macros;ApiKeys.Issuer.ScopeRegistry that declares the application’s scopes;ApiKeys.Issuer.REST, or adds ApiKeys.Issuer.Scoped to its own REST base class;ApiKeys.Issuer.Admin for the admin endpoints.Settings are stored in the ^ApiKeys.Config global and set by the application, usually in its installer:
set ^ApiKeys.Config("Prefix") = "acme"
| Key | Default | Purpose |
|---|---|---|
Prefix |
— (required for issuer) | prefix of issued tokens, e.g. acme → acme_…; helps recognize tokens in logs and secret scanning |
MaxTokensPerClient |
10 | maximum number of active tokens per client |
MaxDays |
365 | maximum token lifetime, in days |
AllowNoExpiry |
0 | allow tokens that never expire |
KeyEnv |
APIKEYS_MASTER_KEY |
name of the environment variable holding the outbound master key |
The integration API is a separate REST class in which every route requires a token. Do not mix it with endpoints that users call with a session.
A scope is a name such as orders:read. The application declares its scopes in a subclass of ApiKeys.Issuer.ScopeRegistry; tokens can only be issued with these scopes, and REST classes can only require them:
Class Acme.ApiScopes Extends ApiKeys.Issuer.ScopeRegistry {XData Scopes [ MimeType = application/json ] { { "orders:read": "Read orders", "orders:write": "Create and update orders" } }
}
A token holds a list of scopes; a check is an exact match, without hierarchies or wildcards.
Extend ApiKeys.Issuer.REST and set SCOPE. Every route of the class then requires a token with this scope:
Class Acme.API.Orders Extends ApiKeys.Issuer.REST {Parameter SCOPE = "orders:read";
XData UrlMap [ XMLNamespace = "http://www.intersystems.com/urlmap" ] { }
ClassMethod List() As %Status { write {"orders": []}.%ToJSON() return $$$OK }
}
A class with its own UrlMap and an empty SCOPE, or with a scope that is not in the registry, does not compile.
A single route can require one more scope with $$$RequireScope (add Include ApiKeys to the class):
ClassMethod Create() As %Status
{
$$$RequireScope("orders:write")
...
}
The module authenticates the request itself, so the web application must not use IRIS password authentication, which would take the Authorization header for itself. Create it with AutheEnabled = 64 (unauthenticated). The request then runs as UnknownUser, so the application also needs an application role with read access to the namespace’s database, otherwise %CSP.REST answers 403 with an empty body before the token is checked:
zn "%SYS"
set props("NameSpace") = "ACME"
set props("DispatchClass") = "Acme.API.Orders"
set props("AutheEnabled") = 64
set props("MatchRoles") = ":%DB_ACME"
do ##class(Security.Applications).Create("/acme/api", .props)
| Case | Status | WWW-Authenticate |
Body |
|---|---|---|---|
no Authorization: Bearer header |
401 |
Bearer |
{"error": "unauthorized"} |
| unknown, expired or revoked token, or a disabled client | 401 |
Bearer error="invalid_token" |
{"error": "invalid_token"} |
| the token lacks the scope | 403 |
Bearer error="insufficient_scope", scope="orders:write" |
{"error": "insufficient_scope", "scope": "orders:write"} |
A 403 is written to the audit log (deny), at most once a day per token and reason.
The token of the current request is available as $$$ApiKeysToken (an ApiKeys.Issuer.Token, with the client in $$$ApiKeysToken.Client).
If the application already has a REST base class (CORS, logging, error handling), add ApiKeys.Issuer.Scoped as a second parent and call Authorize from its OnPreDispatch or from its own authorization hook:
Class Acme.API.Base Extends (%CSP.REST, ApiKeys.Issuer.Scoped) {ClassMethod OnPreDispatch( pUrl As %String, pMethod As %String, ByRef pContinue As %Boolean) As %Status { set pContinue = ##class(ApiKeys.Issuer.Auth).Authorize(..RequiredScope()) return $$$OK }
}
Authorize writes the 401/403 response itself and returns 0. ApiKeys.Issuer.REST is exactly this class. A subclass that overrides OnPreDispatch must call ##super() and respect pContinue.
@methodWhen one class serves routes with different scopes, set SCOPE = "@method". OnPreDispatch then only checks that the token is active, and each route method starts with $$$RequireScope:
Include ApiKeysClass Acme.API.Orders Extends ApiKeys.Issuer.REST {
Parameter SCOPE = "@method";
XData UrlMap [ XMLNamespace = "http://www.intersystems.com/urlmap" ] { }
ClassMethod List() As %Status { $$$RequireScope("orders:read") ... }
}
When the class compiles, every Route of its UrlMap is checked: the source of the route method must contain $$$RequireScope with a scope from the registry, otherwise the class does not compile and the error names the route. Rules for this mode:
The macro is written in the route method itself, with the scope as a string literal: a scope in a variable or a check in a helper method is not found.
The route method must be defined in the source of the class named in Call (or of the REST class itself). An inherited method cannot be checked: override it or remove the route.
The check runs when the REST class compiles. Editing only a controller (for example, removing $$$RequireScope) does not recompile the REST class, so also call the check from a unit test of the application, one line per API class:
do $$$AssertStatusOK(##class(ApiKeys.Issuer.Scoped).Validate(##class(Acme.API.Orders).%ClassName(1), ##class(Acme.API.Orders).#SCOPE))
Map Forward<Map Prefix="..." Forward="..."/> entries are not checked: the forwarded class has its own check. A router class that only forwards to API classes with different scopes extends plain %CSP.REST, not ApiKeys.Issuer.REST: otherwise its own check would apply to every forwarded class.
Tokens are issued and revoked through the admin endpoints or from the terminal with ApiKeys.Issuer.Service:
do ##class(ApiKeys.Issuer.Service).CreateClient("billing", "[email protected]", $username, .client)
do ##class(ApiKeys.Issuer.Service).Issue(client, "production", $listbuild("orders:read"), 90, $username, .token, .tok)
write token
do ##class(ApiKeys.Issuer.Service).Revoke(tok.%Id(), $username)
The token itself is shown only once; the database keeps its hash and last 4 characters.
Rotation. A client may hold several active tokens, so rotation needs no special support: issue a new token, set it on the calling side, then revoke the old one.
ApiKeys.Issuer.Admin is a set of REST endpoints for managing clients and tokens. The module does not know how the application’s users and roles work, so access is decided by one method, Actor(). It returns the id of the current admin, which is written to CreatedBy, RevokedBy and the audit log, or "" when access is denied. In Admin itself it always returns "", so the endpoints stay closed until the application subclasses the class.
Before using the endpoints, set the token prefix and declare the scopes.
Admin and implement Actor()Return the admin’s id when the current user may manage API keys. For example, if the application’s admins hold an IRIS resource:
Class Acme.ApiKeysAdmin Extends ApiKeys.Issuer.Admin {ClassMethod Actor() As %String { return:$system.Security.Check("Acme_ApiKeysAdmin", "USE") $username return "" }
}
If the application keeps its own users and sessions, use its check instead and return its user id.
Choose one of two options.
a. Inside the application’s own REST class. Add a Map to the UrlMap of the dispatch class of the web application the admin UI already uses:
With the web application at /api, the endpoints answer at /api/api-keys/..., for example /api/api-keys/scopes. A request first passes the OnPreDispatch of the application’s class, with its session and authentication, and then Actor() decides whether this user is an admin.
ApiKeys.Issuer.Admin. A subclass’s UrlMap replaces the parent’s, so the endpoints would disappear, and Actor() would close the whole API.ApiKeys.Issuer.REST. Otherwise every admin request would need a bearer token with that API’s scope.Map and Route entries are matched in order: put the Map before routes whose URL could also match /api-keys/....b. As a separate web application. Create a web application whose dispatch class is the subclass, with authentication that sets $username (for example, password):
zn "%SYS"
set props("NameSpace") = "ACME"
set props("DispatchClass") = "Acme.ApiKeysAdmin"
set props("AutheEnabled") = 32
do ##class(Security.Applications).Create("/acme/api-keys", .props)
The endpoints then answer at /acme/api-keys/....
| Method | URL | Body | Response |
|---|---|---|---|
| GET | /scopes |
{"scope": "description"} |
|
| GET | /clients |
clients | |
| POST | /clients |
{"name", "contact"} |
the new client |
| PUT | /clients/:id |
{"contact", "disabled"}, a missing field is left as is |
the client |
| GET | /clients/:id/tokens |
the client’s tokens, without the tokens themselves | |
| POST | /clients/:id/tokens |
{"name", "scopes": [], "expiresInDays"} |
{"id", "token", "expiresAt"} |
| DELETE | /tokens/:id |
the revoked token; it stays in the list | |
| GET | /clients/:id/events |
the client’s audit log |
POST /clients/:id/tokens; the database keeps only its hash. Show it to the admin with a note to copy it now.2026-11-30T12:00:00Z).{"error": "..."} with status 400 (invalid request or a rule such as an unknown scope or the active token limit), 403 (Actor() returned "") or 404 (unknown client or token).Tokens issued to this system by others are stored encrypted with a master key: 32 random bytes, base64-encoded, in the environment variable APIKEYS_MASTER_KEY (the name can be changed with the KeyEnv setting). Generate a separate key for each environment and keep it in your secret store:
openssl rand -base64 32
How the value gets into the variable (a Kubernetes secret, a compose file, a systemd unit) is up to you. What matters:
iris session) inherit the instance’s environment as it was when the instance started. Set the variable before iris start, in the container spec or in the environment of the user that starts the instance. An export in a shell of a running container is not seen by the instance; changing the key needs a restart.A person sets the token in the terminal; the input is not echoed, so the token gets into neither the shell history nor the process list:
do ##class(ApiKeys.Outbound.Credential).Set("billing")
The name (billing) is the target system, chosen by the application; setting a token again replaces it. For scripts and tests there is Store(target, token). List() prints the stored targets with the last 4 characters of each token, and Remove(target) deletes one.
set req = ##class(%Net.HttpRequest).%New()
set req.Server = "billing.example.com"
set req.Https = 1
set req.SSLConfiguration = "default"
set sc = ##class(ApiKeys.Outbound.Credential).Authorize("billing", req)
return:$$$ISERR(sc) sc
set sc = req.Get("/api/orders")
Authorize adds Authorization: Bearer <token>. If no token is stored for the target, it returns an error that tells which Set to run. Send bearer tokens over HTTPS only.
A 401 from the other system means that the token has expired or was revoked: log it explicitly instead of falling back to a default result, so that someone sets a new token.
Changing the master key. There is no re-encryption: after the key changes, set the tokens again with Set.
demo/ runs two IRIS containers in one compose network: issuer issues and checks tokens and serves a small API (Demo.Points), client stores the token it was given and calls that API (Demo.Client). The master key is needed only by client; gen-key.sh puts it into demo/.env, which is not committed and not copied into the images.
You need git, Docker with Compose, and openssl. All commands run from the repository root.
Clone the repository, then build and start the containers:
git clone https://github.com/ogurecapps/iris-api-keys.git
cd iris-api-keys
./demo/gen-key.sh
docker compose -f demo/docker-compose.yml up -d --build
Open a terminal on issuer:
docker compose -f demo/docker-compose.yml exec issuer iris session IRIS
Create a client and issue a token with points:read only. The token is shown once:
do ##class(ApiKeys.Issuer.Service).CreateClient("client-demo", "", $username, .client)
do ##class(ApiKeys.Issuer.Service).Issue(client, "demo", $listbuild("points:read"), 30, $username, .token, .tok)
write token
Keep this session open for step 5.
In another shell, open a terminal on client:
docker compose -f demo/docker-compose.yml exec client iris session IRIS
Store the token. Paste it and press Enter; the input is not echoed, and the reply shows the last 4 characters:
do ##class(ApiKeys.Outbound.Credential).Set("issuer")
On client, call the API:
do ##class(Demo.Client).GetPoints()
do ##class(Demo.Client).AddPoints()
GetPoints returns 200; AddPoints returns 403 with insufficient_scope, because the token has no points:write.
On issuer, revoke the token:
do ##class(ApiKeys.Issuer.Service).Revoke(tok.%Id(), $username)
Repeat step 4: both calls now return 401 with invalid_token.
Stop and remove the containers:
docker compose -f demo/docker-compose.yml down
The API is also published on the host at http://localhost:52780/demo/api/. The demo uses plain HTTP inside the compose network; a real integration must use HTTPS.
@method check is textual. It looks for the first $$$RequireScope("...") in the source of the route method, so a commented-out macro or a macro in a branch that does not always run also passes. It catches a forgotten check, not a misplaced one; the rest is up to code review.^ApiKeys.DenyCount grow until the application cleans them up.