Rules¶
The resty-security rule list: declaration order, first match wins, route patterns with inline regex, the complete rule grammar and exactly what each rule can read.
A rule is a small expression that answers one question about a request: may it proceed? The rules are declared as a list on the root module, evaluated in order, and the first match wins.
@SecurityConfiguration({
guards: guards => guards
.match("/admin/public", "allow()") // most specific first
.match("/admin/**", "inGrant('ADMIN')")
.match("/articles", "may('article:write')", ["POST"])
.match("/articles/<id>", "method != 'DELETE' or may('article:delete')")
.anyRequest("identified()") // fallback, must be last
})
Each expression is parsed once, when the class is defined, and the resulting tree is stored on the rule. A request only walks that tree, so no parsing ever happens while serving traffic, and a typo fails at boot.
match and anyRequest¶
| Method | Purpose |
|---|---|
match(pattern \| pattern[], rule, methods?) | add a rule for one pattern or a list, optionally limited to http methods |
anyRequest(rule) | fallback applied when nothing above matched |
Both throw at declaration time for the two mistakes that would silently change behaviour:
| Mistake | Error |
|---|---|
a match after anyRequest() | a rule was declared after anyRequest(), it could never match; order rules from specific to general |
| two fallbacks | anyRequest() was called twice |
anyRequest is optional. Without it, a request that matches no rule is denied — the fallback only chooses which rule covers the leftovers, it is not what makes the application deny by default.
Patterns¶
| Pattern | Matches |
|---|---|
/health | exactly /health |
/docs/** | /docs, /docs/, /docs/a, /docs/a/b — the slash is part of /** |
/users/<id> | one segment, same as /users/* |
/users/<id:(\d+)> | one segment that also matches the inline pattern, so /users/abc is not matched |
/v<version:(\d+)>/users/<id> | an inline pattern inside a segment: /v2/users/7 |
/files/<path:([\s\S]+)> | an inline pattern that crosses segments: /files/a/b/c.txt |
/openapi.json | exactly that; a dot is not a wildcard |
A trailing slash is ignored. The third argument restricts a rule to methods:
guards: guards => guards
.match("/articles", "may('article:write')", ["POST", "PUT"])
.match("/articles", "identified()", ["GET"])
Inline patterns are honoured exactly like the router. A rule written for /users/<id:(\d+)> covers exactly the requests the router serves for that template — it cannot silently cover /users/abc while the endpoint rejects it. This parity is asserted against @typeix/router's own RouteParser in the package test suite.
Patterns the router cannot express, /docs/** and /**, are guard-only: RouteParser rejects them, so they exist for rules and are matched by this package alone.
One intentional difference from the router¶
The router compiles a bare <param> to ([\s\S]+), which can swallow /: /a/<x>/b/<y> matches /a/1/x/b/2. The guard matcher keeps a bare parameter inside one segment, because a security pattern has to be predictable — /users/<id> must not also cover /users/1/2/3/delete. Anything that genuinely needs to cross segments uses an explicit inline pattern, which both sides handle identically.
Order decides overlapping patterns¶
First match wins, so a broad pattern declared before a specific one also covers the specific path:
// the first rule wins for /files/private too
.match("/files/<path:([\s\S]+)>", "allow()")
.match("/files/private/**", "inGrant('ADMIN')")
// declared the other way around, the private path is protected
.match("/files/private/**", "inGrant('ADMIN')")
.match("/files/<path:([\s\S]+)>", "allow()")
Put the most specific patterns first. A useful default order is: explicit public routes, then admin or internal prefixes, then per-method rules, then the fallback.
The rule language¶
A closed grammar, parsed once at boot. An unknown function is a startup error, never a silent allow.
Functions¶
| Function | Arguments | Answers | Notes |
|---|---|---|---|
allow() | none | true | use it only for a deliberate public route |
deny() | none | false | the explicit fallback; an unmatched request is denied anyway |
identified() | none | authenticated? | false for the guest identity, even on an open route |
guest() | none | anonymous? | the exact inverse of identified() |
inGrant('A','B') | one or more strings | any role held | the ROLE_ prefix is always added, so write the bare role name: inGrant('ADMIN') checks ROLE_ADMIN, and inGrant('ROLE_ADMIN') checks ROLE_ROLE_ADMIN |
inAnyGrant('A','B') | one or more strings | any role held | same as inGrant; the name documents intent |
may('a:b') | one or more strings | any permission held | compared as written, no prefix |
mayAny('a:b') | one or more strings | any permission held | same as may |
header('name') | exactly one string | a value | only valid inside a comparison; case insensitive |
query('name') | exactly one string | a value | only valid inside a comparison |
An unknown name — including the pre-9.2 names open() and closed() — fails at boot with unknown rule function "open" rather than silently denying or allowing.
Operands¶
| Operand | Example | Result |
|---|---|---|
| quoted string | 'POST', "acme" | string literal, single or double quotes |
| number | 2, -1.5 | number literal |
| boolean | true, false | boolean literal |
| identity property | identity.name, identity.tenant | the identity field, then an attribute of the same name |
| route parameter | #id | the captured path parameter — route rules only |
| request field | path, method | the resolved request |
| value function | header('x'), query('q') | a request value |
There are exactly two operators, == and !=. When either side is a string the comparison is done as strings, so header('x-api-version') == 2 matches the header value "2". Precedence is not / ! first, then the comparison, then and, then or — parentheses override it.
guards: guards => guards
.match("/a", "not guest() and inGrant('ADMIN')")
.match("/b", "identified() and (inGrant('ADMIN') or inGrant('SUPPORT'))")
.match("/c", "method == 'POST' and may('article:write')")
path never includes the query string, so path == '/articles' also matches /articles?page=2. Read the query with query('page'), never by comparing path.
What a rule can read¶
| Symbol | Route rule (match, anyRequest) | @Guard | @GuardResult |
|---|---|---|---|
identity, identified(), guest() | yes | yes | yes |
header(…), query(…) | yes | yes | yes |
path, method | yes | yes | yes |
#param | yes | rejected at boot | rejected at boot |
result | not available | not available | yes |
A route rule sees the resolved route, so it is the only place a path parameter exists. A @typeix/di method interceptor is constructed without the route, so #id could never resolve inside @Guard; it would compare undefined and deny every request. Instead of that silent denial, the decorator throws when the class is defined:
// fails at class definition:
// @Guard: route parameters like "#id" are only available in a route rule
// (GuardBuilder.match), not on a method; use a route rule, or compare `path`
@Guard("#id == identity.name")
read(@PathParam("id") id: string) {}
// move it to the route rule
guards: guards => guards.match("/articles/<id>", "#id == identity.name")
// or keep it on the method and compare the path
@Guard("path == '/articles/mine'")
read() {}
Recipes¶
Public health check, everything else identified¶
guards: guards => guards
.match("/health", "allow()")
.anyRequest("identified()")
Roles on a prefix, permissions on a verb¶
guards: guards => guards
.match("/admin/**", "inGrant('ADMIN')")
.match("/articles", "may('article:write')", ["POST"])
.match("/articles/<id>", "may('article:delete')", ["DELETE"])
.anyRequest("identified()")
Tenant isolation through an identity attribute¶
guards: guards => guards
.match("/t/<tenant>/**", "#tenant == identity.tenant")
.anyRequest("identified()")
#tenant is a route parameter, so this belongs on the route rule — not on a @Guard.
API version by header¶
guards: guards => guards
.match("/v2/**", "header('x-api-version') == '2'")
.anyRequest("identified()")
A static key with no authenticator at all¶
@SecurityConfiguration({
guards: guards => guards
.match("/api/**", "header('x-api-key') == 'secret-key'")
.anyRequest("deny()")
})
No authenticator means every caller is a guest, which is enough when the rule reads a header directly.
Only one method of a route¶
guards: guards => guards
.match("/articles/<id>", "method != 'DELETE' or may('article:delete')")
.anyRequest("identified()")
What happens on a denial¶
The chain sets the status and returns a small body, {message, statusCode}, which stops the handler from running. It does not throw: the router re-dispatches a thrown RouterError to the error route, and without an @OnError handler that lookup throws its own 404 and overwrites the status.
| Caller | Status | Body |
|---|---|---|
| anonymous | 401 | {message: challengeMessage, statusCode: 401} |
| authenticated | 403 | {message: denialMessage, statusCode: 403} |
Next¶
- The authenticator — where the
Identitycomes from - Method rules —
@Guard,@GuardResult,@Open - Protecting every endpoint —
/docs,/graphql, websockets