Home Applications iris-api-keys

iris-api-keys

Community Project
This project is maintained by its author and is not officially supported by InterSystems. For technical support, please contact the project developer.
0
0 reviews
0
Awards
2
Views
0
IPM installs
0
Add to bundle
Details
Releases (1)
Reviews
Issues
API authorization for IRIS-to-IRIS integrations, packaged as an IPM module

What's new in this version

Initial Release

iris-api-keys

API authorization for IRIS-to-IRIS integrations, packaged as an IPM module.

  • Issuer (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.
  • Outbound (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:

Installation

zpm "install iris-api-keys"

What gets installed

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 key

Include └── 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;
  • a subclass of ApiKeys.Issuer.ScopeRegistry that declares the application’s scopes;
  • an API class that extends ApiKeys.Issuer.REST, or adds ApiKeys.Issuer.Scoped to its own REST base class;
  • optionally, a subclass of ApiKeys.Issuer.Admin for the admin endpoints.

Settings

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

Issuer: protecting an API

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.

Declare the scopes

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.

One scope for the whole class

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 web application

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)

Responses to a rejected request

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).

Your own REST base class

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.

One scope per route: @method

When 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 ApiKeys

Class 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))
    

Routers with 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.

Issuing tokens

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.

Admin endpoints

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.

1. Subclass 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.

2. Plug the subclass in

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.

  • Do not make the application’s REST class a subclass of ApiKeys.Issuer.Admin. A subclass’s UrlMap replaces the parent’s, so the endpoints would disappear, and Actor() would close the whole API.
  • Mount the endpoints in the class used by the admin UI, not in the integration API that extends 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/....

Endpoints

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
  • The token itself is returned only once, in the response to POST /clients/:id/tokens; the database keeps only its hash. Show it to the admin with a note to copy it now.
  • Clients and tokens are never deleted: clients are disabled, tokens are revoked.
  • Dates are ISO 8601 in UTC (2026-11-30T12:00:00Z).
  • Errors return {"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).

Outbound: calling an API

The master key

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 processes (web requests, tasks, 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.
  • The key is not cached: it is read on every encryption and decryption.
  • Without the key, storing and reading tokens fails with an error that names the variable; the module never falls back to plain text.
  • The variable is visible to processes of the same OS user and inherited by child processes. This is the same level of access as a key file mounted into the container.

Storing a token

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.

Using the token

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

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.

  1. 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
    
  2. 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.

  3. 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")
    
  4. 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.

  5. 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.

  6. 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.

Known limitations

  • The @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.
  • No master key rotation. After the key changes, outbound tokens are set again.
  • No cleanup. The audit log and ^ApiKeys.DenyCount grow until the application cleans them up.

License

Apache License 2.0

Made with
Install
zpm install iris-api-keys download archive
Version
0.1.002 Dec, 2026
Category
Integration
Works with
InterSystems IRISInterSystems IRIS for HealthHealthShareHealth Connect CloudEnsembleCaché
First published
02 Dec, 2026
Last edited
02 Dec, 2026