-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauth-session.test.ts
More file actions
224 lines (177 loc) · 6.11 KB
/
auth-session.test.ts
File metadata and controls
224 lines (177 loc) · 6.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// src/lib/auth-session.test.ts
//
// Functions: resetCookieState, getCookieOptions, createCookieStore, loadAuthModule
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"
type CookieEntry = {
value: string
options?: Record<string, unknown>
}
const cookieState = new Map<string, CookieEntry>()
const deletedCookies: string[] = []
function resetCookieState() {
cookieState.clear()
deletedCookies.length = 0
}
function getCookieOptions(name: string): Record<string, unknown> | undefined {
return cookieState.get(name)?.options
}
function createCookieStore() {
return {
get(name: string) {
const entry = cookieState.get(name)
return entry ? { name, value: entry.value } : undefined
},
set(name: string, value: string, options?: Record<string, unknown>) {
cookieState.set(name, { value, options })
},
delete(name: string) {
deletedCookies.push(name)
cookieState.delete(name)
},
}
}
async function loadAuthModule() {
vi.resetModules()
return import("./auth")
}
let tokenCounter = 0
vi.mock("next/headers", () => ({
cookies: vi.fn(async () => createCookieStore()),
}))
vi.mock("jose", () => ({
EncryptJWT: class EncryptJWT {
private payload: Record<string, unknown>
constructor(payload: Record<string, unknown>) {
this.payload = payload
}
setProtectedHeader() {
return this
}
setIssuedAt() {
return this
}
setExpirationTime() {
return this
}
async encrypt() {
tokenCounter += 1
return JSON.stringify({ payload: this.payload, tokenCounter })
}
},
jwtDecrypt: vi.fn(async (token: string) => ({ payload: JSON.parse(token).payload })),
}))
vi.mock("@/lib/cookie-security", async () => {
return {
shouldSecureCookies: () => {
if (process.env.SECURE_COOKIES === "true") return true
if (process.env.BASE_URL?.toLowerCase().startsWith("https://")) return true
return false
},
}
})
describe("auth session cookies", () => {
beforeEach(() => {
resetCookieState()
tokenCounter = 0
vi.unstubAllEnvs()
vi.stubEnv("SESSION_SECRET", "x".repeat(32))
vi.stubEnv("NODE_ENV", "test")
})
afterAll(() => {
vi.unstubAllEnvs()
})
it("sets HttpOnly strict session cookies and decrypts them through getSession", async () => {
const { createSession, getSession } = await loadAuthModule()
const token = await createSession("a".repeat(64), 30)
expect(cookieState.get("tt_session")?.value).toBe(token)
expect(cookieState.get("tt_max_age")?.value).toBe("1800")
expect(getCookieOptions("tt_session")).toMatchObject({
httpOnly: true,
sameSite: "strict",
secure: false,
maxAge: 1800,
path: "/",
})
expect(getCookieOptions("tt_max_age")).toMatchObject({
httpOnly: true,
sameSite: "strict",
secure: false,
maxAge: 1800,
path: "/",
})
await expect(getSession()).resolves.toEqual({ encryptionKey: "a".repeat(64) })
})
it("uses secure cookies when SECURE_COOKIES=true and different tokens per session", async () => {
vi.stubEnv("SECURE_COOKIES", "true")
const { createSession } = await loadAuthModule()
const first = await createSession("b".repeat(64), null)
const second = await createSession("b".repeat(64), null)
expect(first).not.toBe(second)
expect(getCookieOptions("tt_session")).toMatchObject({
secure: true,
maxAge: 60 * 60 * 24 * 7,
})
})
it("enables secure cookies when BASE_URL uses https", async () => {
vi.stubEnv("BASE_URL", "https://trackertracker.example.com")
const { createSession } = await loadAuthModule()
await createSession("f".repeat(64), null)
expect(getCookieOptions("tt_session")).toMatchObject({
secure: true,
})
})
it("does not set secure cookies when NODE_ENV is production but no SECURE_COOKIES or HTTPS BASE_URL", async () => {
vi.stubEnv("NODE_ENV", "production")
const { createSession } = await loadAuthModule()
await createSession("g".repeat(64), null)
expect(getCookieOptions("tt_session")).toMatchObject({
secure: false,
})
})
it("does not set secure cookies when BASE_URL uses http://", async () => {
vi.stubEnv("BASE_URL", "http://trackertracker.local")
const { createSession } = await loadAuthModule()
await createSession("h".repeat(64), null)
expect(getCookieOptions("tt_session")).toMatchObject({
secure: false,
})
expect(getCookieOptions("tt_max_age")).toMatchObject({
secure: false,
})
})
it("does not set secure cookies when SECURE_COOKIES is the string 'false'", async () => {
vi.stubEnv("SECURE_COOKIES", "false")
const { createSession } = await loadAuthModule()
await createSession("i".repeat(64), null)
expect(getCookieOptions("tt_session")).toMatchObject({
secure: false,
})
})
it("sets secure cookies when BASE_URL uses HTTPS:// with uppercase scheme", async () => {
vi.stubEnv("BASE_URL", "HTTPS://trackertracker.example.com")
const { createSession } = await loadAuthModule()
await createSession("j".repeat(64), null)
expect(getCookieOptions("tt_session")).toMatchObject({
secure: true,
})
})
it("clears both cookies on logout", async () => {
const { clearSession, createSession } = await loadAuthModule()
await createSession("c".repeat(64), 15)
await clearSession()
expect(deletedCookies).toEqual(["tt_session", "tt_max_age"])
expect(cookieState.size).toBe(0)
})
it("returns null when session decryption fails and verifies pending tokens separately", async () => {
const { createPendingToken, createSession, getSession, verifyPendingToken } =
await loadAuthModule()
const pendingToken = await createPendingToken("d".repeat(64))
await expect(verifyPendingToken(pendingToken)).resolves.toEqual({
encryptionKey: "d".repeat(64),
})
await createSession("e".repeat(64), 10)
cookieState.set("tt_session", { value: "not-a-real-jwe" })
await expect(getSession()).resolves.toBeNull()
await expect(verifyPendingToken(cookieState.get("tt_session")?.value ?? "")).resolves.toBeNull()
})
})