Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

121 changes: 105 additions & 16 deletions middleware/auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { assertEquals } from "@std/assert";
import { assertEquals, assertRejects } from "@std/assert";
import auth from "./auth.ts";

const acceptValid = (value: string) => value === "valid";

function request(path: string, cookie?: string): Request {
const headers = new Headers();
if (cookie) headers.set("cookie", cookie);
Expand All @@ -9,7 +11,7 @@ function request(path: string, cookie?: string): Request {

Deno.test("auth redirects to the sign-in page without the cookie", async () => {
let nextCalled = false;
const middleware = auth();
const middleware = auth({ verify: acceptValid });

const response = await middleware(request("/private"), () => {
nextCalled = true;
Expand All @@ -21,37 +23,108 @@ Deno.test("auth redirects to the sign-in page without the cookie", async () => {
assertEquals(nextCalled, false);
});

Deno.test("auth redirect does not echo request headers", async () => {
const headers = new Headers({
cookie: "session=secret",
authorization: "Bearer token",
Deno.test("auth does not call verify when the cookie is missing", async () => {
let verifyCalled = false;
const middleware = auth({
verify: () => {
verifyCalled = true;
return true;
},
});
const middleware = auth();

const response = await middleware(
new Request("http://localhost/private", { headers }),
request("/private"),
() => new Response("secret"),
);

assertEquals(response.headers.get("cookie"), null);
assertEquals(response.headers.get("authorization"), null);
assertEquals(response.headers.get("location"), "/signin");
assertEquals(response.status, 302);
assertEquals(verifyCalled, false);
});

Deno.test("auth redirects when verify rejects the cookie value", async () => {
let nextCalled = false;
const middleware = auth({ verify: acceptValid });

const response = await middleware(
request("/private", "authenticated=forged"),
() => {
nextCalled = true;
return new Response("secret");
},
);

assertEquals(response.status, 302);
assertEquals(nextCalled, false);
});

Deno.test("auth lets requests with the cookie through", async () => {
const middleware = auth();
Deno.test("auth lets requests through when verify accepts the value", async () => {
const middleware = auth({ verify: acceptValid });

const response = await middleware(
request("/private", "authenticated=1"),
request("/private", "authenticated=valid"),
() => new Response("secret"),
);

assertEquals(response.status, 200);
assertEquals(await response.text(), "secret");
});

Deno.test("auth supports an async verify that receives the request", async () => {
let seenPath: string | undefined;
const middleware = auth({
verify: async (value, req) => {
seenPath = new URL(req.url).pathname;
await Promise.resolve();
return value === "valid";
},
});

const response = await middleware(
request("/private", "authenticated=valid"),
() => new Response("secret"),
);

assertEquals(response.status, 200);
assertEquals(seenPath, "/private");
});

Deno.test("auth propagates errors thrown by verify", async () => {
const middleware = auth({
verify: () => {
throw new Error("store unavailable");
},
});

await assertRejects(
async () =>
await middleware(
request("/private", "authenticated=valid"),
() => new Response("secret"),
),
Error,
"store unavailable",
);
});

Deno.test("auth redirect does not echo request headers", async () => {
const headers = new Headers({
cookie: "session=secret",
authorization: "Bearer token",
});
const middleware = auth({ verify: acceptValid });

const response = await middleware(
new Request("http://localhost/private", { headers }),
() => new Response("secret"),
);

assertEquals(response.headers.get("cookie"), null);
assertEquals(response.headers.get("authorization"), null);
assertEquals(response.headers.get("location"), "/signin");
});

Deno.test("auth does not redirect requests to the sign-in page itself", async () => {
const middleware = auth();
const middleware = auth({ verify: acceptValid });

const response = await middleware(
request("/signin"),
Expand All @@ -63,7 +136,7 @@ Deno.test("auth does not redirect requests to the sign-in page itself", async ()
});

Deno.test("auth honors a custom sign-in path", async () => {
const middleware = auth({ signin: "/login" });
const middleware = auth({ verify: acceptValid, signin: "/login" });

const redirected = await middleware(
request("/private"),
Expand All @@ -78,3 +151,19 @@ Deno.test("auth honors a custom sign-in path", async () => {
);
assertEquals(allowed.status, 200);
});

Deno.test("auth reads a custom cookie name", async () => {
const middleware = auth({ verify: acceptValid, cookie: "token" });

const ignored = await middleware(
request("/private", "authenticated=valid"),
() => new Response("secret"),
);
assertEquals(ignored.status, 302, "the default cookie name is not read");

const allowed = await middleware(
request("/private", "token=valid"),
() => new Response("secret"),
);
assertEquals(allowed.status, 200);
});
36 changes: 29 additions & 7 deletions middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,47 @@ import { STATUS_CODE, STATUS_TEXT } from "@std/http/status";

/** Options for the {@linkcode auth} middleware. */
export interface Options {
/**
* Decides whether the value of the authentication cookie is valid, for
* example by looking it up in a session store or checking a signature. It is
* only called when the cookie is present. Requests it rejects are redirected
* to the sign-in page.
*/
verify: (value: string, request: Request) => boolean | Promise<boolean>;
/** Path of the sign-in page. Requests to it are never redirected. Defaults to `/signin`. */
signin?: string;
/** Name of the cookie that holds the credential. Defaults to `authenticated`. */
cookie?: string;
}

/**
* Redirects requests without an `authenticated` cookie to the sign-in page.
* Redirects requests that do not carry a valid authentication cookie to the
* sign-in page.
*
* This only checks that the cookie is present, not that its value was issued by
* the server, so it must not be relied on as real authentication.
* The middleware does not issue or validate credentials itself: `verify` decides
* whether the cookie's value is acceptable. Use a value the server created, such
* as a session id it can look up, never one a client could make up.
*
* @example
* ```ts
* import auth from "./auth.ts";
*
* const sessions = new Set<string>(); // ids issued at sign-in
* const middleware = auth({ verify: (value) => sessions.has(value) });
* ```
*/
export default function auth(options?: Options): Middleware {
const signin = options?.signin ?? "/signin";
export default function auth(options: Options): Middleware {
const { verify } = options;
const signin = options.signin ?? "/signin";
const cookieName = options.cookie ?? "authenticated";
return async function authMiddleware(
request: Request,
next: NextHandler,
): Promise<Response> {
const url = new URL(request.url);
const cookies = getCookies(request.headers);
const allowed = cookies?.authenticated || url.pathname === signin;
const value = getCookies(request.headers)[cookieName];
const allowed = url.pathname === signin ||
(value !== undefined && await verify(value, request));

if (allowed) {
return await next();
Expand Down
55 changes: 54 additions & 1 deletion middleware/csrf.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assert, assertEquals, assertNotEquals } from "@std/assert";
import { getSetCookies } from "@std/http/cookie";
import csrf, { generateCSRFToken } from "./csrf.ts";
import csrf, { csrfToken, generateCSRFToken } from "./csrf.ts";

function post(body: string, cookie?: string): Request {
const headers = new Headers({
Expand Down Expand Up @@ -178,6 +178,59 @@ Deno.test("csrf rejects a request when the cookie is missing", async () => {
assertEquals(response.status, 403);
});

Deno.test("csrfToken gives handlers the token on a first request", async () => {
const middleware = csrf();
const request = new Request("http://localhost/");
let seen: string | undefined;

const response = await middleware(request, () => {
seen = csrfToken(request);
return new Response("ok");
});

assert(seen, "the handler can read the token before the cookie exists");
const cookie = getSetCookies(response.headers).find((c) =>
c.name === "csrf_token"
);
assertEquals(cookie?.value, seen, "the cookie carries the same token");
});

Deno.test("csrfToken returns the token from the cookie on later requests", async () => {
const middleware = csrf();
const request = new Request("http://localhost/", {
headers: { cookie: "csrf_token=existing" },
});
let seen: string | undefined;

await middleware(request, () => {
seen = csrfToken(request);
return new Response("ok");
});

assertEquals(seen, "existing");
});

Deno.test("csrfToken is undefined for a request without a token", () => {
assertEquals(csrfToken(new Request("http://localhost/")), undefined);
});

Deno.test("a token read from csrfToken is accepted when submitted back", async () => {
const middleware = csrf();
const first = new Request("http://localhost/");
let token: string | undefined;
await middleware(first, () => {
token = csrfToken(first);
return new Response("form");
});

const response = await middleware(
post(`csrf_token=${encodeURIComponent(token!)}`, `csrf_token=${token}`),
() => new Response("ok"),
);

assertEquals(response.status, 200);
});

Deno.test("csrf responds 400 to a malformed multipart POST", async () => {
const middleware = csrf();
const request = new Request("http://localhost/form", {
Expand Down
32 changes: 26 additions & 6 deletions middleware/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,21 @@ export function generateCSRFToken(length: number = 32): string {
return btoa(String.fromCharCode(...bytes));
}

/** Tokens issued while handling a request that did not have a cookie yet. */
const issuedTokens = new WeakMap<Request, string>();

/**
* Returns the CSRF token for a request that passed through {@linkcode csrf}, to
* embed in a form or send to client code. On a visitor's first request the
* token has not reached the browser yet, so it is looked up from the request
* object itself: pass the same `Request` the middleware received.
*
* @returns The token, or `undefined` if the request did not pass through `csrf()`
*/
export function csrfToken(request: Request): string | undefined {
return issuedTokens.get(request) ?? getCookies(request.headers)["csrf_token"];
}

/**
* Reads the token a request submitted: the `x-csrf-token` header if present,
* otherwise the `csrf_token` field of a form body. Throws if a form body cannot
Expand Down Expand Up @@ -40,8 +55,9 @@ async function submittedToken(request: Request): Promise<string | null> {
* back, either in an `x-csrf-token` header or in a `csrf_token` form field, or
* they are rejected with `403`. A form body that cannot be parsed gets `400`.
*
* The cookie is `httpOnly`, so scripts cannot read it. Server-side code has to
* read it from the request's cookies to render it into a page.
* The cookie is `httpOnly`, so scripts cannot read it. Handlers that render a
* form or page call {@linkcode csrfToken} with the request to get the value to
* embed, including on a visitor's first request, before the cookie exists.
*/
export default function csrf(): Middleware {
return async function csrfMiddleware(
Expand All @@ -50,7 +66,7 @@ export default function csrf(): Middleware {
): Promise<Response> {
const url = new URL(request.url);
const cookies = getCookies(request.headers);
const csrfToken = cookies?.["csrf_token"];
const existing = cookies?.["csrf_token"];

if (!SAFE_METHODS.has(request.method.toUpperCase())) {
let submitted: string | null;
Expand All @@ -60,16 +76,20 @@ export default function csrf(): Middleware {
return new Response("Bad Request", { status: 400 });
}

if (!submitted || submitted !== csrfToken) {
if (!submitted || submitted !== existing) {
return new Response("Invalid CSRF token", { status: 403 });
}
}

// Issue the token before running the handler so it can embed the value in the
// page it renders, then send it to the browser as a cookie.
const token = existing ?? generateCSRFToken();
if (!existing) issuedTokens.set(request, token);

const response = await next();

if (!csrfToken) {
if (!existing) {
const https = url.protocol === "https:";
const token = generateCSRFToken();
setCookie(response.headers, {
name: "csrf_token",
value: token,
Expand Down
2 changes: 1 addition & 1 deletion middleware/deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@stewpot/middleware",
"version": "0.4.1",
"version": "0.5.0",
"license": "MIT",
"exports": {
".": "./main.ts",
Expand Down
Loading