Method rules¶
@Guard, @GuardResult, @Open and @CurrentIdentity: per-handler rules, result inspection, what a method rule can read, and how a denial is translated into a response.
Route rules decide whether a request reaches a controller. Method rules narrow that decision for one handler, and they are the only place a rule can inspect a handler's return value.
There are four decorators:
| Decorator | Runs | Purpose |
|---|---|---|
@Guard(expression) | before the handler | narrow the route decision |
@GuardResult(expression) | after the handler | allow the response only if the result satisfies the rule |
@Open() | shorthand | @Guard("allow()") |
@CurrentIdentity() | parameter | inject the resolved Identity |
@Controller({path: "/articles"})
class ArticlesController {
/** the route rule already allowed any identified caller; this narrows it further */
@GET("/<id>")
@Guard("inGrant('EDITOR')")
read(@PathParam("id") id: string) { … }
@POST()
@Guard("may('article:write')")
create(body: CreateArticle) { … }
/** the result only exists after the handler ran, so this is the only place to inspect it */
@DELETE("/<id>")
@Guard("may('article:delete')")
@GuardResult("result.owner == identity.name")
remove(@PathParam("id") id: string) { … }
/** open even though a broad route rule would deny it */
@GET("/feed")
@Open()
feed() { … }
}
Order of evaluation¶
route rule list (first match wins)
└─ @Guard before the handler
└─ handler
└─ @GuardResult on the return value
The route chain runs first. An anonymous caller never reaches a method rule on a protected route — it is stopped with 401 before the controller is touched. A method rule therefore refines an already-allowed decision, it does not replace the route rule.
Multiple @Guard decorators on one handler are allowed and must all hold.
What a method rule can read¶
| Symbol | @Guard | @GuardResult |
|---|---|---|
identity, identified(), guest() | yes | yes |
header(…), query(…) | yes | yes |
path, method | yes | yes |
result | not available | yes |
#param | rejected at boot | rejected at boot |
A route parameter lives on the resolved route, and a @typeix/di method interceptor is constructed without one. #id in a method rule could never resolve; it would compare undefined and deny every request. Instead of that silent denial, the decorator throws when the class is defined:
@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`
Move the rule to the route, or compare path:
// route rule
guards: guards => guards.match("/articles/<id>", "#id == identity.name")
// method rule that reads the request instead
@Guard("path == '/articles/mine'")
read() {}
result is the mirror image: it does not exist before the handler, so @Guard cannot see it. Reading it there is always undefined, which fails the comparison — use @GuardResult.
@GuardResult and non-object results¶
@GuardResult evaluates after the handler and returns the result only when the rule holds; otherwise it answers 403. The rule reads fields of the returned value:
@GET("/<id>")
@GuardResult("result.owner == identity.name")
read(@PathParam("id") id: string): Article { … }
| Result | result.owner == identity.name |
|---|---|
{owner: "ada"} as ada | holds |
{owner: "bob"} as ada | fails, 403 |
null / undefined | fails, 403 — a missing result is not a pass |
| a string or a number | fails unless the rule compares identity only |
The handler has already run when the rule is evaluated, so a @GuardResult cannot prevent side effects. Use @Guard for anything that must be blocked before it happens, and @GuardResult for read paths that must not return data the caller may not see.
@CurrentIdentity()¶
@CurrentIdentity() injects the resolved identity into a parameter:
@Controller({path: "/me"})
class MeController {
@GET()
read(@CurrentIdentity() who: Identity) {
return {name: who.name, grants: who.grants, tenant: who.attributes?.tenant};
}
}
It is parameter-only by design. The chain resolves the identity after the controller instance is constructed, so a decorated property would still hold its initial value. For a service that needs the identity, inject IDENTITY_CONTEXT instead — see Reading the identity.
How a denial becomes a response¶
A method rule throws RouterError(403). Left alone, the router re-dispatches that to the error route, and without an @OnError handler that lookup throws its own 404 and overwrites the status. GuardChain wraps the handler and translates the error back into a status:
| Situation | Status |
|---|---|
@Guard denies an identified caller | 403 |
@GuardResult denies | 403 |
| the route chain denied earlier | 401 or 403, depending on the identity |
That is why the chain must be in front of the method rules: @SecurityConfiguration does that. A @Guard used without it reaches the router's error handling directly and needs an @OnError handler to render 403 instead of 404.
A custom method interceptor¶
When a rule needs more than an expression can express, write a @typeix/di method interceptor. It gets the same Method object, including decoratorArgs — which for createMethodInterceptor is the config object itself, not {args: config}:
@Injectable()
class AuditInterceptor implements Interceptor {
constructor(@Inject(AuditLog) private readonly log: AuditLog) {
}
async invoke(method: Method): Promise<any> {
const identity = method.injector.has(IDENTITY) ? method.injector.get(IDENTITY) as Identity : undefined;
const result = await method.invoke();
await this.log.write({handler: method.decoratorArgs, who: identity?.name});
return result;
}
}
export function Audit(label: string): MethodDecorator {
return createMethodInterceptor(Audit, AuditInterceptor, {label});
}
Always call method.invoke(), never method.invokeWithArgs() without arguments: the latter replaces the handler arguments, so every @PathParam becomes undefined.
Next¶
- Rules — the expression language both decorators use
- Protecting every endpoint — reading the identity outside a handler
- Testing — asserting a method denial