Securing a resty API¶
A complete identity and access-control starter: one rule list over six feature modules, JWT and Basic login, tenant isolation, method guards and the pitfalls the project was built to demonstrate.
This tutorial walks through api-resty-security, a runnable application that puts every feature of @typeix/resty-security behind a real route. It is the reference for how the pieces fit together — not a fragment, but an application you can start and poke with curl.
There is no database. Identities live in an in-memory IdentityStore, so npm install && npm start is the whole setup, and every demonstration is reproducible.
What it demonstrates¶
| Concern | Where it is decided |
|---|---|
| One rule list for the whole app | src/security-rules.ts, installed by @SecurityConfiguration |
| JWT, Basic login, an opaque API key | one DefaultAuthenticator with three checkers |
| Roles and permissions | inGrant('ADMIN'), may('article:write') |
| Tenant isolation | #tenant == identity.tenant on a route rule |
| Method-level narrowing | @Guard, @GuardResult, @Open |
| The identity inside a service | a request-scoped AuditService reading IDENTITY |
| Documentation behind the chain | pipeSwagger runs after pipeServer |
Project layout¶
src
├─ application.ts # @SecurityConfiguration + @RootModule
├─ bootstrap.ts # pipeServer → pipeSwagger
├─ security-rules.ts # the rule list, exported for the spec
├─ identity
│ ├─ users.store.ts # IdentityStore, scrypt hashes computed lazily
│ ├─ api-key.checker.ts # custom CredentialChecker
│ └─ tokens.ts # JwtVerifier, signJwt wrapper
├─ services/audit.service.ts # request scoped, reads the identity
└─ modules
├─ public → /health, /public/**
├─ session → /session/token, /session/me, /session/accounts
├─ articles → /articles, @Guard, @GuardResult, @Open
├─ admin → /admin/**, /reports/**
├─ tenants → /t/<tenant>/**, /org/<org>/**
└─ platform → /api/**, /files/**, /v2/**, /search, /export
Two decisions shape the whole project:
- The rules are exported, not inline.
security-rules.tsexportssecurityRules(guards), andapplication.tsinstalls exactly that function. The unit spec imports the same export, so assertions cannot drift from the real policy. - Modules only contribute controllers. No module knows about security; every decision is in one list, which is what makes the policy reviewable in one screen.
The rule list¶
This is the file the rest of the tutorial refers to:
import {GuardBuilder} from "@typeix/resty-security";
export function securityRules(guards: GuardBuilder): void {
guards
// ---- public ---------------------------------------------------------
.match('/health', 'allow()')
.match('/public/**', "guest() and identity.tenant == 'public'")
// a specific tenant path before the general tenant rule below
.match('/t/<tenant>/public/**', 'allow()')
// ---- static API key, no identity involved ---------------------------
.match('/api/**', "header('x-api-key') == 'secret-key'")
// ---- files: the private branch must be declared first ---------------
.match('/files/private/**', "inGrant('ADMIN')")
.match('/files/<path:([\\s\\S]+)>', "may('file:read')")
// ---- documentation of a protected API -------------------------------
.match('/docs/**', 'allow()')
// ---- roles ----------------------------------------------------------
.match('/admin/**', "inGrant('ADMIN')")
.match('/reports/**', "inAnyGrant('ADMIN','AUDITOR')")
// ---- tenant isolation ----------------------------------------------
.match('/org/<org>/**', '#org == identity.org')
.match('/t/<tenant>/**', '#tenant == identity.tenant')
// ---- headers, query string, method ---------------------------------
.match('/v2/**', "header('x-api-version') == '2'")
.match('/search', "query('admin') != 'true' or inGrant('ADMIN')")
.match('/export', "method != 'POST' or may('export:write')")
// ---- open route inside a protected namespace ------------------------
.match('/articles/feed', 'allow()')
.match('/articles', "may('article:write')", ['POST'])
.match('/articles/<id>', "identified() and (method != 'DELETE' or may('article:delete'))")
// ---- everything else needs a caller ---------------------------------
.anyRequest('identified()');
}
Read it top to bottom and the ordering rules become obvious: /files/private/** sits before /files/<path:…> because the general pattern would otherwise swallow the private branch, and /t/<tenant>/public/** sits before /t/<tenant>/** for the same reason.
Wiring¶
@SecurityConfiguration({
authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
.add(new JwtTokenChecker(createJwtVerifier()))
.add(new ApiKeyChecker(new Map([
["acme:abc123", {org: "acme", grants: ["ROLE_SERVICE", "file:read", "article:read"]}],
["globex:xyz789", {org: "globex", grants: ["ROLE_SERVICE", "file:read"]}]
])))
.add(new LoginChecker(store, new ScryptPasswordHasher())),
guestFactory: () => guestIdentity({tenant: "public", channel: "web"}),
guards: securityRules
})
@RootModule({
imports: [PublicModule, SessionModule, ArticlesModule, AdminModule, TenantsModule, PlatformModule],
controllers: [],
providers: [],
shared_providers: [UsersStore, DefaultAuthenticator, {provide: Logger, useFactory: () => new Logger(…)}]
})
export class Application {}
Four details are worth pausing on:
Checkers are tried in order. Bearer <jwt> is offered to JwtTokenChecker first, then the same bearer value to ApiKeyChecker (acme:abc123), and a Basic header reaches LoginChecker. First non-null answer wins, so one authenticator serves three credential styles.
guestFactory gives anonymous callers attributes. Without it, guest() and identity.tenant == 'public' could never be true, because a bare guest has no attributes.
shared_providers is the argument list. The factory's parameters (store, authenticator) are resolved from that array in declaration order.
pipeServer takes no security options. The decorator publishes the chain through metadata; the bootstrap stays unaware that security exists:
async function bootstrap() {
const server = createServer();
await pipeServer(server, Application);
await pipeSwagger(server, Application, {
path: "/docs",
yaml: true,
info: {title: "Resty security API", version: "1.0.0", …}
});
server.listen(8080);
}
Because pipeSwagger runs after pipeServer, its routes are registered through the same pipeline and therefore pass through the chain.
Running it¶
cd resty-starters/api-resty-security
npm install
npm run start # or: npm run start:dev
Demo accounts, all with the password secret: ada, bob, admin.
B=http://localhost:8080
TOKEN=$(curl -s -u ada:secret -X POST $B/session/token | jq -r .accessToken)
| Account | Grants | Attributes |
|---|---|---|
ada | ROLE_EDITOR, article:write, article:delete, file:read, ROLE_DEVELOPER | tenant acme, org acme |
bob | ROLE_VIEWER, article:read, file:read, ROLE_AUDITOR | tenant globex, org globex |
admin | ROLE_ADMIN, export:write, file:read, ROLE_DEVELOPER, article:write | tenant acme, org acme |
The routes, and what each one teaches¶
| Route | Rule that decides it | Lesson |
|---|---|---|
GET /health | allow() | an explicit public route |
GET /public/info | guest() and identity.tenant == 'public' | attributes on the guest identity |
POST /session/token | fallback identified() | Basic credentials, then the handler signs a JWT |
GET /session/me | fallback identified() | @CurrentIdentity() in a handler |
GET /api/catalog | header('x-api-key') == 'secret-key' | a static key with no authenticator involved |
GET /files/… with Bearer acme:abc123 | may('file:read') | a custom CredentialChecker |
GET /admin/stats | inGrant('ADMIN') | role gate |
GET /reports/summary | inAnyGrant('ADMIN','AUDITOR') | any-of roles |
POST /articles | may('article:write') + @Guard | permission, checked twice on purpose |
DELETE /articles/<id> | @GuardResult("result.owner == identity.name") | ownership after the handler ran |
GET /articles/feed | allow() + @Open() | an open route inside a protected namespace |
GET /t/<tenant>/profile | #tenant == identity.tenant | tenant isolation as a route parameter |
GET /org/<org>/settings | #org == identity.org | the same idea with another attribute |
GET /v2/articles | header('x-api-version') == '2' | version gate by header |
GET /search?admin=true | query('admin') != 'true' or inGrant('ADMIN') | a conditional branch in the query string |
POST /export | method != 'POST' or may('export:write') | per-method restriction inside one rule |
GET /files/private/<path> | inGrant('ADMIN') | a specific branch declared before the general one |
GET /docs | allow() | see the note below |
/docs is open in this starter
security-rules.ts matches /docs/** with allow() so the Swagger UI is reachable without a token while you explore the project. The comment above that rule and the note in bootstrap.ts still describe the stricter intent. For a real deployment, change it to inGrant('DEVELOPER') — ada and admin carry ROLE_DEVELOPER, so the UI then requires a login.
Three demonstrations worth running¶
# ada may delete her own article, not bob's — same grant, different owner
curl -X DELETE -H "authorization: Bearer $TOKEN" $B/articles/article-1 # 200
curl -X DELETE -H "authorization: Bearer $TOKEN" $B/articles/article-2 # 403
# bob is an auditor, ada is not
BOB=$(curl -s -u bob:secret -X POST $B/session/token | jq -r .accessToken)
curl -H "authorization: Bearer $BOB" $B/reports/summary # 200
curl -H "authorization: Bearer $TOKEN" $B/reports/summary # 403
# wrong tenant, even with a valid token
curl -H "authorization: Bearer $TOKEN" $B/t/acme/profile # 200
curl -H "authorization: Bearer $TOKEN" $B/t/globex/profile # 403
The first is the one that matters most: article:delete is a permission, ownership is a fact about the result, and only @GuardResult can see the second one.
Decorator order is interceptor order¶
DELETE /articles/<id> declares two method rules, and their order is deliberate:
@DELETE("<id>")
@GuardResult("result.owner == identity.name")
@Guard("may('article:delete')")
remove(@PathParam("id") id: string) { … }
The decorator declared last runs first, so the grant is checked before the handler executes. Reversing the two would wrap @Guard inside @GuardResult, running the handler — and any write in it — before authorization.
Reading the identity in a service¶
A handler gets the identity through a parameter:
@GET("me")
me(@CurrentIdentity() who: Identity) {
return {name: who.name, grants: who.grants, attributes: who.attributes};
}
A service cannot, because the chain resolves the identity after the controller is constructed. It reads the request injector instead, and it must be request scoped:
@Injectable()
export class AuditService {
@Inject() private injector: Injector;
record(event: string, detail: Record<string, any> = {}) {
const identity = this.injector.has(IDENTITY)
? this.injector.get(IDENTITY) as Identity
: guestIdentity();
// detail first: a caller must not be able to forge the recorded facts
return {...detail, event, actor: identity.name, grants: identity.grants,
authenticated: identity.authenticated};
}
}
@Controller({path: "/articles", providers: [AuditService]})
Declaring AuditService in @Controller({providers}) is the load-bearing part: resty builds it from the per-request injector. In a module providers array it would be a singleton built from the module injector, which never holds a request identity — every audit entry would say guest.
Pitfalls this starter was built to show¶
Grants are prefixed. inGrant('DEVELOPER') looks for ROLE_DEVELOPER. A store returning DEVELOPER without the prefix does not match — a silent 403, not an error.
An audit entry is written before detail is merged. The spread order in record() means a caller cannot forge actor, grants or authenticated through the payload. In an audit log, the recorded facts win.
A query rule gates every request to the path. query('admin') == 'true' and inGrant('ADMIN') would deny ?admin=false too, because the rule matches the path and then evaluates. The starter uses the negated form, query('admin') != 'true' or inGrant('ADMIN'), so only the admin branch is gated.
@Open() cannot rescue a route-level deny. The chain is a request interceptor and returns before the handler, so match("/articles/feed", "deny()") would still answer 401 for a guest. @Open() documents intent and protects the handler; the route rule has to allow the request.
A custom checker only sees login and token. The chain parses Authorization into those two kinds, so a bespoke x-api-key header cannot reach a checker — it is expressed as a rule (/api/** reads the header directly). A checker works on the bearer value, which is how Bearer acme:abc123 is resolved here.
A route rule that allows a guest hides 401 from 403. With method != 'DELETE' or may(...) an anonymous read reached the method guard and produced 403. Adding identified() to the route rule restores the challenge: anonymous 401, identified-but-insufficient 403.
useFactory authenticators must be synchronous. The sync injector does not await, so an async factory hands the chain a promise instead of an authenticator.
A trailing slash in a request does not match. /health/ falls through to the fallback, while the pattern /health matches /health only. Use /health/** to cover both.
Rules only cover registered routes. A path no controller declares is answered 404 by the router before any interceptor runs, so anyRequest protects endpoints, not typos.
Tests¶
npm run test # unit, no server
npm run test:e2e # http assertions against a real listener
npm run test:cov # unit with coverage thresholds
| File | Level | Covers |
|---|---|---|
src/security-rules.spec.ts | unit | every rule, built from the real securityRules export |
src/identity/tokens.spec.ts | unit | signing, verification, algorithm confusion, expiry, issuer and audience |
src/identity/users.store.spec.ts | unit | lookup, lazily cached scrypt hashes, no secrets in describe() |
src/identity/api-key.checker.spec.ts | unit | the custom credential checker |
src/services/audit.service.spec.ts | unit | identity resolution, context fallback, guest |
src/modules/**/*.spec.ts | unit | controller behaviour, including guard denials |
src/application.spec.ts | wiring | the security factory is published for pipeServer |
test/app.e2e-spec.ts | e2e | status codes, credential parsing, token validation, 401 vs 403 |
Two testing properties are worth copying:
The rules spec tests the real policy. It imports securityRules from src/security-rules.ts — the same function application.ts installs — so a rule change that forgets the spec still shows up as a failing assertion rather than a stale test.
@Guard runs even without a server. Method guards are DI interceptors, so a controller spec that calls the method directly still hits them, and every call returns a promise. Assertions therefore await, and a denial is a rejection carrying code: 403.
buildGuards, parseExpression and evaluateExpression make the rule layer testable on its own, without an HTTP listener — see Testing.
Where to go next¶
- Security quick start — the smallest working setup
- Rules — patterns, order and the complete grammar
- Credentials — checks, stores and hashing
- JWT — verification policy and issuing tokens
@typeix/resty-security— every option in one table