-
Notifications
You must be signed in to change notification settings - Fork 79
Single User Auth #202
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Single User Auth #202
Changes from 2 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
8c47298
feat: add single user auth via secret
stordahl f5333a5
test: use pool forks
stordahl 06852dc
some cleanup from copilot review
stordahl 24dbf17
feat: implement JWT based auth
stordahl dd8691b
chore: add generate-secrets script for dev
stordahl c694f77
fix: use secret as salt, address other review
stordahl ffe1675
chore: ignore generate-secrets script in codecov
stordahl 1434565
fix: clean up a bit
stordahl d65b92e
refactor: revert to not use JWT secret as hash salt
stordahl 5fe0246
more clean up
stordahl 8b90e8e
fix: add node compat flag
stordahl 3e396ce
refactor: explicitly handle missing secrets
stordahl 290dcaa
Merge branch 'main' into stordahl/auth
stordahl 50e5194
fix: rm rr node pkg
stordahl bed0158
feat: make auth optional
stordahl 7c38ca8
fix: add auth enabled env var to generate-secrets script
stordahl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,177 @@ | ||
import { describe, test, expect, vi, beforeEach, afterEach } from "vitest"; | ||
import { login, logout, requireAuth, getUser } from "../auth"; | ||
import { createSessionStorage } from "../session"; | ||
|
||
vi.mock("../session"); | ||
vi.mock("react-router", () => ({ | ||
redirect: vi.fn((url, options) => ({ url, options })), | ||
})); | ||
|
||
const mockSessionStorage = { | ||
getSession: vi.fn(), | ||
commitSession: vi.fn(), | ||
destroySession: vi.fn(), | ||
}; | ||
|
||
const mockSession = { | ||
get: vi.fn(), | ||
set: vi.fn(), | ||
}; | ||
|
||
const mockEnv = { | ||
CF_APP_PASSWORD: "test-password", | ||
} as Env; | ||
|
||
describe("auth", () => { | ||
beforeEach(() => { | ||
vi.mocked(createSessionStorage).mockReturnValue(mockSessionStorage as any); | ||
mockSessionStorage.getSession.mockResolvedValue(mockSession); | ||
mockSessionStorage.commitSession.mockResolvedValue("session-cookie"); | ||
mockSessionStorage.destroySession.mockResolvedValue("destroyed-cookie"); | ||
mockSession.get.mockReturnValue(false); | ||
mockSession.set.mockReturnValue(undefined); | ||
}); | ||
|
||
afterEach(() => { | ||
vi.clearAllMocks(); | ||
}); | ||
|
||
describe("login", () => { | ||
test("should login successfully with correct password", async () => { | ||
const request = new Request("http://localhost", { | ||
headers: { Cookie: "existing-cookie" }, | ||
}); | ||
|
||
const result = await login(request, "test-password", mockEnv); | ||
|
||
expect(createSessionStorage).toHaveBeenCalledWith("test-password"); | ||
expect(mockSessionStorage.getSession).toHaveBeenCalledWith("existing-cookie"); | ||
expect(mockSession.set).toHaveBeenCalledWith("authenticated", true); | ||
expect(mockSessionStorage.commitSession).toHaveBeenCalledWith(mockSession); | ||
expect(result).toEqual({ | ||
url: "/dashboard", | ||
options: { | ||
headers: { | ||
"Set-Cookie": "session-cookie", | ||
}, | ||
}, | ||
}); | ||
}); | ||
|
||
test("should throw error with incorrect password", async () => { | ||
const request = new Request("http://localhost"); | ||
|
||
await expect(login(request, "wrong-password", mockEnv)).rejects.toThrow( | ||
"Invalid password" | ||
); | ||
}); | ||
|
||
test("should handle request without cookie header", async () => { | ||
const request = new Request("http://localhost"); | ||
|
||
await login(request, "test-password", mockEnv); | ||
|
||
expect(mockSessionStorage.getSession).toHaveBeenCalledWith(null); | ||
}); | ||
}); | ||
|
||
describe("logout", () => { | ||
test("should logout successfully", async () => { | ||
const request = new Request("http://localhost", { | ||
headers: { Cookie: "session-cookie" }, | ||
}); | ||
|
||
const result = await logout(request, mockEnv); | ||
|
||
expect(createSessionStorage).toHaveBeenCalledWith("test-password"); | ||
expect(mockSessionStorage.getSession).toHaveBeenCalledWith("session-cookie"); | ||
expect(mockSessionStorage.destroySession).toHaveBeenCalledWith(mockSession); | ||
expect(result).toEqual({ | ||
url: "/", | ||
options: { | ||
headers: { | ||
"Set-Cookie": "destroyed-cookie", | ||
}, | ||
}, | ||
}); | ||
}); | ||
|
||
test("should handle request without cookie header", async () => { | ||
const request = new Request("http://localhost"); | ||
|
||
await logout(request, mockEnv); | ||
|
||
expect(mockSessionStorage.getSession).toHaveBeenCalledWith(null); | ||
}); | ||
}); | ||
|
||
describe("requireAuth", () => { | ||
test("should return session when authenticated", async () => { | ||
mockSession.get.mockReturnValue(true); | ||
const request = new Request("http://localhost", { | ||
headers: { Cookie: "session-cookie" }, | ||
}); | ||
|
||
const result = await requireAuth(request, mockEnv); | ||
|
||
expect(createSessionStorage).toHaveBeenCalledWith("test-password"); | ||
expect(mockSessionStorage.getSession).toHaveBeenCalledWith("session-cookie"); | ||
expect(mockSession.get).toHaveBeenCalledWith("authenticated"); | ||
expect(result).toBe(mockSession); | ||
}); | ||
|
||
test("should redirect when not authenticated", async () => { | ||
mockSession.get.mockReturnValue(false); | ||
const request = new Request("http://localhost"); | ||
|
||
await expect(requireAuth(request, mockEnv)).rejects.toEqual({ | ||
url: "/", | ||
options: undefined, | ||
}); | ||
}); | ||
|
||
test("should redirect when session has no authenticated value", async () => { | ||
mockSession.get.mockReturnValue(undefined); | ||
const request = new Request("http://localhost"); | ||
|
||
await expect(requireAuth(request, mockEnv)).rejects.toEqual({ | ||
url: "/", | ||
options: undefined, | ||
}); | ||
}); | ||
}); | ||
|
||
describe("getUser", () => { | ||
test("should return user object when authenticated", async () => { | ||
mockSession.get.mockReturnValue(true); | ||
const request = new Request("http://localhost", { | ||
headers: { Cookie: "session-cookie" }, | ||
}); | ||
|
||
const result = await getUser(request, mockEnv); | ||
|
||
expect(createSessionStorage).toHaveBeenCalledWith("test-password"); | ||
expect(mockSessionStorage.getSession).toHaveBeenCalledWith("session-cookie"); | ||
expect(mockSession.get).toHaveBeenCalledWith("authenticated"); | ||
expect(result).toEqual({ authenticated: true }); | ||
}); | ||
|
||
test("should return null when not authenticated", async () => { | ||
mockSession.get.mockReturnValue(false); | ||
const request = new Request("http://localhost"); | ||
|
||
const result = await getUser(request, mockEnv); | ||
|
||
expect(result).toBeNull(); | ||
}); | ||
|
||
test("should return null when session has no authenticated value", async () => { | ||
mockSession.get.mockReturnValue(undefined); | ||
const request = new Request("http://localhost"); | ||
|
||
const result = await getUser(request, mockEnv); | ||
|
||
expect(result).toBeNull(); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import { describe, test, expect, vi } from "vitest"; | ||
import { createSessionStorage } from "../session"; | ||
import { createCookieSessionStorage } from "react-router"; | ||
|
||
vi.mock("react-router", () => ({ | ||
createCookieSessionStorage: vi.fn(), | ||
})); | ||
|
||
describe("session", () => { | ||
describe("createSessionStorage", () => { | ||
test("should create session storage with correct configuration", () => { | ||
const mockSessionStorage = { mock: "session-storage" }; | ||
vi.mocked(createCookieSessionStorage).mockReturnValue(mockSessionStorage as any); | ||
|
||
const secret = "test-secret"; | ||
const result = createSessionStorage(secret); | ||
|
||
expect(createCookieSessionStorage).toHaveBeenCalledWith({ | ||
cookie: { | ||
name: "__counterscale_session", | ||
httpOnly: true, | ||
maxAge: 60 * 60 * 24 * 30, // 30 days | ||
path: "/", | ||
sameSite: "lax", | ||
secrets: [secret], | ||
secure: true, | ||
}, | ||
}); | ||
expect(result).toBe(mockSessionStorage); | ||
}); | ||
|
||
test("should use provided secret in configuration", () => { | ||
const secret = "my-custom-secret"; | ||
createSessionStorage(secret); | ||
|
||
expect(createCookieSessionStorage).toHaveBeenCalledWith( | ||
expect.objectContaining({ | ||
cookie: expect.objectContaining({ | ||
secrets: [secret], | ||
}), | ||
}) | ||
); | ||
}); | ||
|
||
test("should configure cookie with security settings", () => { | ||
createSessionStorage("test-secret"); | ||
|
||
expect(createCookieSessionStorage).toHaveBeenCalledWith( | ||
expect.objectContaining({ | ||
cookie: expect.objectContaining({ | ||
httpOnly: true, | ||
secure: true, | ||
sameSite: "lax", | ||
path: "/", | ||
}), | ||
}) | ||
); | ||
}); | ||
|
||
test("should set correct session name and expiration", () => { | ||
createSessionStorage("test-secret"); | ||
|
||
expect(createCookieSessionStorage).toHaveBeenCalledWith( | ||
expect.objectContaining({ | ||
cookie: expect.objectContaining({ | ||
name: "__counterscale_session", | ||
maxAge: 2592000, // 30 days in seconds | ||
}), | ||
}) | ||
); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { redirect } from "react-router"; | ||
stordahl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import { createSessionStorage } from "./session"; | ||
|
||
export async function login(request: Request, password: string, env: Env) { | ||
if (password !== env.CF_APP_PASSWORD) { | ||
stordahl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
throw new Error("Invalid password"); | ||
} | ||
|
||
const sessionStorage = createSessionStorage(env.CF_APP_PASSWORD); | ||
const session = await sessionStorage.getSession(request.headers.get("Cookie")); | ||
|
||
session.set("authenticated", true); | ||
|
||
return redirect("/dashboard", { | ||
headers: { | ||
"Set-Cookie": await sessionStorage.commitSession(session), | ||
}, | ||
}); | ||
} | ||
|
||
export async function logout(request: Request, env: Env) { | ||
const sessionStorage = createSessionStorage(env.CF_APP_PASSWORD); | ||
const session = await sessionStorage.getSession(request.headers.get("Cookie")); | ||
|
||
return redirect("/", { | ||
headers: { | ||
"Set-Cookie": await sessionStorage.destroySession(session), | ||
}, | ||
}); | ||
} | ||
|
||
export async function requireAuth(request: Request, env: Env) { | ||
stordahl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const sessionStorage = createSessionStorage(env.CF_APP_PASSWORD); | ||
const session = await sessionStorage.getSession(request.headers.get("Cookie")); | ||
|
||
if (!session.get("authenticated")) { | ||
throw redirect("/"); | ||
} | ||
|
||
return session; | ||
} | ||
|
||
export async function getUser(request: Request, env: Env) { | ||
const sessionStorage = createSessionStorage(env.CF_APP_PASSWORD); | ||
const session = await sessionStorage.getSession(request.headers.get("Cookie")); | ||
|
||
return session.get("authenticated") ? { authenticated: true } : null; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import { createCookieSessionStorage } from "react-router"; | ||
|
||
export function createSessionStorage(secret: string) { | ||
return createCookieSessionStorage({ | ||
cookie: { | ||
name: "__counterscale_session", | ||
httpOnly: true, | ||
maxAge: 60 * 60 * 24 * 30, // 30 days | ||
stordahl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
path: "/", | ||
sameSite: "lax", | ||
secrets: [secret], | ||
secure: true, | ||
stordahl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, | ||
}); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.