mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
Fixes 15 defects found by a max-effort multi-agent review of the last 6 merged PRs (#388, #390, #391, #392, #393, #394), all adversarially verified before fixing. Install queue + dispatcher (the serious cluster): - features.ts: finalize the installer child exactly once. A failed spawn fires both "error" and "close", and the second event released the file lock and active slot that pump() had just handed to the next queued bundle, letting two pip processes write the same venv concurrently. Outcome recording now happens before pump() so the next bundle's first progress frame cannot race the previous install's bookkeeping. - feature-status.ts: keep failed-install errors in a per-bundle map instead of the single progress slot. With the queue auto-starting the next install, the slot was overwritten within seconds and a failed install vanished without ever surfacing to GET /features. - bridge.ts: scope child lifecycle per process (stopped-children set + request generation tags) instead of an instance-wide shuttingDown flag that the next spawn reset. A stale SIGTERMed child's late close event could record a phantom crash (5 of which permanently disable the dispatcher), null out the freshly spawned child, and reject the new child's pending requests. The request-timeout kill path still counts as a real crash. - install_feature.py: the pre-write disk re-check measured ai_dir's filesystem even when budgeting the cross-filesystem copy that lands on the venv's disk; now each budget is checked against the filesystem the bytes actually land on, so ENOSPC cannot strike mid-write and leave site-packages half overwritten. Behavior regressions: - embed-subtitles: preserve pre-existing subtitle tracks (0:s?) and MKV attachments (0:t?) that the -map 0:v:0/0:a? rewrite silently dropped; data streams stay unmapped on purpose (the actual MPEG remux fix). The new subtitle maps first so the language tag hits the right stream. - usage-survey-overlay: fail closed when the settings fetch fails; the fail-open path rendered the blocking survey against an unhealthy API and soft-locked admins, the lock-out class #392 fixed. - features-store: queued bundles poll instead of each holding an SSE connection (Install All could pin 7 EventSources and exhaust the browser's 6-per-origin HTTP/1.1 limit, hanging the whole app); listenToProgress closes any prior stream and stops any poll before subscribing; installAll skips bundles already installing or queued. Contracts, tests, i18n: - openapi.yaml: add "queued" to the features status enum and document downloadBytes/installedBytes (Schemathesis conformance). - feature-lifecycle e2e: queue transcription (~0.5 GB) instead of ocr (~6 GB) and give the test a budget that covers both install drains (the stacked waits exceeded the old 900s timeout). - docker-compose.qa.yml: parameterize the host port (QA_APP_PORT) so QA_PROJECT_NAME concurrent stacks can actually bind. - compare + watermark-image: restore per-input error attribution ("Invalid first/second image", "Invalid watermark image") lost in the shared-handler migration. - ai-features-section: the "{size} on disk" suffix now goes through i18n; key added to all 21 locales. - watermark-image + content-aware-resize: migrate to the shared inputHandlerFor("image") chain like compare/vectorize/compose, fixing drift in the inline copies (no SVG sanitize, no RAW extension hint, no AVIF probe). Verified: typecheck across 9 workspaces, Biome clean on all changed files, 584 targeted unit tests and 249 integration tests green (including real-ffmpeg embed-subtitles runs). One unit test updated to the new poll-while-queued contract with a single-EventSource assertion. Claude-Session: https://claude.ai/code/session_017mR1HiHaf3a1BmUtrHX4j3
453 lines
16 KiB
TypeScript
453 lines
16 KiB
TypeScript
/**
|
|
* Auth route edge-case tests — login failures, session expiry,
|
|
* password-change side effects, register validation.
|
|
*/
|
|
|
|
import { eq } from "drizzle-orm";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { db, schema } from "../../../apps/api/src/db/index.js";
|
|
import { buildTestApp, loginAsAdmin, type TestApp } from "../test-server.js";
|
|
|
|
let testApp: TestApp;
|
|
let adminToken: string;
|
|
|
|
const uid = () => `auth_test_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
|
|
|
beforeAll(async () => {
|
|
testApp = await buildTestApp();
|
|
adminToken = await loginAsAdmin(testApp.app);
|
|
}, 30_000);
|
|
|
|
afterAll(async () => {
|
|
await testApp.cleanup();
|
|
}, 10_000);
|
|
|
|
// Helper: register a user, clear mustChangePassword, return { username, password }
|
|
async function createUser(
|
|
opts: { role?: string; team?: string } = {},
|
|
): Promise<{ username: string; password: string; id: string }> {
|
|
const username = uid();
|
|
const password = "ValidPass1";
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/register",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { username, password, ...opts },
|
|
});
|
|
const body = JSON.parse(res.body);
|
|
if (res.statusCode !== 201) {
|
|
throw new Error(`createUser failed: ${res.statusCode} ${res.body}`);
|
|
}
|
|
await db
|
|
.update(schema.users)
|
|
.set({ mustChangePassword: false })
|
|
.where(eq(schema.users.username, username));
|
|
return { username, password, id: body.id };
|
|
}
|
|
|
|
// Helper: login and return token
|
|
async function loginAs(username: string, password: string): Promise<string> {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username, password },
|
|
});
|
|
const body = JSON.parse(res.body);
|
|
if (!body.token) throw new Error(`loginAs failed: ${res.body}`);
|
|
return body.token as string;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// LOGIN FAILURES
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
describe("Login failures", () => {
|
|
it("empty body returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: {},
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
});
|
|
|
|
it("missing username returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { password: "Anything1" },
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
});
|
|
|
|
it("missing password returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username: "admin" },
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
});
|
|
|
|
it("unknown username returns 401", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username: `nonexistent_${Date.now()}`, password: "Whatever1" },
|
|
});
|
|
expect(res.statusCode).toBe(401);
|
|
});
|
|
|
|
it("wrong password returns 401", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username: "admin", password: "WrongPass1" },
|
|
});
|
|
expect(res.statusCode).toBe(401);
|
|
});
|
|
|
|
it("unknown username and wrong password take comparable time (no enumeration timing oracle)", async () => {
|
|
// Both cases must return the identical 401 body, but a naive implementation
|
|
// short-circuits on "user not found" before ever running the password
|
|
// hash (scrypt), while "wrong password for a real user" always pays the
|
|
// scrypt cost. That gap lets an attacker enumerate valid usernames purely
|
|
// from response timing even though the status code and body are identical.
|
|
// See getDummyHash() in apps/api/src/plugins/auth.ts; it equalizes cost
|
|
// by running verifyPassword against a dummy hash on the unknown-user path.
|
|
const SAMPLES = 10;
|
|
const median = (values: number[]) => {
|
|
const sorted = [...values].sort((a, b) => a - b);
|
|
return sorted[Math.floor(sorted.length / 2)];
|
|
};
|
|
|
|
const unknownUserTimes: number[] = [];
|
|
for (let i = 0; i < SAMPLES; i++) {
|
|
const start = performance.now();
|
|
await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username: `nonexistent_${uid()}_${i}`, password: "Whatever1" },
|
|
});
|
|
unknownUserTimes.push(performance.now() - start);
|
|
}
|
|
|
|
const wrongPasswordTimes: number[] = [];
|
|
for (let i = 0; i < SAMPLES; i++) {
|
|
const start = performance.now();
|
|
await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username: "admin", password: `WrongPass1_${i}` },
|
|
});
|
|
wrongPasswordTimes.push(performance.now() - start);
|
|
}
|
|
|
|
const unknownMedian = median(unknownUserTimes);
|
|
const wrongPasswordMedian = median(wrongPasswordTimes);
|
|
const ratio =
|
|
Math.max(unknownMedian, wrongPasswordMedian) /
|
|
Math.max(1, Math.min(unknownMedian, wrongPasswordMedian));
|
|
|
|
// A real (unfixed) timing oracle shows up as 5-10x+ here (unknown-user
|
|
// returns near-instantly; wrong-password waits on scrypt). Bound at 3x to
|
|
// absorb normal event-loop/GC jitter while still catching a regression.
|
|
expect(ratio).toBeLessThan(3);
|
|
}, 30_000);
|
|
|
|
it("failed logins generate LOGIN_FAILED audit events", async () => {
|
|
const marker = uid();
|
|
// Trigger a failed login with a unique username
|
|
await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
payload: { username: marker, password: "Whatever1" },
|
|
});
|
|
|
|
const res = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/v1/audit-log?action=LOGIN_FAILED&limit=50",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
expect(res.statusCode).toBe(200);
|
|
const body = JSON.parse(res.body);
|
|
const match = body.entries.find(
|
|
(e: any) => e.action === "LOGIN_FAILED" && e.details?.username === marker,
|
|
);
|
|
expect(match).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// SESSION EDGE CASES
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
describe("Session edge cases", () => {
|
|
it("no token on session endpoint returns 401", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
});
|
|
expect(res.statusCode).toBe(401);
|
|
});
|
|
|
|
it("expired session token returns 401", async () => {
|
|
// Login to get a valid session
|
|
const token = await loginAs("admin", "Adminpass1");
|
|
|
|
// Manually expire the session in the DB
|
|
await db
|
|
.update(schema.sessions)
|
|
.set({ expiresAt: new Date(Date.now() - 60_000) })
|
|
.where(eq(schema.sessions.id, token));
|
|
|
|
const res = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
expect(res.statusCode).toBe(401);
|
|
});
|
|
});
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// PASSWORD CHANGE SIDE EFFECTS
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
describe("Password change side effects", () => {
|
|
it("changing password invalidates other sessions", async () => {
|
|
const { username, password } = await createUser();
|
|
|
|
// Create two sessions
|
|
const token1 = await loginAs(username, password);
|
|
const token2 = await loginAs(username, password);
|
|
|
|
// Verify both sessions work
|
|
const check1 = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${token1}` },
|
|
});
|
|
expect(check1.statusCode).toBe(200);
|
|
|
|
const check2 = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${token2}` },
|
|
});
|
|
expect(check2.statusCode).toBe(200);
|
|
|
|
// Change password via session 1
|
|
const changeRes = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/change-password",
|
|
headers: { authorization: `Bearer ${token1}` },
|
|
payload: { currentPassword: password, newPassword: "NewValid1" },
|
|
});
|
|
expect(changeRes.statusCode).toBe(200);
|
|
|
|
// Session 1 should still work (it's the current session)
|
|
const after1 = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${token1}` },
|
|
});
|
|
expect(after1.statusCode).toBe(200);
|
|
|
|
// Session 2 should now be invalid
|
|
const after2 = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${token2}` },
|
|
});
|
|
expect(after2.statusCode).toBe(401);
|
|
});
|
|
|
|
it("changing password revokes API keys", async () => {
|
|
const { username, password } = await createUser();
|
|
const token = await loginAs(username, password);
|
|
|
|
// Create an API key
|
|
const createKeyRes = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/v1/api-keys",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { name: "test-key" },
|
|
});
|
|
expect(createKeyRes.statusCode).toBe(201);
|
|
const apiKey = JSON.parse(createKeyRes.body).key;
|
|
|
|
// Verify the key works (hit a public-ish endpoint that still reads auth)
|
|
const keyCheck = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/v1/api-keys",
|
|
headers: { authorization: `Bearer ${apiKey}` },
|
|
});
|
|
expect(keyCheck.statusCode).toBe(200);
|
|
|
|
// Change password
|
|
const changeRes = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/change-password",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { currentPassword: password, newPassword: "NewValid2" },
|
|
});
|
|
expect(changeRes.statusCode).toBe(200);
|
|
|
|
// API key should now be revoked
|
|
const keyAfter = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/v1/api-keys",
|
|
headers: { authorization: `Bearer ${apiKey}` },
|
|
});
|
|
expect(keyAfter.statusCode).toBe(401);
|
|
});
|
|
});
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// PASSWORD RESET SIDE EFFECTS (admin resets another user)
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
describe("Password reset side effects", () => {
|
|
it("admin reset invalidates target user sessions", async () => {
|
|
const { username, password, id } = await createUser();
|
|
const userToken = await loginAs(username, password);
|
|
|
|
// Verify user session works
|
|
const before = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${userToken}` },
|
|
});
|
|
expect(before.statusCode).toBe(200);
|
|
|
|
// Admin resets the user's password
|
|
const resetRes = await testApp.app.inject({
|
|
method: "POST",
|
|
url: `/api/auth/users/${id}/reset-password`,
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { newPassword: "ResetPass1" },
|
|
});
|
|
expect(resetRes.statusCode).toBe(200);
|
|
|
|
// User session should now be invalid
|
|
const after = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/auth/session",
|
|
headers: { authorization: `Bearer ${userToken}` },
|
|
});
|
|
expect(after.statusCode).toBe(401);
|
|
});
|
|
|
|
it("admin reset revokes target user API keys", async () => {
|
|
const { username, password, id } = await createUser();
|
|
const userToken = await loginAs(username, password);
|
|
|
|
// Create an API key for the target user
|
|
const createKeyRes = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/v1/api-keys",
|
|
headers: { authorization: `Bearer ${userToken}` },
|
|
payload: { name: "target-key" },
|
|
});
|
|
expect(createKeyRes.statusCode).toBe(201);
|
|
const apiKey = JSON.parse(createKeyRes.body).key;
|
|
|
|
// Verify the key works
|
|
const keyBefore = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/v1/api-keys",
|
|
headers: { authorization: `Bearer ${apiKey}` },
|
|
});
|
|
expect(keyBefore.statusCode).toBe(200);
|
|
|
|
// Admin resets the user's password
|
|
const resetRes = await testApp.app.inject({
|
|
method: "POST",
|
|
url: `/api/auth/users/${id}/reset-password`,
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { newPassword: "ResetPass2" },
|
|
});
|
|
expect(resetRes.statusCode).toBe(200);
|
|
|
|
// API key should now be revoked
|
|
const keyAfter = await testApp.app.inject({
|
|
method: "GET",
|
|
url: "/api/v1/api-keys",
|
|
headers: { authorization: `Bearer ${apiKey}` },
|
|
});
|
|
expect(keyAfter.statusCode).toBe(401);
|
|
});
|
|
});
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// REGISTER VALIDATION
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
describe("Register validation", () => {
|
|
it("invalid username chars returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/register",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { username: "bad user!@#", password: "ValidPass1" },
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
|
});
|
|
|
|
it("username too short (2 chars) returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/register",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { username: "ab", password: "ValidPass1" },
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
|
});
|
|
|
|
it("weak password returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/register",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { username: uid(), password: "weak" },
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
|
});
|
|
|
|
it("non-existent team name returns 400", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/register",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: {
|
|
username: uid(),
|
|
password: "ValidPass1",
|
|
team: `ghost_team_${Date.now()}`,
|
|
},
|
|
});
|
|
expect(res.statusCode).toBe(400);
|
|
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
|
});
|
|
|
|
it("unknown role defaults to user", async () => {
|
|
const username = uid();
|
|
const res = await testApp.app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/register",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { username, password: "ValidPass1", role: "bogus" },
|
|
});
|
|
expect(res.statusCode).toBe(201);
|
|
const body = JSON.parse(res.body);
|
|
expect(body.role).toBe("user");
|
|
});
|
|
|
|
it("delete non-existent user returns 404", async () => {
|
|
const res = await testApp.app.inject({
|
|
method: "DELETE",
|
|
url: "/api/auth/users/00000000-0000-0000-0000-000000000000",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
expect(res.statusCode).toBe(404);
|
|
});
|
|
});
|