@ttoss/iam
Policy-based access control for an API: resource names, a permission catalog, policy validation and policy evaluation. Pure TypeScript with no runtime dependencies. Storage, credentials and request handling belong to the application.
Installation
pnpm add @ttoss/iam
Concepts
| Concept | Example |
|---|---|
| Resource name | srn:project/prj_1/task/tsk_1 |
| Pattern | *, srn:project/prj_1, srn:project/*/task, srn:**/task/t? |
| Action | tasks:GetTask, tasks:*, * |
| Policy document | { statement: [{ effect, action, resource?, condition?, denial? }] } |
| Owner | 'top', or the node a policy belongs to: { type: 'project', id } |
| Policy sets | OwnedPolicy[][]: every set must allow |
- A pattern reaches a name when it matches the name or any ancestor of it, so
srn:project/prj_1reaches every resource under that project. - An
Allowacts only within its owner's reach; aDenyapplies wherever it matches and wins. Nothing allows by default. - A
Denymay carry adenial({ code, message, meta? }) that is returned with the refusal. - Conditions use the operators in
CONDITION_OPERATORS(StringEquals,StringNotEquals,StringLike) over platform keys (iam:ResourceType,iam:ResourceTag/<tag>,iam:RequestTag/<tag>) and the action keys the catalog declares. A key or variable the check does not supply, or an operator outside that list, makes anAllowgrant nothing and aDenyapply, in a check and in a listed row alike.
Usage
import { createIam, ownedBy } from '@ttoss/iam';
const iam = createIam({
prefix: 'srn:',
pathAliasRootType: 'project', // enables srn:project/<id>/path/<segments>
namespace: 'iam', // the default
variables: ['iam:ActorId'],
resourceTypes: ['project', 'task'],
denialCodes: ['TASK_LOCKED'],
modules: [
{
module: 'tasks',
actions: [
{ action: 'tasks:GetTask', operationId: 'getTask' },
{
action: 'tasks:TransitionTask',
operationId: 'transitionTask',
conditionKeys: ['tasks:Transition'],
},
],
},
],
});
Validate a policy
const result = iam.validatePolicyDocument(body);
if (!result.valid) {
throw new Error(result.errors.join('\n'));
}
result.document; // PolicyDocument
Validation refuses unknown actions, malformed patterns, types outside
resourceTypes, condition keys nothing supplies, undeclared variables and
denial codes outside denialCodes. Each of these would otherwise make a
Deny silently never match. resourceTypes may also be a predicate,
(type) => boolean, for types registered at runtime.
Decide a check
const policies = ownedBy({
owner: { type: 'project', id: 'prj_1' },
documents: [result.document],
});
const decision = iam.decideOnChain({
policies,
action: 'tasks:GetTask',
chain: {
name: 'srn:project/prj_1/task/tsk_1',
links: [], // live ancestors outside the name, such as a share
tagBags: [{ team: 'red' }], // one bag per tagged node
},
});
decision.allowed; // boolean
decision.denial; // the denial of the Deny that decided, or null
Authorize requests
createAuthorizer checks labeled policy sets (a principal and the sets it
holds) and records which principal refused each check:
import { createAuthorizer } from '@ttoss/iam';
const authorizer = createAuthorizer<string>({
evaluator: iam.evaluator,
getSets: async (check) => {
return [
{ principal: 'user', sets: [userPolicies] },
{ principal: 'api_key', sets: [keyPolicies] },
];
},
loadLinks: async ({ name }) => {
return [];
},
defaultResource: (check) => {
return undefined;
},
});
await authorizer.isAllowed({
action: 'tasks:GetTask',
resource: 'srn:project/prj_1/task/tsk_1',
});
authorizer.refusedBy({
action: 'tasks:GetTask',
resource: 'srn:project/prj_1/task/tsk_1',
}); // { principal, denial } | undefined
List the rows a policy allows
compileRowFilter turns policy sets into a store-independent RowFilter for
one listed type: a row passes exactly when decideOnChain allows the action on
that row. matchesRow reads a filter in memory; @ttoss/iam-postgresdb
renders it as a Sequelize where.
import { matchesRow } from '@ttoss/iam';
const filter = iam.compileRowFilter({
policies: [userPolicies],
action: 'files:GetFile',
list: {
root: { type: 'project', id: 'prj_1' },
resourceType: 'file',
hasPath: true,
rowTagged: true,
},
});
matchesRow({ filter, row: { id: 'fil_1', path: '/docs/a.md', tags: {} } });
list field | Meaning |
|---|---|
root | The node every row sits under |
resourceType | The listed type |
parent | { type, id?, tags? }: one parent, or every parent without id |
hasPath | Rows carry a path alias under root |
rowTagged | Rows carry their own tag bag |
parentTagged | The parent type carries a tag bag |
links | The live links of root |
A filter is all, none, and, or, not, or a leaf over a row's id,
parentId (glob), path (regex) or tags (tagEquals, tagLike).
Resource names
iam.names (or createResourceNames({ prefix }) on its own) builds, parses
and compares names and patterns:
| Method | Returns |
|---|---|
buildName({ steps }) | srn:project/p/task/t |
buildPathAlias({ rootId, segments }) | srn:project/p/path/docs/a%20b |
parseName(value) | { ok, value } or { ok: false, error } |
ancestors(name) | the name and every ancestor |
matchPattern({ pattern, name }) | whether the pattern reaches the name |
patternCovers({ outer, inner }) | whether outer reaches everything inner does |
patternsOverlap({ a, b }) | whether some name is reached by both |
patternRegex({ pattern }) | a regex for filtering stored names (JS and PostgreSQL ~) |
patternError(pattern) | why a pattern is malformed, or null |
matchGlob, globCovers and globOverlaps do the same for actions and
condition values (* any run, ? one character).