diff --git a/backend/.env.example b/backend/.env.example index eb06131..2f2c635 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1 +1,7 @@ -DATABASE_URL=postgresql://vinmonopolet_app:change_me@localhost:5432/vinmonopolet \ No newline at end of file +DATABASE_URL=postgresql://vinmonopolet_app:change_me@localhost:5432/vinmonopolet + +# Optional. Set to true only when the site is served over HTTPS, so the login cookie is only sent over HTTPS. +# COOKIE_SECURE=true + +# The PostgreSQL tests (src/auth/user-store.db.test.ts) read TEST_DATABASE_URL from the shell, not from +# this file. Without it, they are skipped. See "Database tests" in docs/api.md. diff --git a/backend/migrations/1794488612043_create-user-tables.sql b/backend/migrations/1794488612043_create-user-tables.sql new file mode 100644 index 0000000..b5e41e5 --- /dev/null +++ b/backend/migrations/1794488612043_create-user-tables.sql @@ -0,0 +1,33 @@ +-- Up Migration + +-- Registered users. "user" is a reserved word in PostgreSQL, so the table is called app_user. +-- Other tables refer to the generated id, never to the username, so a username can be changed +-- later without touching reviews, favourites or follows. +CREATE TABLE app_user ( + id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + -- Stored in lowercase. Same rule as USERNAME_PATTERN in backend/src/auth/credentials.ts. + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,30}$'), + -- scrypt hash with salt and parameters, see backend/src/auth/password.ts. Never the password. + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- One row per logged-in browser. Only the SHA-256 hash of the cookie token is stored, +-- so someone who reads the database still cannot log in as a user. +CREATE TABLE user_session ( + token_hash bytea PRIMARY KEY, + user_id integer NOT NULL REFERENCES app_user (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL +); + +-- For "log out everywhere" and for deleting a user's sessions. +CREATE INDEX user_session_user ON user_session (user_id); + +-- For removing expired sessions. +CREATE INDEX user_session_expires ON user_session (expires_at); + +-- Down Migration + +DROP TABLE user_session; +DROP TABLE app_user; \ No newline at end of file diff --git a/backend/src/auth/auth-api.test.ts b/backend/src/auth/auth-api.test.ts new file mode 100644 index 0000000..88f6f85 --- /dev/null +++ b/backend/src/auth/auth-api.test.ts @@ -0,0 +1,175 @@ +// API tests: real GraphQL requests through Apollo Server, with the in-memory store instead of +// PostgreSQL. A small fake browser keeps the session cookie between requests. +import { ApolloServer } from '@apollo/server'; +import { describe, expect, it } from 'vitest'; +import { typeDefs } from '../schema'; +import { createMemoryUserStore } from '../test/memory-user-store'; +import { createAuthContext, type AuthContext } from './auth-context'; +import { createAuthService } from './auth-service'; +import type { CookieJar } from './cookies'; +import { authResolvers } from './resolvers'; +import { authTypeDefs } from './schema'; + +const USER_FIELDS = 'id username createdAt'; +const REGISTER = `mutation Register($input: CredentialsInput!) { register(input: $input) { ${USER_FIELDS} } }`; +const LOGIN = `mutation Login($input: CredentialsInput!) { login(input: $input) { ${USER_FIELDS} } }`; +const LOGOUT = 'mutation Logout { logout }'; +const ME = `query Me { me { ${USER_FIELDS} } }`; + +const CREDENTIALS = { username: 'ola_n', password: 'langt-nok-passord' }; + +function setup() { + const { store, users } = createMemoryUserStore(); + const service = createAuthService(store, { scryptParams: { N: 1024, r: 8, p: 1 } }); + const server = new ApolloServer<{ auth: AuthContext }>({ + typeDefs: [typeDefs, authTypeDefs], + resolvers: authResolvers, + }); + + /** Like a browser: keeps the cookie the server sets and sends it with the next request. */ + function createBrowser() { + let cookie: string | undefined; + const jar: CookieJar = { + setSession: (token) => (cookie = token), + clearSession: () => (cookie = undefined), + }; + + async function request(query: string, variables?: Record) { + const response = await server.executeOperation( + { query, variables }, + { contextValue: { auth: createAuthContext(service, cookie, jar) } }, + ); + if (response.body.kind !== 'single') throw new Error('Expected a single result'); + return response.body.singleResult; + } + + return { request, cookie: () => cookie, setCookie: (value: string) => (cookie = value) }; + } + + return { createBrowser, users }; +} + +const codeOf = (result: { errors?: readonly { extensions?: Record }[] }) => + result.errors?.[0]?.extensions?.code; + +describe('auth API', () => { + it('me is null for a visitor without a cookie', async () => { + const browser = setup().createBrowser(); + const result = await browser.request(ME); + expect(result.errors).toBeUndefined(); + expect(result.data).toEqual({ me: null }); + }); + + it('register sets a cookie, and me then returns the new user', async () => { + const browser = setup().createBrowser(); + const registered = await browser.request(REGISTER, { input: CREDENTIALS }); + expect(registered.data?.register).toMatchObject({ id: expect.any(String), username: 'ola_n' }); + expect(browser.cookie()).toBeDefined(); + + const me = await browser.request(ME); + expect(me.data?.me).toEqual(registered.data?.register); + }); + + it('returns createdAt as an ISO date', async () => { + const browser = setup().createBrowser(); + const result = await browser.request(REGISTER, { input: CREDENTIALS }); + const { createdAt } = result.data?.register as { createdAt: string }; + expect(new Date(createdAt).toISOString()).toBe(createdAt); + }); + + it('the schema has no field that can expose the password hash', async () => { + const browser = setup().createBrowser(); + const result = await browser.request(`query { me { passwordHash } }`); + expect(result.errors?.[0]?.message).toMatch(/Cannot query field "passwordHash"/); + }); + + it('login works from another browser, and both are logged in', async () => { + const { createBrowser } = setup(); + const laptop = createBrowser(); + const phone = createBrowser(); + await laptop.request(REGISTER, { input: CREDENTIALS }); + + const login = await phone.request(LOGIN, { input: CREDENTIALS }); + expect(login.data?.login).toMatchObject({ username: 'ola_n' }); + expect(phone.cookie()).not.toBe(laptop.cookie()); + expect((await laptop.request(ME)).data?.me).not.toBeNull(); + expect((await phone.request(ME)).data?.me).not.toBeNull(); + }); + + it('logout clears the cookie and ends only that session', async () => { + const { createBrowser } = setup(); + const laptop = createBrowser(); + const phone = createBrowser(); + await laptop.request(REGISTER, { input: CREDENTIALS }); + await phone.request(LOGIN, { input: CREDENTIALS }); + + expect((await phone.request(LOGOUT)).data).toEqual({ logout: true }); + expect(phone.cookie()).toBeUndefined(); + expect((await phone.request(ME)).data).toEqual({ me: null }); + expect((await laptop.request(ME)).data?.me).not.toBeNull(); + }); + + it('an old cookie stops working after logging in again', async () => { + const browser = setup().createBrowser(); + await browser.request(REGISTER, { input: CREDENTIALS }); + const oldCookie = browser.cookie(); + await browser.request(LOGIN, { input: CREDENTIALS }); + expect(browser.cookie()).not.toBe(oldCookie); + }); + + it('logout without a session still returns true', async () => { + const browser = setup().createBrowser(); + expect((await browser.request(LOGOUT)).data).toEqual({ logout: true }); + }); + + it.each([ + [{ username: 'x', password: 'langt-nok-passord' }, 'username', 'USERNAME_TOO_SHORT'], + [{ username: 'ola nordmann', password: 'langt-nok-passord' }, 'username', 'USERNAME_INVALID_CHARACTERS'], + [{ username: 'ola_n', password: 'kort' }, 'password', 'PASSWORD_TOO_SHORT'], + ])('register rejects %j with field and reason', async (input, field, reason) => { + const { createBrowser, users } = setup(); + const browser = createBrowser(); + const result = await browser.request(REGISTER, { input }); + expect(result.errors?.[0]?.extensions).toMatchObject({ code: 'BAD_USER_INPUT', field, reason }); + expect(browser.cookie()).toBeUndefined(); + expect(users).toHaveLength(0); + }); + + it('register rejects a taken username', async () => { + const { createBrowser } = setup(); + await createBrowser().request(REGISTER, { input: CREDENTIALS }); + const result = await createBrowser().request(REGISTER, { input: { ...CREDENTIALS, username: 'OLA_N' } }); + expect(codeOf(result)).toBe('USERNAME_TAKEN'); + }); + + it('login with a wrong password gives INVALID_CREDENTIALS and no cookie', async () => { + const { createBrowser } = setup(); + await createBrowser().request(REGISTER, { input: CREDENTIALS }); + const browser = createBrowser(); + const result = await browser.request(LOGIN, { input: { ...CREDENTIALS, password: 'feil-passord' } }); + expect(codeOf(result)).toBe('INVALID_CREDENTIALS'); + expect(browser.cookie()).toBeUndefined(); + }); + + it('a forged or changed cookie is treated as logged out', async () => { + const { createBrowser } = setup(); + const owner = createBrowser(); + await owner.request(REGISTER, { input: CREDENTIALS }); + const real = owner.cookie()!; + + const attacker = createBrowser(); + for (const forged of [`${real.slice(0, -1)}${real.endsWith('A') ? 'B' : 'A'}`, 'not-a-token', '']) { + attacker.setCookie(forged); + expect((await attacker.request(ME)).data).toEqual({ me: null }); + } + }); +}); + +describe('requireUser', () => { + it('throws UNAUTHENTICATED without a session, for features that need a logged-in user', async () => { + const { store } = createMemoryUserStore(); + const service = createAuthService(store, { scryptParams: { N: 1024, r: 8, p: 1 } }); + const auth = createAuthContext(service, undefined, { setSession() {}, clearSession() {} }); + await expect(auth.requireUser()).rejects.toMatchObject({ extensions: { code: 'UNAUTHENTICATED' } }); + }); +}); diff --git a/backend/src/auth/auth-context.ts b/backend/src/auth/auth-context.ts new file mode 100644 index 0000000..6315fbe --- /dev/null +++ b/backend/src/auth/auth-context.ts @@ -0,0 +1,50 @@ +// The auth part of the GraphQL context: one per request. Resolvers use this instead of reading +// cookies themselves, and features that need a logged-in user call requireUser(). +import type { AuthResult, AuthService, PublicUser } from './auth-service'; +import type { CookieJar } from './cookies'; +import type { CredentialsInput } from './credentials'; +import { AuthErrorCode, authError } from './errors'; + +export interface AuthContext { + /** The logged-in user, or null. Looked up at most once per request, and only if a resolver asks. */ + currentUser(): Promise; + /** The logged-in user, or an UNAUTHENTICATED error. Use this in resolvers for favourites, reviews and so on. */ + requireUser(): Promise; + register(input: CredentialsInput): Promise; + login(input: CredentialsInput): Promise; + logout(): Promise; +} + +export function createAuthContext(service: AuthService, token: string | undefined, cookies: CookieJar): AuthContext { + let current: Promise | undefined; + + const currentUser = () => (current ??= service.userForToken(token)); + + async function signIn(start: () => Promise): Promise { + const { user, session } = await start(); + // A new login replaces the old session in this browser, so an old token stops working. + await service.logout(token); + cookies.setSession(session.token, session.expiresAt); + current = Promise.resolve(user); + return user; + } + + return { + currentUser, + + async requireUser() { + const user = await currentUser(); + if (!user) throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); + return user; + }, + + register: (input) => signIn(() => service.register(input)), + login: (input) => signIn(() => service.login(input)), + + async logout() { + await service.logout(token); + cookies.clearSession(); + current = Promise.resolve(null); + }, + }; +} diff --git a/backend/src/auth/auth-service.test.ts b/backend/src/auth/auth-service.test.ts new file mode 100644 index 0000000..ab28675 --- /dev/null +++ b/backend/src/auth/auth-service.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest'; +import { createMemoryUserStore } from '../test/memory-user-store'; +import { createAuthService, type AuthServiceOptions } from './auth-service'; +import { createAttemptLimiter } from './rate-limit'; +import { hashSessionToken } from './session-token'; + +const FAST = { N: 1024, r: 8, p: 1 }; +const CREDENTIALS = { username: 'Kari', password: 'langt-nok-passord' }; + +function setup(options: AuthServiceOptions = {}) { + let time = new Date('2026-11-12T12:00:00Z'); + const now = () => time; + const memory = createMemoryUserStore(now); + const service = createAuthService(memory.store, { scryptParams: FAST, now, ...options }); + return { ...memory, service, advanceDays: (days: number) => (time = new Date(time.getTime() + days * 86_400_000)) }; +} + +/** The error code, so tests do not depend on the developer message. */ +async function codeOf(promise: Promise) { + try { + await promise; + } catch (error) { + return (error as { extensions?: { code?: string } }).extensions?.code; + } + return undefined; +} + +describe('register', () => { + it('creates a user with a generated id and a lowercase username', async () => { + const { service } = setup(); + const { user } = await service.register(CREDENTIALS); + expect(user).toMatchObject({ id: expect.any(Number), username: 'kari' }); + }); + + it('stores a hash, never the password', async () => { + const { service, users } = setup(); + await service.register(CREDENTIALS); + expect(users[0].passwordHash).toMatch(/^scrypt\$/); + expect(users[0].passwordHash).not.toContain(CREDENTIALS.password); + }); + + it('does not return the password hash', async () => { + const { service } = setup(); + const { user } = await service.register(CREDENTIALS); + expect(Object.keys(user).sort()).toEqual(['createdAt', 'id', 'username']); + }); + + it('logs the user in, and only the token hash is stored', async () => { + const { service, sessions } = setup(); + const { user, session } = await service.register(CREDENTIALS); + expect(await service.userForToken(session.token)).toEqual(user); + expect([...sessions.keys()]).toEqual([hashSessionToken(session.token).toString('hex')]); + }); + + it('rejects a taken username, also with other casing', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + expect(await codeOf(service.register({ ...CREDENTIALS, username: 'KARI' }))).toBe('USERNAME_TAKEN'); + }); + + it('validates the input before anything is stored', async () => { + const { service, users } = setup(); + expect(await codeOf(service.register({ username: 'k', password: 'kort' }))).toBe('BAD_USER_INPUT'); + expect(users).toHaveLength(0); + }); +}); + +describe('login', () => { + it('logs in with the right password, ignoring the casing of the username', async () => { + const { service } = setup(); + const registered = await service.register(CREDENTIALS); + const { user } = await service.login({ ...CREDENTIALS, username: ' KARI ' }); + expect(user).toEqual(registered.user); + }); + + it('gives the same error for a wrong password and an unknown username', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + expect(await codeOf(service.login({ ...CREDENTIALS, password: 'feil-passord' }))).toBe('INVALID_CREDENTIALS'); + expect(await codeOf(service.login({ ...CREDENTIALS, username: 'finnes_ikke' }))).toBe('INVALID_CREDENTIALS'); + }); + + it('rejects a password that is too long without hashing it', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + expect(await codeOf(service.login({ ...CREDENTIALS, password: 'a'.repeat(10_000) }))).toBe('INVALID_CREDENTIALS'); + }); + + it('gives each login its own session', async () => { + const { service } = setup(); + await service.register(CREDENTIALS); + const first = await service.login(CREDENTIALS); + const second = await service.login(CREDENTIALS); + expect(first.session.token).not.toBe(second.session.token); + }); + + it('pauses a username after too many failures, and the right password is also refused', async () => { + const loginLimiter = createAttemptLimiter({ maxAttempts: 2, windowMs: 60_000 }); + const { service } = setup({ loginLimiter }); + await service.register(CREDENTIALS); + await codeOf(service.login({ ...CREDENTIALS, password: 'feil-1-passord' })); + await codeOf(service.login({ ...CREDENTIALS, password: 'feil-2-passord' })); + expect(await codeOf(service.login(CREDENTIALS))).toBe('TOO_MANY_ATTEMPTS'); + }); + + it('removes expired sessions', async () => { + const { service, sessions, advanceDays } = setup({ sessionDays: 1 }); + await service.register(CREDENTIALS); + advanceDays(2); + await service.login(CREDENTIALS); + expect(sessions.size).toBe(1); + }); +}); + +describe('sessions', () => { + it('stop working after logout', async () => { + const { service } = setup(); + const { session } = await service.register(CREDENTIALS); + await service.logout(session.token); + expect(await service.userForToken(session.token)).toBeNull(); + }); + + it('expire after the configured number of days', async () => { + const { service, advanceDays } = setup({ sessionDays: 30 }); + const { session } = await service.register(CREDENTIALS); + advanceDays(29); + expect(await service.userForToken(session.token)).not.toBeNull(); + advanceDays(2); + expect(await service.userForToken(session.token)).toBeNull(); + }); + + it('ignore missing and malformed tokens', async () => { + const { service } = setup(); + expect(await service.userForToken(undefined)).toBeNull(); + expect(await service.userForToken('not-a-token')).toBeNull(); + await expect(service.logout('not-a-token')).resolves.toBeUndefined(); + }); +}); diff --git a/backend/src/auth/auth-service.ts b/backend/src/auth/auth-service.ts new file mode 100644 index 0000000..740d032 --- /dev/null +++ b/backend/src/auth/auth-service.ts @@ -0,0 +1,102 @@ +// Registration, login, logout and "who is this?". Knows nothing about HTTP or GraphQL fields: +// it gets a UserStore and returns users and session tokens. +import { LOGIN_ATTEMPT_WINDOW_MS, MAX_LOGIN_ATTEMPTS, SESSION_DAYS } from './config'; +import { normalizeUsername, PASSWORD_MAX_LENGTH, validateCredentials, type CredentialsInput } from './credentials'; +import { AuthErrorCode, authError } from './errors'; +import { DEFAULT_SCRYPT_PARAMS, hashPassword, verifyPassword, type ScryptParams } from './password'; +import { createAttemptLimiter, type AttemptLimiter } from './rate-limit'; +import { createSessionToken, hashSessionToken, isSessionToken } from './session-token'; +import type { UserRecord, UserStore } from './user-store'; + +/** A user without the password hash. This is all that leaves the auth module. */ +export interface PublicUser { + id: number; + username: string; + createdAt: Date; +} + +export interface Session { + token: string; + expiresAt: Date; +} + +export interface AuthResult { + user: PublicUser; + session: Session; +} + +export interface AuthServiceOptions { + sessionDays?: number; + now?: () => Date; + /** Tests use cheaper parameters so they run fast. */ + scryptParams?: ScryptParams; + loginLimiter?: AttemptLimiter; +} + +export type AuthService = ReturnType; + +const DAY_MS = 24 * 60 * 60 * 1000; + +const toPublicUser = ({ id, username, createdAt }: UserRecord): PublicUser => ({ id, username, createdAt }); + +export function createAuthService(store: UserStore, options: AuthServiceOptions = {}) { + const { + sessionDays = SESSION_DAYS, + now = () => new Date(), + scryptParams = DEFAULT_SCRYPT_PARAMS, + loginLimiter = createAttemptLimiter({ maxAttempts: MAX_LOGIN_ATTEMPTS, windowMs: LOGIN_ATTEMPT_WINDOW_MS }), + } = options; + + // Compared against when the username does not exist, so a wrong username takes as long + // as a wrong password and the response time does not reveal which usernames exist. + let dummyHash: Promise | undefined; + const getDummyHash = () => (dummyHash ??= hashPassword('not-a-real-password', scryptParams)); + + async function startSession(userId: number): Promise { + const token = createSessionToken(); + const expiresAt = new Date(now().getTime() + sessionDays * DAY_MS); + await store.createSession(hashSessionToken(token), userId, expiresAt); + return { token, expiresAt }; + } + + return { + async register(input: CredentialsInput): Promise { + const { username, password } = validateCredentials(input); + const user = await store.createUser(username, await hashPassword(password, scryptParams)); + if (!user) throw authError(AuthErrorCode.USERNAME_TAKEN, 'The username is taken.', { field: 'username' }); + return { user: toPublicUser(user), session: await startSession(user.id) }; + }, + + async login(input: CredentialsInput): Promise { + const username = normalizeUsername(input.username); + if (loginLimiter.isBlocked(username)) { + throw authError(AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed logins. Try again later.'); + } + + // A password longer than any we accept can never match, so it is not hashed at all. + const tooLong = input.password.length > PASSWORD_MAX_LENGTH; + const user = tooLong ? null : await store.findUserByUsername(username); + const matches = !tooLong && (await verifyPassword(input.password, user?.passwordHash ?? (await getDummyHash()))); + + if (!user || !matches) { + loginLimiter.recordFailure(username); + // The same error for wrong username and wrong password. + throw authError(AuthErrorCode.INVALID_CREDENTIALS, 'Wrong username or password.'); + } + + loginLimiter.reset(username); + await store.deleteExpiredSessions(); // Cheap with the index, and keeps the table small. + return { user: toPublicUser(user), session: await startSession(user.id) }; + }, + + async logout(token: string | undefined): Promise { + if (isSessionToken(token)) await store.deleteSession(hashSessionToken(token)); + }, + + async userForToken(token: string | undefined): Promise { + if (!isSessionToken(token)) return null; + const user = await store.findUserBySession(hashSessionToken(token)); + return user ? toPublicUser(user) : null; + }, + }; +} diff --git a/backend/src/auth/config.ts b/backend/src/auth/config.ts new file mode 100644 index 0000000..3d71e0e --- /dev/null +++ b/backend/src/auth/config.ts @@ -0,0 +1,16 @@ +// Settings for login. Kept in one place so they are easy to find and change. + +export const SESSION_COOKIE = 'kk_session'; + +/** How long a login lasts before the user must log in again. */ +export const SESSION_DAYS = 30; + +/** Failed logins allowed per username before it is paused. */ +export const MAX_LOGIN_ATTEMPTS = 10; +export const LOGIN_ATTEMPT_WINDOW_MS = 15 * 60 * 1000; + +/** + * Secure cookies are only sent over HTTPS. The VM serves plain HTTP, so this is off unless + * COOKIE_SECURE=true is set in backend/.env. Turn it on if the site moves to HTTPS. + */ +export const COOKIE_SECURE = process.env.COOKIE_SECURE === 'true'; diff --git a/backend/src/auth/cookies.test.ts b/backend/src/auth/cookies.test.ts new file mode 100644 index 0000000..527115d --- /dev/null +++ b/backend/src/auth/cookies.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { parseCookies, sessionCookieOptions } from './cookies'; + +describe('parseCookies', () => { + it('reads several cookies', () => { + const cookies = parseCookies('kk_session=abc; theme=dark'); + expect(cookies.get('kk_session')).toBe('abc'); + expect(cookies.get('theme')).toBe('dark'); + }); + + it('returns an empty map without a header', () => { + expect(parseCookies(undefined).size).toBe(0); + expect(parseCookies('').size).toBe(0); + }); + + it('decodes values and keeps "=" inside a value', () => { + expect(parseCookies('a=b%20c; d=e=f').get('a')).toBe('b c'); + expect(parseCookies('d=e=f').get('d')).toBe('e=f'); + }); + + it('keeps the first value of a repeated name', () => { + expect(parseCookies('a=1; a=2').get('a')).toBe('1'); + }); + + it('skips broken parts instead of throwing', () => { + const cookies = parseCookies('bad; =x; broken=%E0%A4%A; ok=1'); + expect(cookies.get('ok')).toBe('1'); + expect(cookies.has('broken')).toBe(false); + }); +}); + +describe('sessionCookieOptions', () => { + it('keeps the cookie away from JavaScript and other sites', () => { + expect(sessionCookieOptions(false)).toMatchObject({ httpOnly: true, sameSite: 'lax', secure: false, path: '/' }); + expect(sessionCookieOptions(true).secure).toBe(true); + }); +}); diff --git a/backend/src/auth/cookies.ts b/backend/src/auth/cookies.ts new file mode 100644 index 0000000..04ab45b --- /dev/null +++ b/backend/src/auth/cookies.ts @@ -0,0 +1,42 @@ +// Reading and writing the session cookie. Small enough that we do not need cookie-parser. +import type { CookieOptions, Response } from 'express'; +import { SESSION_COOKIE } from './config'; + +/** Parses a Cookie header. Values that cannot be decoded are skipped. */ +export function parseCookies(header: string | undefined): Map { + const cookies = new Map(); + if (!header) return cookies; + + for (const part of header.split(';')) { + const separator = part.indexOf('='); + if (separator === -1) continue; + const name = part.slice(0, separator).trim(); + const value = part.slice(separator + 1).trim(); + if (!name || cookies.has(name)) continue; // The first value wins, as in browsers. + try { + cookies.set(name, decodeURIComponent(value)); + } catch { + // Malformed percent-encoding: ignore this cookie. + } + } + return cookies; +} + +/** The options for the session cookie. httpOnly keeps it away from JavaScript, so XSS cannot steal it. */ +export function sessionCookieOptions(secure: boolean): CookieOptions { + return { httpOnly: true, sameSite: 'lax', secure, path: '/' }; +} + +/** What the auth code needs from the response. Lets tests use a fake instead of Express. */ +export interface CookieJar { + setSession(token: string, expiresAt: Date): void; + clearSession(): void; +} + +export function createCookieJar(res: Response, secure: boolean): CookieJar { + const options = sessionCookieOptions(secure); + return { + setSession: (token, expiresAt) => res.cookie(SESSION_COOKIE, token, { ...options, expires: expiresAt }), + clearSession: () => res.clearCookie(SESSION_COOKIE, options), + }; +} diff --git a/backend/src/auth/credentials.test.ts b/backend/src/auth/credentials.test.ts new file mode 100644 index 0000000..5ec750f --- /dev/null +++ b/backend/src/auth/credentials.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { + normalizeUsername, + PASSWORD_MAX_LENGTH, + PASSWORD_MIN_LENGTH, + USERNAME_MAX_LENGTH, + validateCredentials, +} from './credentials'; + +const PASSWORD = 'langt-nok-passord'; + +/** The `reason` from the BAD_USER_INPUT error, so tests do not depend on the message. */ +function reasonFor(username: string, password = PASSWORD): unknown { + try { + validateCredentials({ username, password }); + } catch (error) { + return (error as { extensions: { reason: string } }).extensions.reason; + } + return undefined; +} + +describe('normalizeUsername', () => { + it('trims and lowercases', () => { + expect(normalizeUsername(' Ola_N ')).toBe('ola_n'); + }); +}); + +describe('validateCredentials', () => { + it('accepts valid input and normalizes the username', () => { + expect(validateCredentials({ username: 'Kari_99', password: PASSWORD })).toEqual({ + username: 'kari_99', + password: PASSWORD, + }); + }); + + it('does not trim the password', () => { + expect(validateCredentials({ username: 'kari', password: ' mellomrom ' }).password).toBe(' mellomrom '); + }); + + it('rejects usernames that are too short or too long', () => { + expect(reasonFor('ab')).toBe('USERNAME_TOO_SHORT'); + expect(reasonFor('a'.repeat(USERNAME_MAX_LENGTH + 1))).toBe('USERNAME_TOO_LONG'); + expect(reasonFor('a'.repeat(USERNAME_MAX_LENGTH))).toBeUndefined(); + }); + + it('rejects characters outside a-z, 0-9 and _', () => { + for (const username of ['ola nordmann', 'blåbær', 'ola-n', 'ola.n', 'ola@ntnu']) { + expect(reasonFor(username)).toBe('USERNAME_INVALID_CHARACTERS'); + } + }); + + it('checks the password length at both ends', () => { + expect(reasonFor('kari', 'a'.repeat(PASSWORD_MIN_LENGTH - 1))).toBe('PASSWORD_TOO_SHORT'); + expect(reasonFor('kari', 'a'.repeat(PASSWORD_MIN_LENGTH))).toBeUndefined(); + expect(reasonFor('kari', 'a'.repeat(PASSWORD_MAX_LENGTH + 1))).toBe('PASSWORD_TOO_LONG'); + }); + + it('says which field is wrong, with the BAD_USER_INPUT code', () => { + expect(() => validateCredentials({ username: 'x', password: PASSWORD })).toThrow( + expect.objectContaining({ extensions: expect.objectContaining({ code: 'BAD_USER_INPUT', field: 'username' }) }), + ); + }); +}); diff --git a/backend/src/auth/credentials.ts b/backend/src/auth/credentials.ts new file mode 100644 index 0000000..ec5b713 --- /dev/null +++ b/backend/src/auth/credentials.ts @@ -0,0 +1,47 @@ +// Rules for usernames and passwords. The frontend has the same limits in +// frontend/src/features/auth/credentials.ts, so change both together. +import { invalidCredentialsInput } from './errors'; + +export const USERNAME_MIN_LENGTH = 3; +export const USERNAME_MAX_LENGTH = 30; +/** Lowercase letters a-z, digits and underscore, so usernames work in URLs such as /bruker/ola. */ +export const USERNAME_PATTERN = /^[a-z0-9_]+$/; + +// NIST SP 800-63B: at least 8 characters, allow long passwords, no rules about character types. +// The upper limit stops very long inputs from making the hashing slow. +export const PASSWORD_MIN_LENGTH = 8; +export const PASSWORD_MAX_LENGTH = 128; + +export interface CredentialsInput { + username: string; + password: string; +} + +/** " Ola_N " → "ola_n". Usernames are unique regardless of case. */ +export function normalizeUsername(username: string): string { + return username.trim().toLowerCase(); +} + +/** For registration. Returns the cleaned input, or throws BAD_USER_INPUT with `field` and `reason`. */ +export function validateCredentials(input: CredentialsInput): CredentialsInput { + const username = normalizeUsername(input.username); + const { password } = input; // Never trimmed: spaces are allowed in passwords. + + if (username.length < USERNAME_MIN_LENGTH) { + throw invalidCredentialsInput('username', 'USERNAME_TOO_SHORT', `The username needs at least ${USERNAME_MIN_LENGTH} characters.`); + } + if (username.length > USERNAME_MAX_LENGTH) { + throw invalidCredentialsInput('username', 'USERNAME_TOO_LONG', `The username can have at most ${USERNAME_MAX_LENGTH} characters.`); + } + if (!USERNAME_PATTERN.test(username)) { + throw invalidCredentialsInput('username', 'USERNAME_INVALID_CHARACTERS', 'The username can only contain a-z, 0-9 and _.'); + } + if (password.length < PASSWORD_MIN_LENGTH) { + throw invalidCredentialsInput('password', 'PASSWORD_TOO_SHORT', `The password needs at least ${PASSWORD_MIN_LENGTH} characters.`); + } + if (password.length > PASSWORD_MAX_LENGTH) { + throw invalidCredentialsInput('password', 'PASSWORD_TOO_LONG', `The password can have at most ${PASSWORD_MAX_LENGTH} characters.`); + } + + return { username, password }; +} diff --git a/backend/src/auth/errors.ts b/backend/src/auth/errors.ts new file mode 100644 index 0000000..d9fccc5 --- /dev/null +++ b/backend/src/auth/errors.ts @@ -0,0 +1,29 @@ +// Error codes the frontend can rely on. The messages are for developers; the frontend shows +// its own Norwegian text based on the code (and on `reason` for BAD_USER_INPUT). +import { GraphQLError } from 'graphql'; + +export const AuthErrorCode = { + BAD_USER_INPUT: 'BAD_USER_INPUT', + USERNAME_TAKEN: 'USERNAME_TAKEN', + INVALID_CREDENTIALS: 'INVALID_CREDENTIALS', + TOO_MANY_ATTEMPTS: 'TOO_MANY_ATTEMPTS', + UNAUTHENTICATED: 'UNAUTHENTICATED', +} as const; + +export type AuthErrorCode = (typeof AuthErrorCode)[keyof typeof AuthErrorCode]; + +/** Why a username or password was rejected at registration. */ +export type CredentialsReason = + | 'USERNAME_TOO_SHORT' + | 'USERNAME_TOO_LONG' + | 'USERNAME_INVALID_CHARACTERS' + | 'PASSWORD_TOO_SHORT' + | 'PASSWORD_TOO_LONG'; + +export function authError(code: AuthErrorCode, message: string, extensions: Record = {}) { + return new GraphQLError(message, { extensions: { code, ...extensions } }); +} + +export function invalidCredentialsInput(field: 'username' | 'password', reason: CredentialsReason, message: string) { + return authError(AuthErrorCode.BAD_USER_INPUT, message, { field, reason }); +} diff --git a/backend/src/auth/password.test.ts b/backend/src/auth/password.test.ts new file mode 100644 index 0000000..3efe9b2 --- /dev/null +++ b/backend/src/auth/password.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_SCRYPT_PARAMS, hashPassword, verifyPassword } from './password'; + +// Cheap parameters keep the tests fast. One test uses the real defaults. +const FAST = { N: 1024, r: 8, p: 1 }; + +describe('hashPassword', () => { + it('stores the parameters, salt and hash, never the password', async () => { + const stored = await hashPassword('hemmelig-passord', FAST); + expect(stored).toMatch(/^scrypt\$1024\$8\$1\$[A-Za-z0-9+/=]+\$[A-Za-z0-9+/=]+$/); + expect(stored).not.toContain('hemmelig-passord'); + }); + + it('gives a different hash for the same password, because the salt is random', async () => { + expect(await hashPassword('samme-passord', FAST)).not.toBe(await hashPassword('samme-passord', FAST)); + }); + + it('works with the default parameters', async () => { + const stored = await hashPassword('standard-passord'); + expect(stored.startsWith(`scrypt$${DEFAULT_SCRYPT_PARAMS.N}$`)).toBe(true); + expect(await verifyPassword('standard-passord', stored)).toBe(true); + }); +}); + +describe('verifyPassword', () => { + it('accepts the right password and rejects a wrong one', async () => { + const stored = await hashPassword('riktig passord', FAST); + expect(await verifyPassword('riktig passord', stored)).toBe(true); + expect(await verifyPassword('feil passord', stored)).toBe(false); + expect(await verifyPassword('riktig passord ', stored)).toBe(false); + }); + + it('handles passwords with æ, ø, å and emoji', async () => { + const stored = await hashPassword('blåbærsyltetøy 🍷', FAST); + expect(await verifyPassword('blåbærsyltetøy 🍷', stored)).toBe(true); + }); + + it('returns false for malformed hashes instead of throwing', async () => { + for (const stored of ['', 'plaintext', 'bcrypt$1$2$3$a$b', 'scrypt$x$8$1$c2FsdA==$aGFzaA==', 'scrypt$1000$8$1$c2FsdA==$aGFzaA==']) { + expect(await verifyPassword('passord', stored)).toBe(false); + } + }); +}); diff --git a/backend/src/auth/password.ts b/backend/src/auth/password.ts new file mode 100644 index 0000000..cf7e7ae --- /dev/null +++ b/backend/src/auth/password.ts @@ -0,0 +1,57 @@ +// Password hashing with scrypt from Node's built-in crypto module, so no extra dependency is needed. +// The stored string holds the parameters and the salt, so the parameters can be raised later: +// old hashes still verify with the parameters they were made with. +import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'; + +export interface ScryptParams { + /** CPU and memory cost. Must be a power of two. */ + N: number; + /** Block size. */ + r: number; + /** Parallelisation. */ + p: number; +} + +/** One of the scrypt settings recommended by the OWASP Password Storage Cheat Sheet (about 32 MiB). */ +export const DEFAULT_SCRYPT_PARAMS: ScryptParams = { N: 2 ** 15, r: 8, p: 3 }; + +const SALT_BYTES = 16; +const KEY_BYTES = 32; +const PREFIX = 'scrypt'; + +function derive(password: string, salt: Buffer, keyLength: number, params: ScryptParams): Promise { + return new Promise((resolve, reject) => { + // maxmem must be above 128 * N * r, or Node refuses the parameters. + const maxmem = 256 * params.N * params.r; + scrypt(password, salt, keyLength, { ...params, maxmem }, (error, key) => + error ? reject(error) : resolve(key), + ); + }); +} + +/** Returns "scrypt$N$r$p$salt$hash", with salt and hash in base64. */ +export async function hashPassword(password: string, params = DEFAULT_SCRYPT_PARAMS): Promise { + const salt = randomBytes(SALT_BYTES); + const key = await derive(password, salt, KEY_BYTES, params); + return [PREFIX, params.N, params.r, params.p, salt.toString('base64'), key.toString('base64')].join('$'); +} + +/** Compares in constant time. A malformed stored hash gives false instead of an error. */ +export async function verifyPassword(password: string, stored: string): Promise { + const parts = stored.split('$'); + if (parts.length !== 6 || parts[0] !== PREFIX) return false; + + const [N, r, p] = parts.slice(1, 4).map(Number); + if (![N, r, p].every((value) => Number.isInteger(value) && value > 0)) return false; + + const salt = Buffer.from(parts[4], 'base64'); + const expected = Buffer.from(parts[5], 'base64'); + if (salt.length === 0 || expected.length === 0) return false; + + try { + const actual = await derive(password, salt, expected.length, { N, r, p }); + return timingSafeEqual(actual, expected); + } catch { + return false; // For example N that is not a power of two. + } +} diff --git a/backend/src/auth/rate-limit.test.ts b/backend/src/auth/rate-limit.test.ts new file mode 100644 index 0000000..7c4d8b5 --- /dev/null +++ b/backend/src/auth/rate-limit.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import { createAttemptLimiter } from './rate-limit'; + +function setup() { + let time = 0; + const limiter = createAttemptLimiter({ maxAttempts: 3, windowMs: 1000, now: () => time }); + return { limiter, advance: (ms: number) => (time += ms) }; +} + +describe('createAttemptLimiter', () => { + it('blocks a key after too many failures', () => { + const { limiter } = setup(); + limiter.recordFailure('ola'); + limiter.recordFailure('ola'); + expect(limiter.isBlocked('ola')).toBe(false); + limiter.recordFailure('ola'); + expect(limiter.isBlocked('ola')).toBe(true); + }); + + it('counts each key on its own', () => { + const { limiter } = setup(); + for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); + expect(limiter.isBlocked('kari')).toBe(false); + }); + + it('lets the key in again when the window has passed', () => { + const { limiter, advance } = setup(); + for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); + advance(1000); + expect(limiter.isBlocked('ola')).toBe(false); + }); + + it('starts over after reset', () => { + const { limiter } = setup(); + for (let i = 0; i < 3; i++) limiter.recordFailure('ola'); + limiter.reset('ola'); + expect(limiter.isBlocked('ola')).toBe(false); + }); +}); diff --git a/backend/src/auth/rate-limit.ts b/backend/src/auth/rate-limit.ts new file mode 100644 index 0000000..db68224 --- /dev/null +++ b/backend/src/auth/rate-limit.ts @@ -0,0 +1,53 @@ +// Counts failed attempts per key (here: username) in a fixed time window. +// Kept in memory: enough for one backend process. Move to the database or Redis +// if the backend ever runs as several processes. + +export interface AttemptLimiterOptions { + maxAttempts: number; + windowMs: number; + /** Can be replaced in tests. */ + now?: () => number; +} + +export interface AttemptLimiter { + isBlocked(key: string): boolean; + recordFailure(key: string): void; + reset(key: string): void; +} + +/** Stops the map from growing without limit if someone tries many different usernames. */ +const PRUNE_AT_SIZE = 10_000; + +export function createAttemptLimiter({ maxAttempts, windowMs, now = Date.now }: AttemptLimiterOptions): AttemptLimiter { + const attempts = new Map(); + + function current(key: string) { + const entry = attempts.get(key); + if (entry && now() >= entry.resetAt) { + attempts.delete(key); + return undefined; + } + return entry; + } + + function prune() { + const time = now(); + for (const [key, entry] of attempts) if (time >= entry.resetAt) attempts.delete(key); + } + + return { + isBlocked: (key) => (current(key)?.count ?? 0) >= maxAttempts, + + recordFailure(key) { + const entry = current(key); + if (entry) { + entry.count += 1; + return; + } + if (attempts.size >= PRUNE_AT_SIZE) prune(); + attempts.set(key, { count: 1, resetAt: now() + windowMs }); + }, + + reset: (key) => void attempts.delete(key), + }; +} diff --git a/backend/src/auth/resolvers.ts b/backend/src/auth/resolvers.ts new file mode 100644 index 0000000..c6d154c --- /dev/null +++ b/backend/src/auth/resolvers.ts @@ -0,0 +1,35 @@ +// Resolvers for users and login. They only depend on the auth context, so they can be +// tested without Express or a database (see auth-api.test.ts). +import type { AuthContext } from './auth-context'; +import type { PublicUser } from './auth-service'; +import type { CredentialsInput } from './credentials'; + +type AuthResolverContext = { auth: AuthContext }; + +export function toGraphQLUser(user: PublicUser) { + return { id: String(user.id), username: user.username, createdAt: user.createdAt.toISOString() }; +} + +export const authResolvers = { + Query: { + async me(_parent: unknown, _args: unknown, { auth }: AuthResolverContext) { + const user = await auth.currentUser(); + return user ? toGraphQLUser(user) : null; + }, + }, + + Mutation: { + async register(_parent: unknown, { input }: { input: CredentialsInput }, { auth }: AuthResolverContext) { + return toGraphQLUser(await auth.register(input)); + }, + + async login(_parent: unknown, { input }: { input: CredentialsInput }, { auth }: AuthResolverContext) { + return toGraphQLUser(await auth.login(input)); + }, + + async logout(_parent: unknown, _args: unknown, { auth }: AuthResolverContext) { + await auth.logout(); + return true; + }, + }, +}; diff --git a/backend/src/auth/schema.ts b/backend/src/auth/schema.ts new file mode 100644 index 0000000..16dd712 --- /dev/null +++ b/backend/src/auth/schema.ts @@ -0,0 +1,34 @@ +// GraphQL types for users and login. Extends Query and Mutation from ../schema.ts. +export const authTypeDefs = `#graphql + "A registered user. Only public fields: the password hash and the sessions never leave the backend." + type User { + id: ID! + "Lowercase, 3 to 30 characters: a-z, 0-9 and _." + username: String! + createdAt: String! + } + + input CredentialsInput { + username: String! + password: String! + } + + extend type Query { + "The logged-in user, or null when the request has no valid session cookie." + me: User + } + + extend type Mutation { + """ + Creates a user and logs in (sets the session cookie). + Errors: BAD_USER_INPUT with extensions.field and extensions.reason, and USERNAME_TAKEN. + """ + register(input: CredentialsInput!): User! + + "Logs in and sets the session cookie. Errors: INVALID_CREDENTIALS and TOO_MANY_ATTEMPTS." + login(input: CredentialsInput!): User! + + "Ends the session and clears the cookie. Returns true also if nobody was logged in." + logout: Boolean! + } +`; diff --git a/backend/src/auth/session-token.test.ts b/backend/src/auth/session-token.test.ts new file mode 100644 index 0000000..8ee5831 --- /dev/null +++ b/backend/src/auth/session-token.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { createSessionToken, hashSessionToken, isSessionToken } from './session-token'; + +describe('session tokens', () => { + it('creates tokens that pass the format check', () => { + const token = createSessionToken(); + expect(token).toHaveLength(43); + expect(isSessionToken(token)).toBe(true); + }); + + it('never creates the same token twice', () => { + const tokens = new Set(Array.from({ length: 1000 }, createSessionToken)); + expect(tokens.size).toBe(1000); + }); + + it('rejects values that cannot be tokens', () => { + for (const value of [undefined, null, '', 'abc', 'a'.repeat(44), `${'a'.repeat(42)}=`, 123]) { + expect(isSessionToken(value)).toBe(false); + } + }); + + it('hashes to 32 bytes, the same way every time', () => { + const token = createSessionToken(); + expect(hashSessionToken(token)).toHaveLength(32); + expect(hashSessionToken(token).equals(hashSessionToken(token))).toBe(true); + expect(hashSessionToken(token).equals(hashSessionToken(createSessionToken()))).toBe(false); + }); +}); diff --git a/backend/src/auth/session-token.ts b/backend/src/auth/session-token.ts new file mode 100644 index 0000000..e4b552c --- /dev/null +++ b/backend/src/auth/session-token.ts @@ -0,0 +1,22 @@ +// Session tokens: a random value in the cookie, and only its hash in the database. +import { createHash, randomBytes } from 'node:crypto'; + +const TOKEN_BYTES = 32; + +// 32 bytes in base64url are 43 characters without padding. +const TOKEN_FORMAT = /^[A-Za-z0-9_-]{43}$/; + +/** 256 random bits. Cannot be guessed, so it is safe to use as the only proof of a login. */ +export function createSessionToken(): string { + return randomBytes(TOKEN_BYTES).toString('base64url'); +} + +/** Rejects cookies that cannot be a token, before the database is asked. */ +export function isSessionToken(value: unknown): value is string { + return typeof value === 'string' && TOKEN_FORMAT.test(value); +} + +/** SHA-256 is enough here: the token is random and long, so it needs no salt or slow hash. */ +export function hashSessionToken(token: string): Buffer { + return createHash('sha256').update(token).digest(); +} diff --git a/backend/src/auth/user-store.db.test.ts b/backend/src/auth/user-store.db.test.ts new file mode 100644 index 0000000..b973a9a --- /dev/null +++ b/backend/src/auth/user-store.db.test.ts @@ -0,0 +1,77 @@ +// Tests the SQL in user-store.ts against a real PostgreSQL database. +// Skipped unless TEST_DATABASE_URL is set, so `npm test` works without a database. +// See "Database tests" in docs/api.md for how to create and migrate the test database. +import { Pool } from 'pg'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { createSessionToken, hashSessionToken } from './session-token'; +import { createPgUserStore, type UserStore } from './user-store'; + +const url = process.env.TEST_DATABASE_URL; + +describe.skipIf(!url)('createPgUserStore (PostgreSQL)', () => { + let pool: Pool; + let store: UserStore; + const created: number[] = []; + + /** A unique, valid username, so the tests never clash with other data in the database. */ + const uniqueName = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + + async function createUser() { + const user = await store.createUser(uniqueName(), 'scrypt$1024$8$1$c2FsdA==$aGFzaA=='); + if (!user) throw new Error('Could not create test user'); + created.push(user.id); + return user; + } + + beforeAll(() => { + pool = new Pool({ connectionString: url }); + store = createPgUserStore(pool); + }); + + // Removes only what these tests made. Sessions go with the user (ON DELETE CASCADE). + afterEach(async () => { + await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [created.splice(0)]); + }); + + afterAll(() => pool.end()); + + it('generates increasing ids and sets created_at', async () => { + const first = await createUser(); + const second = await createUser(); + expect(second.id).toBeGreaterThan(first.id); + expect(first.createdAt).toBeInstanceOf(Date); + }); + + it('returns null instead of throwing when the username is taken', async () => { + const user = await createUser(); + expect(await store.createUser(user.username, 'hash')).toBeNull(); + }); + + it('the database itself rejects usernames that break the rules', async () => { + await expect(store.createUser('Ola Nordmann', 'hash')).rejects.toMatchObject({ code: '23514' }); + }); + + it('finds a user by username', async () => { + const user = await createUser(); + expect(await store.findUserByUsername(user.username)).toEqual(user); + expect(await store.findUserByUsername(uniqueName())).toBeNull(); + }); + + it('finds the user from a session, and not after it is deleted', async () => { + const user = await createUser(); + const tokenHash = hashSessionToken(createSessionToken()); + await store.createSession(tokenHash, user.id, new Date(Date.now() + 60_000)); + expect(await store.findUserBySession(tokenHash)).toEqual(user); + + await store.deleteSession(tokenHash); + expect(await store.findUserBySession(tokenHash)).toBeNull(); + }); + + it('ignores and removes expired sessions', async () => { + const user = await createUser(); + const tokenHash = hashSessionToken(createSessionToken()); + await store.createSession(tokenHash, user.id, new Date(Date.now() - 1000)); + expect(await store.findUserBySession(tokenHash)).toBeNull(); + expect(await store.deleteExpiredSessions()).toBeGreaterThanOrEqual(1); + }); +}); diff --git a/backend/src/auth/user-store.ts b/backend/src/auth/user-store.ts new file mode 100644 index 0000000..2b2f00b --- /dev/null +++ b/backend/src/auth/user-store.ts @@ -0,0 +1,80 @@ +// All SQL for users and sessions. The rest of the auth code only talks to the UserStore +// interface, so it can be tested with an in-memory store (src/test/memory-user-store.ts). +import type { Pool } from 'pg'; + +export interface UserRecord { + id: number; + username: string; + passwordHash: string; + createdAt: Date; +} + +export interface UserStore { + /** Returns null if the username is taken. */ + createUser(username: string, passwordHash: string): Promise; + findUserByUsername(username: string): Promise; + createSession(tokenHash: Buffer, userId: number, expiresAt: Date): Promise; + /** Only sessions that have not expired. */ + findUserBySession(tokenHash: Buffer): Promise; + deleteSession(tokenHash: Buffer): Promise; + /** Returns the number of sessions removed. */ + deleteExpiredSessions(): Promise; +} + +interface UserRow { + id: number; + username: string; + password_hash: string; + created_at: Date; +} + +const toUser = (row: UserRow | undefined): UserRecord | null => + row ? { id: row.id, username: row.username, passwordHash: row.password_hash, createdAt: row.created_at } : null; + +export function createPgUserStore(pool: Pool): UserStore { + return { + async createUser(username, passwordHash) { + // ON CONFLICT avoids a race where two people register the same name at the same time. + const result = await pool.query( + `INSERT INTO app_user (username, password_hash) VALUES ($1, $2) + ON CONFLICT (username) DO NOTHING + RETURNING *`, + [username, passwordHash], + ); + return toUser(result.rows[0]); + }, + + async findUserByUsername(username) { + const result = await pool.query('SELECT * FROM app_user WHERE username = $1', [username]); + return toUser(result.rows[0]); + }, + + async createSession(tokenHash, userId, expiresAt) { + await pool.query('INSERT INTO user_session (token_hash, user_id, expires_at) VALUES ($1, $2, $3)', [ + tokenHash, + userId, + expiresAt, + ]); + }, + + async findUserBySession(tokenHash) { + const result = await pool.query( + `SELECT app_user.* + FROM user_session + JOIN app_user ON app_user.id = user_session.user_id + WHERE user_session.token_hash = $1 AND user_session.expires_at > now()`, + [tokenHash], + ); + return toUser(result.rows[0]); + }, + + async deleteSession(tokenHash) { + await pool.query('DELETE FROM user_session WHERE token_hash = $1', [tokenHash]); + }, + + async deleteExpiredSessions() { + const result = await pool.query('DELETE FROM user_session WHERE expires_at <= now()'); + return result.rowCount ?? 0; + }, + }; +} diff --git a/backend/src/context.ts b/backend/src/context.ts new file mode 100644 index 0000000..28eab9b --- /dev/null +++ b/backend/src/context.ts @@ -0,0 +1,24 @@ +// The GraphQL context: what every resolver gets as its third argument. Built once per request. +import type { Request, Response } from 'express'; +import { createAuthContext, type AuthContext } from './auth/auth-context'; +import type { AuthService } from './auth/auth-service'; +import { COOKIE_SECURE, SESSION_COOKIE } from './auth/config'; +import { createCookieJar, parseCookies } from './auth/cookies'; +import { createLoaders, type Loaders } from './loaders'; + +export interface Context { + loaders: Loaders; + auth: AuthContext; +} + +export function createContextFactory(authService: AuthService) { + return async ({ req, res }: { req: Request; res: Response }): Promise => ({ + // Fresh loaders for every request, so batched data is never shared between requests or users. + loaders: createLoaders(), + auth: createAuthContext( + authService, + parseCookies(req.headers.cookie).get(SESSION_COOKIE), + createCookieJar(res, COOKIE_SECURE), + ), + }); +} diff --git a/backend/src/loaders.ts b/backend/src/loaders.ts index b7349e4..d7b5440 100644 --- a/backend/src/loaders.ts +++ b/backend/src/loaders.ts @@ -92,9 +92,4 @@ export function createLoaders() { return { wines, studentRatings, reviews }; } -export type Loaders = ReturnType; - -/** What every resolver gets as its third argument. */ -export interface Context { - loaders: Loaders; -} \ No newline at end of file +export type Loaders = ReturnType; \ No newline at end of file diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 0265c05..cd1f9cb 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -1,7 +1,8 @@ // Resolvers: the functions that fetch data for each field in the schema. import { GraphQLError } from 'graphql'; import { pool } from './db'; -import { type Context, type ReviewRow, type WineRow } from './loaders'; +import type { Context } from './context'; +import { type ReviewRow, type WineRow } from './loaders'; import { authorName, validateReviewInput, diff --git a/backend/src/server.ts b/backend/src/server.ts index 409b828..deb63ef 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,8 +1,12 @@ import { ApolloServer } from '@apollo/server'; import { expressMiddleware } from '@as-integrations/express5'; import express from 'express'; +import { createAuthService } from './auth/auth-service'; +import { authResolvers } from './auth/resolvers'; +import { authTypeDefs } from './auth/schema'; +import { createPgUserStore } from './auth/user-store'; +import { createContextFactory, type Context } from './context'; import { pool } from './db'; -import { createLoaders, type Context } from './loaders'; import { resolvers } from './resolvers'; import { typeDefs } from './schema'; @@ -10,7 +14,12 @@ const PORT = Number(process.env.PORT ?? 3001); async function main() { const app = express(); - const apollo = new ApolloServer({ typeDefs, resolvers }); + // Each feature adds its own types and resolvers. Apollo merges the lists. + const apollo = new ApolloServer({ + typeDefs: [typeDefs, authTypeDefs], + resolvers: [resolvers, authResolvers], + }); + const createContext = createContextFactory(createAuthService(createPgUserStore(pool))); await apollo.start(); // Database check, same as before: shows that the backend can reach PostgreSQL. @@ -29,12 +38,10 @@ async function main() { } }); - // Fresh loaders for every request, so batched data is never shared between requests. - app.use( - '/graphql', - express.json(), - expressMiddleware(apollo, { context: async () => ({ loaders: createLoaders() }) }), - ); + // The context reads the session cookie and gets fresh loaders for every request (see context.ts). + // Apollo's CSRF protection is on by default: it rejects simple cross-site requests, and the + // SameSite=Lax cookie is not sent with cross-site POSTs. Together they protect the login cookie. + app.use('/graphql', express.json(), expressMiddleware(apollo, { context: createContext })); app.listen(PORT, () => { console.log(`Backend listening on http://localhost:${PORT}`); diff --git a/backend/src/test/memory-user-store.ts b/backend/src/test/memory-user-store.ts new file mode 100644 index 0000000..bcef196 --- /dev/null +++ b/backend/src/test/memory-user-store.ts @@ -0,0 +1,52 @@ +// An in-memory UserStore for tests. Behaves like the PostgreSQL store: generated ids, +// unique usernames and expired sessions that are not found. +import type { UserRecord, UserStore } from '../auth/user-store'; + +export function createMemoryUserStore(now: () => Date = () => new Date()) { + const users: UserRecord[] = []; + const sessions = new Map(); + let nextId = 1; + + const key = (tokenHash: Buffer) => tokenHash.toString('hex'); + + const store: UserStore = { + async createUser(username, passwordHash) { + if (users.some((user) => user.username === username)) return null; + const user = { id: nextId++, username, passwordHash, createdAt: now() }; + users.push(user); + return user; + }, + + async findUserByUsername(username) { + return users.find((user) => user.username === username) ?? null; + }, + + async createSession(tokenHash, userId, expiresAt) { + sessions.set(key(tokenHash), { userId, expiresAt }); + }, + + async findUserBySession(tokenHash) { + const session = sessions.get(key(tokenHash)); + if (!session || session.expiresAt <= now()) return null; + return users.find((user) => user.id === session.userId) ?? null; + }, + + async deleteSession(tokenHash) { + sessions.delete(key(tokenHash)); + }, + + async deleteExpiredSessions() { + let removed = 0; + for (const [id, session] of sessions) { + if (session.expiresAt <= now()) { + sessions.delete(id); + removed += 1; + } + } + return removed; + }, + }; + + // users and sessions are exposed so tests can check what was stored. + return { store, users, sessions }; +} diff --git a/docs/api.md b/docs/api.md index 387f5b9..21b68cc 100644 --- a/docs/api.md +++ b/docs/api.md @@ -92,4 +92,109 @@ Invalid input (a rating outside 1–5, a too long comment, an unknown wine) give with the code `BAD_USER_INPUT` and a message that can be shown to the user. `first` is limited to 50. -`studentRating`, `reviews` and `Review.wine` are loaded in batches with DataLoader, so a page of wines runs one query per field instead of one per wine. \ No newline at end of file +`studentRating`, `reviews` and `Review.wine` are loaded in batches with DataLoader, so a page of wines runs one query per field instead of one per wine. +## Users and login + +Students create a user with a username and a password, and stay logged in for 30 days. +The code is in `backend/src/auth/`, the tables in the migration `*_create-user-tables.sql`. + +| Table | Holds | +|---|---| +| `app_user` | `id` (generated by PostgreSQL), `username` (unique, lowercase, `^[a-z0-9_]{3,30}$`), `password_hash`, `created_at` | +| `user_session` | `token_hash` (SHA-256 of the cookie token), `user_id`, `created_at`, `expires_at` | + +Other tables should refer to `app_user.id`, never to the username. + +### How it works + +1. `register` or `login` checks the input and the password, creates a random 256-bit token, + stores its SHA-256 hash in `user_session` and sends the token in the cookie `kk_session`. +2. The browser sends the cookie with every request. The cookie is `HttpOnly` (JavaScript cannot + read it) and `SameSite=Lax` (not sent with cross-site POSTs). Set `COOKIE_SECURE=true` in + `backend/.env` if the site is served over HTTPS. +3. The GraphQL context looks up the session only when a resolver asks for the user, so + requests for wines cost no extra query. +4. `logout` deletes the session row and clears the cookie. + +Choices and why: + +| Choice | Why | Alternatives considered | +|---|---|---| +| Sessions in PostgreSQL with an `httpOnly` cookie | Logout really ends the session, and anyone can check the state with `psql`. The token never reaches JavaScript, so XSS cannot steal it | JWT in localStorage: cannot be revoked, and readable by any script on the page | +| Only the token hash is stored | A copy of the database cannot be used to log in | Storing the token | +| scrypt from `node:crypto` (N = 2^15, r = 8, p = 3, OWASP) | No extra dependency. Parameters are stored with each hash, so they can be raised later | bcrypt or argon2 (native packages) | +| Username and password only | Enough for a student project. No personal data such as e-mail is stored | E-mail with verification and password reset | +| Max 10 failed logins per username per 15 minutes | Stops guessing passwords. Kept in memory, which is enough for one backend process | Per IP address (all users look like 127.0.0.1 behind Apache) | +| Same error for wrong username and wrong password, and the same time | Does not reveal which usernames exist | Separate messages | +| Error codes instead of text | The frontend shows Norwegian text, the backend stays in English | Norwegian messages from the API | + +Apollo Server's built-in CSRF protection is on, and it rejects requests that are not JSON or do not +have a preflight header. Together with `SameSite=Lax` it protects the cookie. + +### Schema + +```graphql +type User { id: ID! username: String! createdAt: String! } +input CredentialsInput { username: String! password: String! } + +query { me { id username createdAt } } # null when not logged in +mutation Register($input: CredentialsInput!) { register(input: $input) { id username } } +mutation Login($input: CredentialsInput!) { login(input: $input) { id username } } +mutation Logout { logout } +``` + +| Error code | When | Extensions | +|---|---|---| +| `BAD_USER_INPUT` | Registration with an invalid username or password | `field` (`username` or `password`) and `reason` (`USERNAME_TOO_SHORT`, `USERNAME_TOO_LONG`, `USERNAME_INVALID_CHARACTERS`, `PASSWORD_TOO_SHORT`, `PASSWORD_TOO_LONG`) | +| `USERNAME_TAKEN` | Registration, also with other casing | `field: "username"` | +| `INVALID_CREDENTIALS` | Wrong username or password | | +| `TOO_MANY_ATTEMPTS` | Too many failed logins for the username | | +| `UNAUTHENTICATED` | A field that needs a logged-in user, called without one | | + +Usernames are trimmed and lowercased. Passwords need 8 to 128 characters and are never trimmed. + +### Adding a feature that needs a logged-in user + +In the resolver, call `requireUser()` on the context and use the returned id: + +```ts +async addFavourite(_parent: unknown, args: { wineId: string }, { auth }: Context) { + const user = await auth.requireUser(); // throws UNAUTHENTICATED + // INSERT INTO favourite (user_id, wine_id) VALUES ($1, $2) with user.id +} +``` + +Never take a user id from the arguments: the user is always the one in the session. +In the frontend, put the page under `` in `App.tsx`, and read the user with +`useAuthenticatedUser()`. + +### Tests + +| File | Tests | +|---|---| +| `auth/password.test.ts`, `session-token.test.ts`, `cookies.test.ts`, `credentials.test.ts`, `rate-limit.test.ts` | The building blocks one by one | +| `auth/auth-service.test.ts` | Register, login, logout and session expiry with an in-memory store | +| `auth/auth-api.test.ts` | Real GraphQL requests through Apollo Server, with a fake browser that keeps the cookie: two browsers, logout, forged cookies, error codes, and that no field exposes the password hash | +| `auth/user-store.db.test.ts` | The SQL against PostgreSQL. Skipped unless `TEST_DATABASE_URL` is set | + +## Database tests + +The tests in `*.db.test.ts` run against a separate test database, so they never touch real data. +They only remove the rows they create. Create the database once: + +```bash +createdb --owner=vinmonopolet_app vinmonopolet_test # see docs/database.md for -h/-U on Windows +cd backend +DATABASE_URL=postgresql://vinmonopolet_app:PASSWORD@localhost:5432/vinmonopolet_test npm run db:migrate +``` + +Then run all tests, including the database tests: + +```bash +TEST_DATABASE_URL=postgresql://vinmonopolet_app:PASSWORD@localhost:5432/vinmonopolet_test npm test +``` + +On Windows PowerShell, set the variable first: `$env:TEST_DATABASE_URL="postgresql://..."`, then `npm test`. +Run the migration again after pulling a new migration. + +See [manual testing](manual-testing.md) for how to test users and user data by hand.