Merge branch 'worktree-agent-a7f7c229' into Develop
# Conflicts: # .planning/REQUIREMENTS.md # .planning/ROADMAP.md # .planning/STATE.md # tests/routes/auth.test.ts # tests/services/auth.service.test.ts
This commit is contained in:
@@ -1,17 +1,34 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import { beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
import { Hono } from "hono";
|
||||
import { requireAuth } from "../../src/server/middleware/auth";
|
||||
import {
|
||||
createApiKey,
|
||||
createSession,
|
||||
createUser,
|
||||
} from "../../src/server/services/auth.service";
|
||||
import { createApiKey } from "../../src/server/services/auth.service";
|
||||
import { createTestDb } from "../helpers/db";
|
||||
|
||||
// Mock @hono/oidc-auth - must be before importing middleware
|
||||
const mockGetAuth = mock(() => null as any);
|
||||
mock.module("@hono/oidc-auth", () => ({
|
||||
getAuth: mockGetAuth,
|
||||
oidcAuthMiddleware: () => async (_c: any, next: any) => next(),
|
||||
processOAuthCallback: async (c: any) => c.json({ ok: true }),
|
||||
revokeSession: async () => {},
|
||||
}));
|
||||
|
||||
// Mock verifyAccessToken from oauth.service
|
||||
const mockVerifyAccessToken = mock(() => Promise.resolve(false));
|
||||
mock.module("../../src/server/services/oauth.service", () => ({
|
||||
verifyAccessToken: mockVerifyAccessToken,
|
||||
}));
|
||||
|
||||
// Import middleware AFTER mocks are set up
|
||||
const { requireAuth } = await import("../../src/server/middleware/auth");
|
||||
|
||||
let db: ReturnType<typeof createTestDb>;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb();
|
||||
mockGetAuth.mockReset();
|
||||
mockGetAuth.mockReturnValue(null);
|
||||
mockVerifyAccessToken.mockReset();
|
||||
mockVerifyAccessToken.mockReturnValue(Promise.resolve(false));
|
||||
});
|
||||
|
||||
function createApp() {
|
||||
@@ -37,35 +54,16 @@ describe("auth middleware", () => {
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
test("returns 403 setup_required when no users exist", async () => {
|
||||
test("rejects POST with no auth credentials", async () => {
|
||||
const app = createApp();
|
||||
const res = await app.request("/items", { method: "POST" });
|
||||
expect(res.status).toBe(403);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("setup_required");
|
||||
});
|
||||
|
||||
test("rejects POST without auth when users exist", async () => {
|
||||
const app = createApp();
|
||||
await createUser(db, "admin", "pass");
|
||||
const res = await app.request("/items", { method: "POST" });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
test("allows POST with valid session cookie", async () => {
|
||||
const app = createApp();
|
||||
const user = await createUser(db, "admin", "pass");
|
||||
const session = createSession(db, user.id);
|
||||
const res = await app.request("/items", {
|
||||
method: "POST",
|
||||
headers: { Cookie: `gearbox_session=${session.id}` },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("Authentication required");
|
||||
});
|
||||
|
||||
test("allows POST with valid API key", async () => {
|
||||
const app = createApp();
|
||||
await createUser(db, "admin", "pass");
|
||||
const key = await createApiKey(db, "test");
|
||||
const res = await app.request("/items", {
|
||||
method: "POST",
|
||||
@@ -76,11 +74,52 @@ describe("auth middleware", () => {
|
||||
|
||||
test("rejects POST with invalid API key", async () => {
|
||||
const app = createApp();
|
||||
await createUser(db, "admin", "pass");
|
||||
const res = await app.request("/items", {
|
||||
method: "POST",
|
||||
headers: { "X-API-Key": "invalid" },
|
||||
headers: { "X-API-Key": "invalid-key-value" },
|
||||
});
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("Invalid API key");
|
||||
});
|
||||
|
||||
test("allows POST with valid Bearer token", async () => {
|
||||
const app = createApp();
|
||||
mockVerifyAccessToken.mockReturnValue(Promise.resolve(true));
|
||||
const res = await app.request("/items", {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer valid-token-123" },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
test("rejects POST with invalid Bearer token", async () => {
|
||||
const app = createApp();
|
||||
mockVerifyAccessToken.mockReturnValue(Promise.resolve(false));
|
||||
const res = await app.request("/items", {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer invalid-token" },
|
||||
});
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("invalid_token");
|
||||
});
|
||||
|
||||
test("allows POST with valid OIDC session", async () => {
|
||||
const app = createApp();
|
||||
mockGetAuth.mockReturnValue({ sub: "user-123", email: "test@example.com" });
|
||||
const res = await app.request("/items", { method: "POST" });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
test("API key takes priority over OIDC session", async () => {
|
||||
const app = createApp();
|
||||
const key = await createApiKey(db, "test");
|
||||
mockGetAuth.mockReturnValue({ sub: "user-123" });
|
||||
const res = await app.request("/items", {
|
||||
method: "POST",
|
||||
headers: { "X-API-Key": key.rawKey },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
import { beforeEach, describe, expect, it } from "bun:test";
|
||||
import { beforeEach, describe, expect, it, mock } from "bun:test";
|
||||
import { Hono } from "hono";
|
||||
import { authRoutes } from "../../src/server/routes/auth.ts";
|
||||
import { createApiKey } from "../../src/server/services/auth.service.ts";
|
||||
import { createTestDb } from "../helpers/db.ts";
|
||||
|
||||
async function createTestApp() {
|
||||
const db = await createTestDb();
|
||||
// Mock @hono/oidc-auth
|
||||
const mockGetAuth = mock(() => null as any);
|
||||
mock.module("@hono/oidc-auth", () => ({
|
||||
getAuth: mockGetAuth,
|
||||
oidcAuthMiddleware: () => async (_c: any, next: any) => next(),
|
||||
processOAuthCallback: async (c: any) => c.json({ ok: true }),
|
||||
revokeSession: async () => {},
|
||||
}));
|
||||
|
||||
// Mock verifyAccessToken from oauth.service
|
||||
mock.module("../../src/server/services/oauth.service", () => ({
|
||||
verifyAccessToken: mock(() => Promise.resolve(false)),
|
||||
}));
|
||||
|
||||
// Import routes AFTER mocks
|
||||
const { authRoutes } = await import("../../src/server/routes/auth.ts");
|
||||
|
||||
function createTestApp() {
|
||||
const db = createTestDb();
|
||||
const app = new Hono<{ Variables: { db?: any } }>();
|
||||
|
||||
app.use("*", async (c, next) => {
|
||||
@@ -18,111 +35,105 @@ async function createTestApp() {
|
||||
|
||||
describe("Auth Routes", () => {
|
||||
let app: Hono;
|
||||
let db: ReturnType<typeof createTestDb>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const testApp = await createTestApp();
|
||||
beforeEach(() => {
|
||||
const testApp = createTestApp();
|
||||
app = testApp.app;
|
||||
db = testApp.db;
|
||||
mockGetAuth.mockReset();
|
||||
mockGetAuth.mockReturnValue(null);
|
||||
});
|
||||
|
||||
describe("GET /api/auth/me", () => {
|
||||
it("returns null user and setupRequired true when no users exist", async () => {
|
||||
it("returns authenticated false when no OIDC session", async () => {
|
||||
const res = await app.request("/api/auth/me");
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.user).toBeNull();
|
||||
expect(body.setupRequired).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/setup", () => {
|
||||
it("creates first user and returns 201", async () => {
|
||||
const res = await app.request("/api/auth/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "secret123" }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.username).toBe("admin");
|
||||
|
||||
// Should set a session cookie
|
||||
const setCookie = res.headers.get("set-cookie");
|
||||
expect(setCookie).toContain("gearbox_session");
|
||||
expect(body.authenticated).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects second setup attempt with 403", async () => {
|
||||
// First setup
|
||||
await app.request("/api/auth/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "secret123" }),
|
||||
it("returns user info when OIDC session exists", async () => {
|
||||
mockGetAuth.mockReturnValue({
|
||||
sub: "logto-user-abc123",
|
||||
email: "user@example.com",
|
||||
});
|
||||
|
||||
// Second attempt
|
||||
const res = await app.request("/api/auth/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "other", password: "secret456" }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("rejects password shorter than 6 characters", async () => {
|
||||
const res = await app.request("/api/auth/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "short" }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/login", () => {
|
||||
beforeEach(async () => {
|
||||
// Create a user first
|
||||
await app.request("/api/auth/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "secret123" }),
|
||||
});
|
||||
});
|
||||
|
||||
it("returns session cookie on valid login", async () => {
|
||||
const res = await app.request("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "secret123" }),
|
||||
});
|
||||
|
||||
const res = await app.request("/api/auth/me");
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.username).toBe("admin");
|
||||
expect(body.authenticated).toBe(true);
|
||||
expect(body.user.id).toBe("logto-user-abc123");
|
||||
expect(body.user.email).toBe("user@example.com");
|
||||
});
|
||||
});
|
||||
|
||||
const setCookie = res.headers.get("set-cookie");
|
||||
expect(setCookie).toContain("gearbox_session");
|
||||
describe("GET /api/auth/keys", () => {
|
||||
it("returns 401 without authentication", async () => {
|
||||
const res = await app.request("/api/auth/keys");
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("rejects invalid credentials with 401", async () => {
|
||||
const res = await app.request("/api/auth/login", {
|
||||
it("returns empty key list with API key auth", async () => {
|
||||
const key = await createApiKey(db, "test-key");
|
||||
const res = await app.request("/api/auth/keys", {
|
||||
headers: { "X-API-Key": key.rawKey },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
// Contains at least the key we created for auth
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/keys", () => {
|
||||
it("creates a new API key when authenticated", async () => {
|
||||
const authKey = await createApiKey(db, "auth-key");
|
||||
const res = await app.request("/api/auth/keys", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": authKey.rawKey,
|
||||
},
|
||||
body: JSON.stringify({ name: "my-new-key" }),
|
||||
});
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.name).toBe("my-new-key");
|
||||
expect(body.key).toBeDefined();
|
||||
expect(body.prefix).toBeDefined();
|
||||
});
|
||||
|
||||
it("rejects without auth", async () => {
|
||||
const res = await app.request("/api/auth/keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "wrongpassword" }),
|
||||
body: JSON.stringify({ name: "my-key" }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/logout", () => {
|
||||
it("clears session cookie", async () => {
|
||||
const res = await app.request("/api/auth/logout", {
|
||||
method: "POST",
|
||||
});
|
||||
describe("DELETE /api/auth/keys/:id", () => {
|
||||
it("deletes an API key when authenticated", async () => {
|
||||
const authKey = await createApiKey(db, "auth-key");
|
||||
const targetKey = await createApiKey(db, "to-delete");
|
||||
|
||||
const res = await app.request(`/api/auth/keys/${targetKey.id}`, {
|
||||
method: "DELETE",
|
||||
headers: { "X-API-Key": authKey.rawKey },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects without auth", async () => {
|
||||
const res = await app.request("/api/auth/keys/1", {
|
||||
method: "DELETE",
|
||||
});
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,120 +1,17 @@
|
||||
import { beforeEach, describe, expect, it } from "bun:test";
|
||||
import {
|
||||
changePassword,
|
||||
createApiKey,
|
||||
createSession,
|
||||
createUser,
|
||||
deleteApiKey,
|
||||
deleteSession,
|
||||
getSession,
|
||||
getUserCount,
|
||||
listApiKeys,
|
||||
verifyApiKey,
|
||||
verifyPassword,
|
||||
} from "../../src/server/services/auth.service.ts";
|
||||
import { createTestDb } from "../helpers/db.ts";
|
||||
|
||||
describe("Auth Service", () => {
|
||||
let db: any;
|
||||
let db: ReturnType<typeof createTestDb>;
|
||||
|
||||
beforeEach(async () => {
|
||||
db = await createTestDb();
|
||||
});
|
||||
|
||||
describe("User Management", () => {
|
||||
it("creates a user with hashed password (hash !== plaintext)", async () => {
|
||||
const user = await createUser(db, "admin", "secret123");
|
||||
|
||||
expect(user).toBeDefined();
|
||||
expect(user.id).toBeGreaterThan(0);
|
||||
expect(user.username).toBe("admin");
|
||||
expect(user.passwordHash).not.toBe("secret123");
|
||||
expect(user.passwordHash.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("verifies correct password returns user", async () => {
|
||||
await createUser(db, "admin", "secret123");
|
||||
const user = await verifyPassword(db, "admin", "secret123");
|
||||
|
||||
expect(user).not.toBeNull();
|
||||
expect(user!.username).toBe("admin");
|
||||
});
|
||||
|
||||
it("rejects incorrect password returns null", async () => {
|
||||
await createUser(db, "admin", "secret123");
|
||||
const user = await verifyPassword(db, "admin", "wrongpassword");
|
||||
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it("getUserCount returns 0 then 1", async () => {
|
||||
const countBefore = await getUserCount(db);
|
||||
expect(countBefore).toBe(0);
|
||||
|
||||
await createUser(db, "admin", "secret123");
|
||||
|
||||
const countAfter = await getUserCount(db);
|
||||
expect(countAfter).toBe(1);
|
||||
});
|
||||
|
||||
it("changes password successfully", async () => {
|
||||
await createUser(db, "admin", "oldpass");
|
||||
const changed = await changePassword(db, "admin", "oldpass", "newpass");
|
||||
expect(changed).toBe(true);
|
||||
|
||||
// Verify new password works
|
||||
const user = await verifyPassword(db, "admin", "newpass");
|
||||
expect(user).not.toBeNull();
|
||||
|
||||
// Verify old password no longer works
|
||||
const oldAttempt = await verifyPassword(db, "admin", "oldpass");
|
||||
expect(oldAttempt).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects password change with wrong current password", async () => {
|
||||
await createUser(db, "admin", "secret123");
|
||||
const changed = await changePassword(
|
||||
db,
|
||||
"admin",
|
||||
"wrongcurrent",
|
||||
"newpass",
|
||||
);
|
||||
expect(changed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Session Management", () => {
|
||||
it("creates and retrieves a session (id length is 64 hex chars)", async () => {
|
||||
const user = await createUser(db, "admin", "secret123");
|
||||
const session = await createSession(db, user.id);
|
||||
|
||||
expect(session).toBeDefined();
|
||||
expect(session.id).toHaveLength(64);
|
||||
expect(session.userId).toBe(user.id);
|
||||
expect(session.expiresAt).toBeInstanceOf(Date);
|
||||
|
||||
const retrieved = await getSession(db, session.id);
|
||||
expect(retrieved).not.toBeNull();
|
||||
expect(retrieved!.id).toBe(session.id);
|
||||
});
|
||||
|
||||
it("returns null for expired session (expiryDays = -1)", async () => {
|
||||
const user = await createUser(db, "admin", "secret123");
|
||||
const session = await createSession(db, user.id, -1);
|
||||
|
||||
const retrieved = await getSession(db, session.id);
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
|
||||
it("deletes a session", async () => {
|
||||
const user = await createUser(db, "admin", "secret123");
|
||||
const session = await createSession(db, user.id);
|
||||
|
||||
await deleteSession(db, session.id);
|
||||
|
||||
const retrieved = await getSession(db, session.id);
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
beforeEach(() => {
|
||||
db = createTestDb();
|
||||
});
|
||||
|
||||
describe("API Key Management", () => {
|
||||
@@ -144,7 +41,7 @@ describe("Auth Service", () => {
|
||||
|
||||
it("deletes key so it is no longer valid", async () => {
|
||||
const result = await createApiKey(db, "test-key");
|
||||
await deleteApiKey(db, result.id);
|
||||
deleteApiKey(db, result.id);
|
||||
|
||||
const isValid = await verifyApiKey(db, result.rawKey);
|
||||
expect(isValid).toBe(false);
|
||||
@@ -154,7 +51,7 @@ describe("Auth Service", () => {
|
||||
await createApiKey(db, "key-one");
|
||||
await createApiKey(db, "key-two");
|
||||
|
||||
const keys = await listApiKeys(db);
|
||||
const keys = listApiKeys(db);
|
||||
expect(keys).toHaveLength(2);
|
||||
expect(keys[0].name).toBe("key-one");
|
||||
expect(keys[1].name).toBe("key-two");
|
||||
|
||||
Reference in New Issue
Block a user