-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.test.ts
More file actions
250 lines (208 loc) · 8.5 KB
/
proxy.test.ts
File metadata and controls
250 lines (208 loc) · 8.5 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";
import { NextRequest, NextResponse } from "next/server";
vi.mock("@/lib/supabase/middleware", () => ({
updateSession: vi.fn(),
}));
import { updateSession } from "@/lib/supabase/middleware";
import { proxy, getTenantSlugFromHost } from "@/proxy";
import { encodePayload, makePayload, IMPERSONATION_COOKIE } from "@/lib/portal/impersonation";
const fakeResponse = new NextResponse(null, { status: 200 });
function makeRequest(
pathname: string,
cookies?: Record<string, string>,
host?: string
): NextRequest {
const req = new NextRequest(`http://${host ?? "localhost:3000"}${pathname}`, {
headers: { host: host ?? "localhost:3000" },
});
if (cookies) {
Object.entries(cookies).forEach(([name, value]) => {
req.cookies.set(name, value);
});
}
return req;
}
function validImpersonationCookie(tenantSlug: string): string {
return encodePayload(
makePayload({
clientId: "c1",
userId: "portal-u1",
tenantId: "t1",
tenantSlug,
clientName: "Acme Corp",
adminUserId: "admin-1",
})
);
}
function mockSession(user: Record<string, unknown> | null) {
(updateSession as Mock).mockResolvedValue({
supabaseResponse: fakeResponse,
user,
});
}
beforeEach(() => {
vi.clearAllMocks();
delete process.env.NEXT_PUBLIC_BASE_DOMAIN;
});
// ── getTenantSlugFromHost ───────────────────────────────────────────────────
describe("getTenantSlugFromHost", () => {
describe("with NEXT_PUBLIC_BASE_DOMAIN=taskflow.com", () => {
beforeEach(() => {
process.env.NEXT_PUBLIC_BASE_DOMAIN = "taskflow.com";
});
it("returns tenant slug from a valid subdomain", () => {
expect(getTenantSlugFromHost("acme.taskflow.com")).toBe("acme");
});
it("returns null for www subdomain", () => {
expect(getTenantSlugFromHost("www.taskflow.com")).toBeNull();
});
it("returns null for bare base domain", () => {
expect(getTenantSlugFromHost("taskflow.com")).toBeNull();
});
it("returns null for localhost", () => {
expect(getTenantSlugFromHost("localhost")).toBeNull();
});
it("returns null for localhost:3000", () => {
expect(getTenantSlugFromHost("localhost:3000")).toBeNull();
});
it("returns null for an unrelated host", () => {
expect(getTenantSlugFromHost("example.com")).toBeNull();
});
it("handles port in subdomain host correctly", () => {
expect(getTenantSlugFromHost("acme.taskflow.com:3000")).toBe("acme");
});
});
describe("without NEXT_PUBLIC_BASE_DOMAIN (local dev fallback to localhost)", () => {
beforeEach(() => {
delete process.env.NEXT_PUBLIC_BASE_DOMAIN;
});
it("returns null for localhost", () => {
expect(getTenantSlugFromHost("localhost")).toBeNull();
});
it("returns null for localhost:3000", () => {
expect(getTenantSlugFromHost("localhost:3000")).toBeNull();
});
it("returns null for any host that does not include 'localhost'", () => {
expect(getTenantSlugFromHost("acme.taskflow.com")).toBeNull();
});
});
});
// ── Admin route guard ──────────────────────────────────────────────────────
describe("proxy: admin routes", () => {
const adminRoutes = [
"/dashboard",
"/clients",
"/clients/123",
"/tasks",
"/tasks/AC-1",
"/time",
"/invoices",
"/reports",
"/settings",
];
it("redirects unauthenticated users to /auth/login", async () => {
for (const route of adminRoutes) {
mockSession(null);
const res = await proxy(makeRequest(route));
expect(res.headers.get("location"), `route: ${route}`).toContain("/auth/login");
}
});
it("redirects client role without tenant_slug to /auth/login", async () => {
mockSession({ id: "u1", app_metadata: { role: "client" } });
const res = await proxy(makeRequest("/dashboard"));
expect(res.headers.get("location")).toContain("/auth/login");
});
it("redirects client role with tenant_slug to their portal", async () => {
mockSession({ id: "u1", app_metadata: { role: "client", tenant_slug: "acme" } });
const res = await proxy(makeRequest("/dashboard"));
expect(res.headers.get("location")).toContain("/portal/acme");
});
it("passes through for admin role", async () => {
mockSession({ id: "u1", app_metadata: { role: "admin" } });
const res = await proxy(makeRequest("/dashboard"));
expect(res).toBe(fakeResponse);
});
it("passes through for all admin sub-routes", async () => {
for (const route of adminRoutes) {
mockSession({ id: "u1", app_metadata: { role: "admin" } });
const res = await proxy(makeRequest(route));
expect(res, `route: ${route}`).toBe(fakeResponse);
}
});
});
// ── Portal route guard ─────────────────────────────────────────────────────
describe("proxy: portal routes", () => {
it("redirects unauthenticated to /portal/[slug]/login", async () => {
mockSession(null);
const res = await proxy(makeRequest("/portal/acme"));
expect(res.headers.get("location")).toContain("/portal/acme/login");
});
it("does NOT guard the login page itself", async () => {
mockSession(null);
const res = await proxy(makeRequest("/portal/acme/login"));
// login page is not portal-protected, falls through
expect(res).toBe(fakeResponse);
});
it("redirects admin role accessing portal to portal login (no cookie)", async () => {
mockSession({ id: "u1", app_metadata: { role: "admin" } });
const res = await proxy(makeRequest("/portal/acme/tasks"));
expect(res.headers.get("location")).toContain("/portal/acme/login");
});
it("allows admin with valid impersonation cookie through portal route", async () => {
mockSession({ id: "admin-1", app_metadata: { role: "admin" } });
const cookie = validImpersonationCookie("acme");
const res = await proxy(makeRequest("/portal/acme", { [IMPERSONATION_COOKIE]: cookie }));
expect(res).toBe(fakeResponse);
});
it("blocks admin with impersonation cookie for wrong slug", async () => {
mockSession({ id: "admin-1", app_metadata: { role: "admin" } });
const cookie = validImpersonationCookie("other-co");
const res = await proxy(makeRequest("/portal/acme", { [IMPERSONATION_COOKIE]: cookie }));
expect(res.headers.get("location")).toContain("/portal/acme/login");
});
it("passes through for client role with matching slug", async () => {
mockSession({
id: "u1",
app_metadata: { role: "client", tenant_slug: "acme" },
});
const res = await proxy(makeRequest("/portal/acme"));
expect(res).toBe(fakeResponse);
});
it("redirects client to their own portal if slug mismatch", async () => {
mockSession({
id: "u1",
app_metadata: { role: "client", tenant_slug: "myco" },
});
const res = await proxy(makeRequest("/portal/other-co"));
expect(res.headers.get("location")).toContain("/portal/myco");
});
});
// ── x-tenant-slug header injection ────────────────────────────────────────
describe("proxy: x-tenant-slug header", () => {
beforeEach(() => {
process.env.NEXT_PUBLIC_BASE_DOMAIN = "taskflow.com";
});
it("injects x-tenant-slug from subdomain on pass-through", async () => {
mockSession(null);
const res = await proxy(makeRequest("/auth/login", undefined, "acme.taskflow.com"));
expect(res.headers.get("x-tenant-slug")).toBe("acme");
});
it("injects empty x-tenant-slug for localhost", async () => {
mockSession(null);
const res = await proxy(makeRequest("/auth/login"));
expect(res.headers.get("x-tenant-slug")).toBe("");
});
});
// ── Non-guarded routes ─────────────────────────────────────────────────────
describe("proxy: non-guarded routes", () => {
it("passes through public routes", async () => {
mockSession(null);
const res = await proxy(makeRequest("/auth/login"));
expect(res).toBe(fakeResponse);
});
it("passes through / regardless of auth", async () => {
mockSession(null);
const res = await proxy(makeRequest("/"));
expect(res).toBe(fakeResponse);
});
});