ReviewOS

also looking at this

stacks/bench-review

Close unauthenticated /api/requests CRUD, and make the session cookie HttpOnly

#77
Merged glennmichael123 wants to merge fix/request-autocrud-and-httponly into main
11 files +552 -57
tests/unit/session-cookie.test.tsadded+116-0
Changes to tests/unit/session-cookie.test.ts
@@ -0,0 +1,116 @@
1import { describe, expect, test } from 'bun:test'
2import { authCookie, authCookieName, authCookieToken, clearAuthCookie } from '@stacksjs/auth'
3import { withClearedSessionCookie, withSessionCookie } from '../../app/Support/sessionCookie'
4
5/**
6 * The security property these tests exist to pin down:
7 *
8 * the session credential must not be readable from JavaScript.
9 *
10 * Before this, `resources/stores/auth.ts` wrote the token with
11 * `document.cookie`, which can never be HttpOnly. The fix moved the write to
12 * the server. These tests assert the three things that has to mean in
13 * practice: the cookie carries HttpOnly, the server can read back what it set,
14 * and logout actually expires it.
15 *
16 * They are deliberately about the cookie contract rather than a full login
17 * round-trip — that needs a running API and a seeded user, so it belongs in a
18 * feature test against the dev server.
19 */
20
21const TOKEN = 'test-plain-token:encrypted-id-payload'
22
23describe('session cookie', () => {
24 test('is HttpOnly, scoped to the whole site, and SameSite=Lax', () => {
25 const cookie = authCookie(TOKEN)
26
27 // The entire point of the change.
28 expect(cookie).toContain('HttpOnly')
29 expect(cookie).toContain('Path=/')
30 // Lax, not Strict: a deep link back into /profile from an external
31 // referrer still has to carry the session so the server-side page gate
32 // (resources/middleware/auth.ts) sees it. Lax is also what withholds the
33 // cookie on cross-site POST, which is what keeps `.skipCsrf()` defensible.
34 expect(cookie).toContain('SameSite=Lax')
35 expect(cookie).toMatch(/Max-Age=\d+/)
36 })
37
38 test('uses the cookie name the rest of the app keys off', () => {
39 // config/auth.ts sets defaultTokenName: 'auth-token' and declares no
40 // cookie block, so this must resolve to 'auth-token' — the same literal
41 // resources/middleware/auth.ts reads out of ctx.cookies. If this ever
42 // drifts, the page-level auth gate stops seeing sessions.
43 expect(authCookieName()).toBe('auth-token')
44 expect(authCookie(TOKEN).startsWith('auth-token=')).toBe(true)
45 })
46
47 test('round-trips: the server can read back the token it set', () => {
48 // authCookieToken() is what requestToken() falls back to, so this is the
49 // actual path a cookie-only request authenticates through.
50 const request = new Request('https://benchreview.org/api/me', {
51 headers: { cookie: authCookie(TOKEN).split(';')[0] },
52 })
53
54 expect(authCookieToken(request)).toBe(TOKEN)
55 })
56
57 test('clearing expires the cookie rather than setting a value', () => {
58 const cleared = clearAuthCookie()
59
60 expect(cleared).toContain('Max-Age=0')
61 expect(cleared).toContain('HttpOnly')
62 expect(cleared.startsWith('auth-token=')).toBe(true)
63 })
64
65 test('omits Secure on loopback so local http sessions still work', () => {
66 // Browsers drop Secure cookies on plain http, so forcing it would break
67 // every localhost login. shouldSecureAuthCookie() handles this; the test
68 // guards the behaviour rather than the implementation.
69 const cookie = authCookie(TOKEN, { secure: false })
70 expect(cookie).not.toContain('Secure')
71
72 expect(authCookie(TOKEN, { secure: true })).toContain('Secure')
73 })
74})
75
76describe('auth responses', () => {
77 test('withSessionCookie installs the cookie and stays uncacheable', async () => {
78 const res = withSessionCookie({ token: TOKEN, user: { id: 1 } }, TOKEN)
79
80 const setCookie = res.headers.get('set-cookie') ?? ''
81 expect(setCookie).toContain('HttpOnly')
82 expect(setCookie).toContain('auth-token=')
83 // A cached auth response would hand one visitor another's session.
84 expect(res.headers.get('cache-control')).toBe('no-store')
85 expect(res.headers.get('content-type')).toBe('application/json')
86 expect(res.status).toBe(200)
87
88 // The JSON body still carries the framework's shape for non-browser clients.
89 expect(await res.json()).toEqual({ token: TOKEN, user: { id: 1 } })
90 })
91
92 test('withClearedSessionCookie expires the cookie', async () => {
93 const res = withClearedSessionCookie({ message: 'Successfully logged out' })
94
95 expect(res.headers.get('set-cookie') ?? '').toContain('Max-Age=0')
96 expect(res.headers.get('cache-control')).toBe('no-store')
97 expect(await res.json()).toEqual({ message: 'Successfully logged out' })
98 })
99})
100
101describe('Request model is not an auto-CRUD surface', () => {
102 test('declares routes: [] so the ORM generator emits nothing', async () => {
103 const model = (await import('../../app/Models/Request')).default as {
104 traits?: { useApi?: unknown }
105 }
106 const useApi = model.traits?.useApi as { uri?: string, routes?: string[] } | boolean | undefined
107
108 // `useApi: true` (the previous value) means the generator defaults to
109 // index + show + store + update + destroy + bulk-delete, all with no 401
110 // path. The `requests` table holds ip_address and user_agent, so a
111 // readable one is a de-anonymisation primitive on an app built around
112 // anonymous reviews.
113 expect(typeof useApi).toBe('object')
114 expect((useApi as { routes?: string[] }).routes).toEqual([])
115 })
116})