Skip to content

Protecting every endpoint

One guard chain over /docs, /graphql and websocket controllers: how the chain attaches to the request pipeline, why extension packages are covered, and how to read the identity from a handler or a service.

4 min read Source

A security chain is only useful if it covers everything it can. In resty, /docs and /graphql are registered by their own packages, yet both go through the same request pipeline as your controllers — so one chain covers them. Websocket connections are the exception, and are handled explicitly below.

Why it works: the request pipeline

pipeServer builds one ServerConfig and passes it to createRouteHandler for every route. ServerConfig carries interceptors, and createRouteHandler prepends them before controller and method interceptors:

route request
  ├─ ServerConfig.interceptors        ← the guard chain lives here
  ├─ controller interceptors
  ├─ method interceptors              ← @Guard / @GuardResult
  └─ handler

@SecurityConfiguration does not require you to touch pipeServer. It publishes the chain through module metadata, and the server reads it:

@SecurityConfiguration({ … })
@RootModule({ … })
class Application {}

await pipeServer(server, Application);    // unchanged

@typeix/resty-swagger and @typeix/resty-graphql register their routes through createRouteHandler rather than the raw router, which is exactly why the chain reaches them. That was a deliberate change in the framework: routing those packages through the raw router would have left /docs and /graphql outside the pipeline.

Docs and GraphQL

@SecurityConfiguration({
  authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
    .add(new LoginChecker(store, new ScryptPasswordHasher())),
  guards: guards => guards
    .match("/health", "allow()")
    .match("/docs/**", "inGrant('DEVELOPER')")
    .match("/graphql", "inGrant('DEVELOPER')")
    .anyRequest("identified()")
})
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator], controllers: [ArticlesController]})
class Application {}

await pipeSwagger(server, Application, {path: "/docs"});
await pipeGraphQL(server, Application, {path: "/graphql"});
Path Rule
/docs, /docs/** developers only
/graphql developers only, then the GraphQL layer parses the query

Authentication completes before query parsing for GraphQL, so an unauthenticated caller never reaches the schema executor and an expensive query cannot be used as an unauthenticated denial-of-service vector.

/docs/** covers the UI, the JSON document and every asset the UI loads, because the swagger package registers them as one prefix.

Websockets

Websocket and Socket.IO connections build their own injector and do not pass through createRouteHandler, so the guard chain does not evaluate rules for individual messages. The handshake is an http request, which is where access should be decided:

@Controller({path: "/live"})
class LiveHandshakeController {
  /** the upgrade is a normal route, so the chain and its rules apply here */
  @GET()
  authorize(@CurrentIdentity() who: Identity): object {
    return {ok: who.authenticated};
  }
}

The websocket controller itself shares the module injector, so it can inject the authenticator and check a credential carried in the first message before handling anything:

@WebSocketController({path: "/live"})
class LiveController {
  constructor(@Inject(DefaultAuthenticator) private readonly authenticator: DefaultAuthenticator) {
  }

  @Subscribe("message")
  async onMessage(payload: {text: string; token?: string}) {
    const identity = await this.authenticator.authenticate({kind: "token", value: payload.token ?? ""});
    if (identity === null) {
      return {error: "unauthorized"};
    }
    return {from: identity.name, text: payload.text};
  }
}

Treat this as application logic: there is no route rule protecting a websocket message, so the check belongs at the top of the handler, before any side effect.

Reading the identity

In a handler

@Controller({path: "/me"})
class MeController {
  @GET()
  read(@CurrentIdentity() who: Identity) {
    return {name: who.name, grants: who.grants, tenant: who.attributes?.tenant};
  }
}

@CurrentIdentity() is parameter-only: the identity is resolved after the controller instance is constructed, so a decorated property would keep its initial value.

In a request-scoped service

Inject IDENTITY_CONTEXT, which is mutable and updated by the chain before the handler runs:

import {IDENTITY_CONTEXT, IdentityContext} from "@typeix/resty-security";

@Injectable()
class AuditService {
  constructor(@Inject(IDENTITY_CONTEXT) private readonly context: IdentityContext) {
  }

  current(): Identity {
    return this.context.identity;
  }
}

In a plain function

The value token IDENTITY is set on the request injector, so anything that receives the injector can read it:

import {IDENTITY} from "@typeix/resty-security";

const identity = injector.has(IDENTITY) ? injector.get(IDENTITY) as Identity : GUEST_IDENTITY;

A chain without the decorator

@SecurityConfiguration is the convenient path, but a chain can be registered explicitly. This is useful in tests, or when the rules are built dynamically:

import {DefaultAuthenticator, GuardChain, TokenChecker, buildGuards} from "@typeix/resty-security";
import {pipeServer} from "@typeix/resty";

const authenticator = new DefaultAuthenticator().add(new TokenChecker(verifyOpaqueToken));

const chain = new GuardChain({
  guards: buildGuards(guards => guards.anyRequest("identified()")),
  authenticator,
  challengeMessage: "Unauthorized",
  denialMessage: "Forbidden"
});

await pipeServer(server, Application, {interceptors: [{provide: GuardChain, useValue: chain}]});

The chain is registered as a value, because it already carries its parsed rules and resty invokes the interceptor instance it finds.

Several applications in one process

Each root module gets its own chain, its own authenticator and its own rules. Because @SecurityConfiguration reads the module's own shared_providers, two applications in one process do not interfere — the package suite relies on this and registers several secured applications in a single jest process.

Next

  • Method rules — narrowing a single handler
  • Rules — the patterns used above
  • Testing — asserting a protected endpoint