Testing¶
Test a security rule without a server, test a secured endpoint over real http, and assert the boot errors that make a typo fail at startup instead of at request time.
Three things are worth testing in an application that uses this package, and each has a different shape:
| Test | Tool | Cost |
|---|---|---|
| a rule decides correctly | buildGuards(...).allows(...) | no server, microseconds |
| an endpoint is actually protected | http.createServer + pipeServer | one server per suite |
| a bad rule fails at boot | the decorator, called directly | no server |
The package suite itself uses exactly these three, plus forged JWTs for the attack cases.
A rule, without a server¶
buildGuards returns the same object the chain uses, and allows takes the request plus the identity:
import {buildGuards} from "@typeix/resty-security";
const guards = buildGuards(g => g
.match("/articles", "may('article:write')", ["POST"])
.match("/articles/<id>", "method != 'DELETE' or may('article:delete')")
.anyRequest("identified()"));
expect(guards.allows({path: "/articles", method: "GET"}, identity).allowed).toBe(true);
expect(guards.allows({path: "/articles", method: "POST"}, withoutGrant).allowed).toBe(false);
expect(guards.allows({path: "/articles/1", method: "DELETE"}, editor).allowed).toBe(false);
The request object accepts path, method, params, headers and query, so a rule that reads a header or a route parameter is testable the same way:
guards.allows({
path: "/v2/articles",
method: "GET",
headers: {"x-api-version": "2"},
query: new URLSearchParams("page=2")
}, identity);
Build identities with identityOf so the fixture stays obvious:
const editor = identityOf({name: "ada", grants: ["ROLE_EDITOR", "article:write"]});
const guest = guestIdentity();
This shape is the fastest way to get exhaustive coverage of a rule list: no I/O, no clock, no server.
A secured endpoint, over real http¶
A rule test proves the decision. It cannot prove the chain is wired, that the status code is right, or that the handler did not run. For that, start a real server:
import {createServer, IncomingMessage, request as httpRequest} from "http";
import {AddressInfo} from "net";
import {Controller, GET, Injectable, pipeServer, RootModule} from "@typeix/resty";
import {
DefaultAuthenticator, Identity, IdentityStore, LoginChecker,
ScryptPasswordHasher, SecurityConfiguration, identityOf
} from "@typeix/resty-security";
declare const storedHash: string;
@Injectable()
class UsersStore implements IdentityStore {
async find(name: string): Promise<Identity | null> {
return name === "ada" ? identityOf({name, grants: ["ROLE_EDITOR"]}) : null;
}
async passwordOf(name: string): Promise<string | null> {
return name === "ada" ? storedHash : null;
}
}
@Controller({path: "/articles"})
class ArticlesController {
@GET()
list(): object {
return {articles: []};
}
}
@SecurityConfiguration({
authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
.add(new LoginChecker(store, new ScryptPasswordHasher())),
guards: guards => guards
.match("/health", "allow()")
.anyRequest("identified()")
})
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator], controllers: [ArticlesController]})
class Application {
}
let server: ReturnType<typeof createServer>;
let port: number;
beforeAll(async () => {
server = createServer();
await pipeServer(server, Application);
await new Promise<void>(resolve => server.listen(0, () => resolve()));
port = (server.address() as AddressInfo).port;
});
afterAll(async () => {
await new Promise<void>(resolve => server.close(() => resolve()));
});
function send(path: string, headers: Record<string, string> = {}): Promise<{status: number; body: any}> {
return new Promise((resolve, reject) => {
const req = httpRequest({port, path, headers}, (res: IncomingMessage) => {
const chunks: Array<Buffer> = [];
res.on("data", chunk => chunks.push(chunk));
res.on("end", () => {
const text = Buffer.concat(chunks).toString("utf8");
resolve({status: res.statusCode, body: text.length === 0 ? undefined : JSON.parse(text)});
});
});
req.on("error", reject);
req.end();
});
}
it("should reject an anonymous caller", async () => {
expect((await send("/articles")).status).toBe(401);
});
it("should accept a valid login", async () => {
const basic = Buffer.from("ada:secret").toString("base64");
expect((await send("/articles", {authorization: `Basic ${basic}`})).status).toBe(200);
});
Notes that save time:
listen(0)lets the OS pick a port, so parallel suites never collide.- Assert the status and the body where the message is configurable — a
200with an empty body is not a pass. - Test the open route by its
404. A route that does not exist but was allowed answers404; a denied one answers401. That ambiguity is the fastest way to tell the two apart, and the package suite relies on it.
A method rule¶
Method rules are only reachable through the pipeline, so test them over http too:
@Controller({path: "/articles"})
class ArticlesController {
@DELETE("/<id>")
@Guard("may('article:delete')")
remove(@PathParam("id") id: string): object {
return {deleted: id};
}
@GET("/<id>")
@GuardResult("result.owner == identity.name")
read(@PathParam("id") id: string): object {
return {owner: "bob"};
}
}
Request as ada (editor, no delete permission) | Expected |
|---|---|
DELETE /articles/1 | 403, and the handler must not have run |
GET /articles/1 where the article is owned by bob | 403 |
To prove the handler did not run, give it a side effect — a counter on the controller instance, or a spy on a service it calls — and assert the counter is unchanged.
A boot error¶
The decorators parse at class definition time, so a bad rule is testable without a server:
it("should reject an unknown rule function", () => {
expect(() => Guard("hasRole('ADMIN')")).toThrow(/unknown rule function "hasRole"/);
});
it("should reject a route parameter on a method", () => {
expect(() => Guard("#id == identity.name")).toThrow(/only available in a route rule/);
});
it("should reject a rule declared after anyRequest", () => {
expect(() => buildGuards(g => g.anyRequest("identified()").match("/x", "allow()")))
.toThrow(/declared after anyRequest/);
});
Asserting the message, not just toThrow(), is what keeps the error useful — these messages are documentation.
Testing a JWT¶
Never build a token by hand: a hand-built token verifies the implementation against itself. Use signJwt, and pin the clock with now:
import {JwtVerifier, signJwt} from "@typeix/resty-security";
let clock = 1_700_000_000;
const verifier = new JwtVerifier({algorithms: ["HS256"], secret: SECRET, now: () => clock});
const token = signJwt({sub: "ada", exp: clock + 60}, {secret: SECRET});
expect(await verifier.resolve(token)).not.toBeNull();
clock += 61;
expect(await verifier.resolve(token)).toBeNull();
For the attack cases — alg: none, an HS256 token signed with an RSA public key, a header edited after signing — forging the token is the point, because that is exactly what an attacker does.
Asserting the identity a handler saw¶
The handler can report it, which makes an integration test readable:
@Controller({path: "/me"})
class MeController {
@GET()
read(@CurrentIdentity() who: Identity): object {
return {name: who.name, grants: who.grants, authenticated: who.authenticated};
}
}
const response = await send("/me", {authorization: "Bearer good"});
expect(response.body).toEqual({name: "ada", grants: ["ROLE_EDITOR"], authenticated: true});
That one assertion proves the credential parser, the checker, the identity model and the injection all agree — which is more than four separate unit tests would tell you.
What the package suite covers¶
As a reference for what a thorough security test suite looks like:
| Area | Cases |
|---|---|
| rule grammar | every function × identity shape × request scope, plus a completeness test that fails when a function is added without a case |
| patterns | inline regex, nested templates, method restriction, trailing slash, parity with @typeix/router |
| chain | 401 vs 403, header and prefix handling, guest factory, identity propagation |
| decorators | @Guard, @GuardResult, @Open, stacked @Guard, the boot errors |
| configuration | every authenticator form, reuse, shared-provider normalization |
| JWT | forged tokens, claims, clock, algorithm confusion |
| performance | parse and evaluate budgets, as regression guards |
The HTTP integration suites caught what the unit tests could not: a wrong decoratorArgs shape that made every @Guard silently allow, an argument wipe in invokeWithArgs, a method denial surfacing as 404, and a method rule that could not read the request at all. When you test your own integration, do the same — go through a real server.
Next¶
- Rules — what to assert
- Method rules — the decorators used above
- JWT —
signJwtand the verifier options