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: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ API_HOST=127.0.0.1
API_PORT=3001
# Enable only for the documented local Apache proxy on the VM.
AUTH_TRUST_PROXY=false
# false for localhost/current HTTP VM; true when HTTPS is configured.
AUTH_COOKIE_SECURE=false
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,16 @@ Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git.

Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing still uses mock data. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user.

Session tokens are bearer credentials stored in localStorage to restore login after refresh or reopening the browser. They expire after seven days and are deleted server-side on successful logout. Temporary API or network errors preserve the local token for a later restoration attempt; only a confirmed invalid or expired session clears it.
Sessions use a host-only HttpOnly cookie (`t31_project2_session`, SameSite=Lax, Path=/, seven-day lifetime). GraphQL context resolves the user from the cookie. Tokens are not returned to frontend JavaScript or stored in localStorage. Logout revokes the server session and clears the cookie. Temporary API failures preserve the cookie for retry. Existing users must log in again after this migration.

Security trade-off: localStorage is readable by JavaScript on the same origin. An XSS vulnerability could steal a token and let an attacker impersonate its owner until expiry or revocation. This prototype accepts that limitation; production deployment should use HTTPS and consider Secure, HttpOnly, SameSite cookies with appropriate CSRF protection. HttpOnly cookies prevent JavaScript from reading the session credential.
Cookie-authenticated POST requests require JSON and `X-Requested-With: recipe-platform`; cross-origin CORS access is disabled. Set `AUTH_COOKIE_SECURE=true` when HTTPS is configured. Keep it false for local HTTP and the current NTNU HTTP deployment. HttpOnly reduces direct token theft through JavaScript; HTTPS is still required to protect credentials in transit.

### Protected routes

Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering,
feilkoder, genererte klientoperasjoner og rate limiting bak Apache.

`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server.
`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the cookie. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server.

## Database

Expand Down
71 changes: 68 additions & 3 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,81 @@ import {
} from './features/auth/authResolvers.js';
import { authClientKey } from './features/auth/authRateLimit.js';
import { authService, type AuthService } from './features/auth/authService.js';
import {
readSessionCookie,
sessionCookie,
SESSION_COOKIE,
} from './features/auth/sessionCookie.js';

export function createApp(
service: AuthService = authService,
trustProxy = process.env.AUTH_TRUST_PROXY === 'true',
secureCookie = process.env.AUTH_COOKIE_SECURE === 'true',
) {
const authResolvers = createAuthResolvers(service);
const cookies = new WeakMap<Request, string>();
return createYoga<{ req?: IncomingMessage }, AuthContext>({
context: ({ request, req }) => ({
authClient: authClientKey(request, req?.socket.remoteAddress, trustProxy),
}),
cors: false,
graphiql: {
defaultHeaders: JSON.stringify({ 'X-Requested-With': 'recipe-platform' }),
},
plugins: [
{
onRequest({ request, fetchAPI, endResponse }) {
if (
request.method === 'POST' &&
(request.headers.get('x-requested-with') !== 'recipe-platform' ||
request.headers.get('content-type')?.split(';')[0]?.trim() !==
'application/json')
) {
endResponse(
new fetchAPI.Response(
JSON.stringify({
errors: [
{
message: 'Request blocked.',
extensions: { code: 'FORBIDDEN' },
},
],
}),
{
status: 403,
headers: { 'Content-Type': 'application/json' },
},
),
);
}
},
onResponse({ request, response }) {
const cookie = cookies.get(request);
if (cookie) response.headers.append('Set-Cookie', cookie);
response.headers.set('Cache-Control', 'no-store');
},
},
],
context: async ({ request, req }) => {
const token = readSessionCookie(request);
const user = token ? await service.currentUser(token) : null;
if (
!user &&
request.headers.get('cookie')?.includes(SESSION_COOKIE + '=')
)
cookies.set(request, sessionCookie(null, secureCookie));
const context: AuthContext = {
authClient: authClientKey(
request,
req?.socket.remoteAddress,
trustProxy,
),
user,
sessionToken: user ? token : null,
setSession: (nextToken) => {
cookies.set(request, sessionCookie(nextToken, secureCookie));
context.sessionToken = nextToken;
},
};
return context;
},
schema: createSchema({
typeDefs: readFileSync(
new URL('./schema.graphql', import.meta.url),
Expand Down
169 changes: 133 additions & 36 deletions apps/api/src/features/auth/authApp.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
import { print } from 'graphql';
import { print, parse } from 'graphql';
import { createApp } from '../../app.js';
import { createAuthService } from './authService.js';
import type { AuthRepository } from './authRepository.js';
Expand All @@ -10,19 +10,22 @@ import {
SignOutDocument,
RegisterDocument,
} from '../../../../../contracts/generated.js';

const token = '11111111-1111-4111-8111-111111111111';
const user = {
id: '22222222-2222-4222-8222-222222222222',
name: 'Hasan',
email: 'hasan@example.com',
};
function setup() {
function setup(secure = false) {
let active = false;
let cookie = '';
const repository: AuthRepository = {
findUserByEmail: vi.fn(async () => ({ ...user, passwordHash: 'hash' })),
createUser: vi.fn(async () => user),
createUserWithSession: vi.fn(async () => ({ user, sessionToken: token })),
createUserWithSession: vi.fn(async () => {
active = true;
return { user, sessionToken: token };
}),
createSession: vi.fn(async () => {
active = true;
return token;
Expand All @@ -32,65 +35,159 @@ function setup() {
active = false;
}),
};
const service = createAuthService(repository, {
hash: async () => 'hash',
verify: async (_hash, password) => password === 'x',
});
const app = createApp(service, false);
const app = createApp(
createAuthService(repository, {
hash: async () => 'hash',
verify: async (_hash, password) => password === 'x',
}),
false,
secure,
);
async function request(
document: Parameters<typeof print>[0],
variables: Record<string, unknown>,
variables: Record<string, unknown> = {},
sentCookie = cookie,
csrf = true,
) {
const response = await app.fetch('http://localhost/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
...(csrf ? { 'X-Requested-With': 'recipe-platform' } : {}),
...(sentCookie ? { Cookie: sentCookie } : {}),
},
body: JSON.stringify({ query: print(document), variables }),
});
return (await response.json()) as {
const setCookie = response.headers.get('set-cookie');
if (setCookie) cookie = setCookie.split(';')[0]!;
const result = (await response.json()) as {
data: {
login?: { sessionToken: string };
login?: { user: typeof user };
register?: { user: typeof user };
currentUser?: typeof user | null;
signOut?: boolean;
};
errors?: { extensions: { code: string } }[];
};
return { ...result, cookie: setCookie, status: response.status };
}
return { repository, request };
return {
repository,
request,
expire: () => {
active = false;
},
};
}
describe('GraphQL authentication contract', () => {
it('logs in with a short existing password, restores session and invalidates it on logout', async () => {
describe('cookie GraphQL authentication', () => {
it('sets an HttpOnly cookie, restores from context and revokes the session on logout', async () => {
const { request } = setup();
const login = await request(LoginDocument, {
email: user.email,
password: 'x',
});
expect(login.errors).toBeUndefined();
expect(login.data.login?.sessionToken).toBe(token);
expect(
(await request(CurrentUserDocument, { sessionToken: token })).data
.currentUser,
).toEqual(user);
expect(login.data.login).toEqual({ user });
expect(JSON.stringify(login.data)).not.toContain(token);
expect(login.cookie).toContain('HttpOnly');
expect(login.cookie).toContain('SameSite=Lax');
expect(login.cookie).toContain('Path=/');
expect(login.cookie).toContain('Max-Age=604800');
expect(login.cookie).not.toContain('Secure');
expect(login.cookie).not.toContain('Domain=');
expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user);
const logout = await request(SignOutDocument);
expect(logout.data.signOut).toBe(true);
expect(logout.cookie).toContain('Max-Age=0');
expect(logout.cookie).toContain('Path=/');
expect(
(await request(SignOutDocument, { sessionToken: token })).data.signOut,
).toBe(true);
expect(
(await request(CurrentUserDocument, { sessionToken: token })).data
.currentUser,
(await request(CurrentUserDocument, {}, 't31_project2_session=' + token))
.data.currentUser,
).toBeNull();
});
it('does not query the repository for malformed session IDs', async () => {
it('registration also creates a cookie without exposing the token', async () => {
const { request, repository } = setup();
vi.mocked(repository.findUserByEmail).mockResolvedValueOnce(null);
const registered = await request(RegisterDocument, {
name: user.name,
email: user.email,
password: 'secret',
});
expect(registered.errors).toBeUndefined();
expect(registered.data.register).toEqual({ user });
expect(registered.cookie).toContain('HttpOnly');
expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user);
});
it('sets Secure when explicitly enabled for HTTPS', async () => {
const { request } = setup(true);
expect(
(await request(CurrentUserDocument, { sessionToken: 'broken' })).data
.currentUser,
).toBeNull();
expect(
(await request(SignOutDocument, { sessionToken: 'broken' })).data.signOut,
).toBe(false);
(await request(LoginDocument, { email: user.email, password: 'x' }))
.cookie,
).toContain('; Secure');
expect((await request(SignOutDocument)).cookie).toContain('; Secure');
});
it('treats absent, malformed and expired cookies as anonymous', async () => {
const { request, repository, expire } = setup();
expect((await request(CurrentUserDocument)).data.currentUser).toBeNull();
const malformed = await request(
CurrentUserDocument,
{},
't31_project2_session=broken',
);
expect(malformed.data.currentUser).toBeNull();
expect(malformed.cookie).toContain('Max-Age=0');
expect(repository.findUserBySession).not.toHaveBeenCalled();
expect(repository.deleteSession).not.toHaveBeenCalled();
await request(LoginDocument, { email: user.email, password: 'x' });
expire();
const expired = await request(CurrentUserDocument);
expect(expired.data.currentUser).toBeNull();
expect(expired.cookie).toContain('Max-Age=0');
});
it('does not clear the cookie or claim success when session revocation fails', async () => {
const { request, repository } = setup();
await request(LoginDocument, { email: user.email, password: 'x' });
vi.mocked(repository.deleteSession).mockRejectedValueOnce(
new Error('Database offline'),
);
const logout = await request(SignOutDocument);
expect(logout.errors).toBeDefined();
expect(logout.cookie).toBeNull();
expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user);
});
it('rejects browser-simple POSTs before executing authentication', async () => {
const { request, repository } = setup();
expect(
(
await request(
LoginDocument,
{ email: user.email, password: 'x' },
'',
false,
)
).status,
).toBe(403);
expect(repository.findUserByEmail).not.toHaveBeenCalled();
});
it('rejects the old token-bearing GraphQL contract', async () => {
const { request } = setup();
expect(
(
await request(
parse('query { currentUser(sessionToken: "old") { id } }'),
)
).errors,
).toBeDefined();
expect(
(
await request(
parse(
'mutation { login(email:"a@example.com",password:"x") { sessionToken } }',
),
)
).errors,
).toBeDefined();
});
it('returns structured codes for invalid input, credentials, duplicate email and rate limits', async () => {
it('preserves structured errors and rate limiting', async () => {
const { request } = setup();
expect(
(await request(LoginDocument, { email: 'a@', password: 'x' })).errors?.[0]
Expand All @@ -103,7 +200,7 @@ describe('GraphQL authentication contract', () => {
expect(
(
await request(RegisterDocument, {
name: 'Hasan',
name: user.name,
email: user.email,
password: 'secret',
})
Expand Down
Loading