Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
355f21b
Passwords also refuse a distinctive word of an institute's name, not …
omerFixesBugs Nov 16, 2026
7016eff
Sprint 1 P1-J plan (docs/plans/sprint-1-p1j-password-hash.md): the ap…
omerFixesBugs Nov 16, 2026
25da8a3
Sprint 1 P2 plan (docs/plans/sprint-1-p2-files.md): institute profile…
omerFixesBugs Nov 16, 2026
995e61e
Test users get phone numbers no other test user of the same database …
omerFixesBugs Nov 16, 2026
356c448
The app login can no longer read users.password_hash (P1-J): SELECT o…
omerFixesBugs Nov 16, 2026
3ca69eb
Every Prisma client leaves users.password_hash out of its reads (P1-J…
omerFixesBugs Nov 16, 2026
30e85f6
Files and the institute profile in the database (P2 task 1): stored_f…
omerFixesBugs Nov 16, 2026
687a83b
CORS_ORIGINS is normalised in env.ts as browsers send Origin (lower-c…
omerFixesBugs Nov 16, 2026
ff8981c
Shared file caps, types and the institute profile schema (P2 task 2):…
omerFixesBugs Nov 16, 2026
917d5eb
The start-up login check also refuses a login with REPLICATION (a rep…
omerFixesBugs Nov 16, 2026
bc6644b
Password login without the hash (P1-J): the API hashes the typed pass…
omerFixesBugs Nov 16, 2026
b0e6315
GET /me/password reads hasPassword from auth_my_password_is_set() (P1…
omerFixesBugs Nov 16, 2026
47fb357
Docs for P1-J: database.md (password_hash not readable by the app, a …
omerFixesBugs Nov 16, 2026
20b29e9
Redis is pinned to one exact version, redis:7.4.11-alpine (the versio…
omerFixesBugs Nov 16, 2026
81bfc26
Docs for the follow-ups: decisions-pending gets the section "Small fo…
omerFixesBugs Nov 16, 2026
9cc9d54
Image processing for uploads (P2 task 3): sharp 0.35.5 (already in th…
omerFixesBugs Nov 16, 2026
b0e010b
FileStore and the per-institute cap (P2 task 4): PostgresFileStore is…
omerFixesBugs Nov 16, 2026
caec9f7
Photo and profile routes (P2 task 5): GET/PUT/DELETE /students/:id/ph…
omerFixesBugs Nov 16, 2026
57cf79f
Web (P2 task 6): Settings → Institute profile (names, EIIN, contact, …
omerFixesBugs Nov 16, 2026
4e4cbb2
Docs for P2 (task 7): docs/files.md, database.md (the three tables an…
omerFixesBugs Nov 16, 2026
724ffb0
The photo dialog's preview URL is made when a file is chosen, not in …
omerFixesBugs Nov 16, 2026
110857d
files.spec: the profile fields by id ("নাম (বাংলা)" is also part of t…
omerFixesBugs Nov 16, 2026
8c3a4f9
After the review (P1-J7): a dedicated login for the password login. j…
omerFixesBugs Nov 16, 2026
72b714b
The password login looks the hash up on its own database login (Login…
omerFixesBugs Nov 16, 2026
06f3236
Docs after the P1-J review: what an injection in an ordinary request …
omerFixesBugs Nov 16, 2026
82f6600
Test phones never wrap and their lock survives races (review of PR #1…
omerFixesBugs Nov 16, 2026
27403c3
The institute-name rule compares passwords and names like the phone r…
omerFixesBugs Nov 16, 2026
7aa31c5
An origin setting with a login, a path, a query or a fragment is no o…
omerFixesBugs Nov 16, 2026
fd6430e
Docs after the review of PR #17: P1-I's title line says it is built h…
omerFixesBugs Nov 16, 2026
9dbee45
P1-J migration after the second review: it first checks that jantrik_…
omerFixesBugs Nov 16, 2026
a980a60
The password login's database login must reach the same database, por…
omerFixesBugs Nov 16, 2026
ff673b8
Docs after the second P1-J review: the server upgrade creates the rol…
omerFixesBugs Nov 16, 2026
13deed2
A file reference is tied to its kind (review R6): UNIQUE (tenant_id, …
omerFixesBugs Nov 16, 2026
cb86722
Uploads hold no database connection while they arrive (review R1): th…
omerFixesBugs Nov 16, 2026
459bcf7
Web after the review: a chosen image is shrunk in the browser to 1600…
omerFixesBugs Nov 16, 2026
944e840
Docs after the review: auth.md (the request pipeline and @OwnTransact…
omerFixesBugs Nov 16, 2026
282c8b6
Review round 2, API: uploads in flight bounded before multer (16 per …
omerFixesBugs Nov 16, 2026
cfd4506
Review round 2, web: the browser asks for the EXIF orientation explic…
omerFixesBugs Nov 16, 2026
73eb83b
Docs for review round 2: auth.md (the upload routes' re-checks, Uploa…
omerFixesBugs Nov 16, 2026
e622e52
The interceptor opens its transaction through an unchecked entry (aro…
omerFixesBugs Nov 16, 2026
3d2c5d5
Review round 3: no upload slot leaks when the client left before Uplo…
omerFixesBugs Nov 16, 2026
de19108
The two new origin tests' development settings also name DATABASE_LOG…
omerFixesBugs Nov 16, 2026
aa0105b
Merge P1-J (#16) into the small follow-ups (#17): the ready resolutio…
omerFixesBugs Nov 16, 2026
b1efceb
Merge remote-tracking branch 'origin/feature/sprint-1-p1j-password-ha…
omerFixesBugs Nov 16, 2026
b5d3697
Merge remote-tracking branch 'origin/feature/sprint-1-p2-files' into …
omerFixesBugs Nov 16, 2026
c857102
Merge remote-tracking branch 'origin/feature/small-followups-after-p1…
omerFixesBugs Nov 16, 2026
9309fa8
Work in progress: a staff guide draft and draft legal texts (terms of…
omerFixesBugs Nov 19, 2026
ed5d56c
Docs only: a plain staff guide draft (signing in, setup, students, gu…
omerFixesBugs Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
The password login looks the hash up on its own database login (Login…
…PrismaService, a pool of 4, used by AuthService only: login-isolation.spec.ts) and verifies with argon2 as before. The start-up check refuses a privileged DATABASE_LOGIN_URL (fail closed) or one mixed up with DATABASE_URL; production refuses the owner or superuser there, and the receiver must not be given it. A stored hash above 64 MiB, 10 passes or 4 lanes, or one argon2 cannot read, counts as no password (the dummy check runs). Tests and Playwright derive DATABASE_LOGIN_URL like the platform login

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
omerFixesBugs and claude committed Nov 16, 2026
commit 72b714b7b7a0d97db4e64f5f2b2a7b2bff96f806
2 changes: 2 additions & 0 deletions apps/api/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { JwtModule } from '@nestjs/jwt';
import type { Env } from '../config/env.js';
import { AuthController } from './auth.controller.js';
import { AuthService } from './auth.service.js';
import { LoginPrismaService } from './login-prisma.service.js';
import { OtpService } from './otp.service.js';
import { PasswordController } from './password.controller.js';
import { PasswordSettingsService } from './password-settings.service.js';
Expand All @@ -23,6 +24,7 @@ import { TokenService } from './token.service.js';
controllers: [AuthController, PasswordController],
providers: [
AuthService,
LoginPrismaService,
OtpService,
PasswordService,
PasswordSettingsService,
Expand Down
18 changes: 9 additions & 9 deletions apps/api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ import { RateLimiter } from '../redis/rate-limiter.service.js';
import { Db } from '../tenancy/db.service.js';
import { TenantAccessService } from '../tenancy/tenant-access.service.js';
import {
findUserForLogin,
findUserForPasswordLogin,
listMemberships,
listMembershipsFor,
passwordMatches,
type LoginUser,
} from './login-lookup.js';
import { LoginPrismaService } from './login-prisma.service.js';
import { OtpService } from './otp.service.js';
import { PasswordService } from './password.service.js';
import { newRefreshToken, SessionService, type SessionMeta } from './session.service.js';
Expand All @@ -35,6 +35,7 @@ type ResponseUser = AuthResponse['user'];
export class AuthService {
constructor(
private readonly prisma: PrismaService,
private readonly login: LoginPrismaService,
private readonly db: Db,
private readonly otp: OtpService,
private readonly passwords: PasswordService,
Expand Down Expand Up @@ -80,13 +81,12 @@ export class AuthService {
},
);

const user = await findUserForLogin(this.prisma.client, { phone, email });
// One argon2 hash and one comparison in the database whatever the account (a dummy hash and
// the nil user when needed), so timing doesn't reveal unknown accounts. The stored hash never
// leaves the database (P1-J).
const digest = await this.passwords.loginDigest(user?.password_params, password);
const ok = await passwordMatches(this.prisma.client, user?.id, digest);
if (!user || !ok) throw invalidCredentials();
// On the password login's own database login (P1-J): no ordinary request can read a hash.
const found = await findUserForPasswordLogin(this.login.client, { phone, email });
// Always verify (against a dummy hash if needed) so timing doesn't reveal unknown accounts.
const ok = await this.passwords.verify(found?.password_hash, password);
if (!found || !ok) throw invalidCredentials();
const user: LoginUser = { id: found.id, name: found.name, locale: found.locale };
// Passwords are for staff (sprint 1 P1): an active staff membership in an open institute.
// Anyone else gets the same answer as a wrong password, and it counts as a failed attempt.
const memberships = await listMembershipsFor(this.prisma.client, user.id);
Expand Down
47 changes: 47 additions & 0 deletions apps/api/src/auth/login-isolation.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';

// P1-J: the password login's own database login (LoginPrismaService, jantrik_login_app) is the
// only way to a password hash. It stays with the password login in code as well as in the
// database: only AuthService holds it, and only the login lookup names the function.
const SRC = path.resolve(import.meta.dirname, '..');

function sources(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const full = path.join(dir, e.name);
if (e.isDirectory()) return sources(full);
return e.name.endsWith('.ts') && !e.name.endsWith('.spec.ts') ? [full] : [];
});
}

const files = sources(SRC).map((full) => ({
rel: path.relative(SRC, full).split(path.sep).join('/'),
code: readFileSync(full, 'utf8'),
}));

const usesLoginClient = (code: string) => /login-prisma\.service/.test(code);
const namesLookup = (code: string) => /\bauth_find_user_for_password_login\b/.test(code);

describe('the password login’s database login stays with the password login', () => {
it('only AuthService (and its module) use LoginPrismaService', () => {
expect(files.filter((f) => usesLoginClient(f.code)).map((f) => f.rel)).toEqual([
'auth/auth.module.ts',
'auth/auth.service.ts',
]);
});

it('only the login lookup and the start-up check name the password lookup', () => {
expect(files.filter((f) => namesLookup(f.code)).map((f) => f.rel)).toEqual([
'auth/login-lookup.ts',
'auth/login-prisma.service.ts',
]);
});

it('the scan finds what it looks for', () => {
expect(usesLoginClient("import { LoginPrismaService } from './login-prisma.service.js';")).toBe(
true,
);
expect(namesLookup('SELECT * FROM auth_find_user_for_password_login($1, $2)')).toBe(true);
expect(namesLookup('SELECT * FROM auth_find_user_for_login($1, $2)')).toBe(false);
});
});
40 changes: 16 additions & 24 deletions apps/api/src/auth/login-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,35 @@ export interface LoginUser {
id: string;
name: string;
locale: 'bn' | 'en';
/**
* The stored password hash up to its last `$` (argon2id, version, cost, salt), never its digest
* (P1-J); null without a usable password.
*/
password_params: string | null;
}

/** Login lookup through the SECURITY DEFINER function (users RLS hides everyone otherwise). */
/**
* Login lookup through the SECURITY DEFINER function (users RLS hides everyone otherwise), on the
* app login. It returns who the person is, never password data (P1-J).
*/
export async function findUserForLogin(
prisma: PrismaClient,
by: { phone?: string | null; email?: string | null },
): Promise<LoginUser | undefined> {
const rows = await prisma.$queryRaw<LoginUser[]>`
SELECT id::text, name, locale::text AS locale, password_params
SELECT id::text, name, locale::text AS locale
FROM auth_find_user_for_login(${by.phone ?? null}, ${by.email ?? null})`;
return rows[0];
}

/** Stands in for "no such user", so a failed lookup runs the same queries as a real account. */
const NO_USER = '00000000-0000-0000-0000-000000000000';

/**
* Whether `digest` (`PasswordService.loginDigest`) is the SHA-256 of the user's stored password
* hash. The database compares (`auth_my_password_matches`, scoped by `app.user_id`): the hash
* never reaches the API (P1-J).
* The password login's lookup, with the stored hash (null: no password). `login` must be the
* password login's own database login (LoginPrismaService, jantrik_login_app): it is the only
* one that may run this function, so no ordinary request can reach a hash (P1-J).
*/
export async function passwordMatches(
prisma: PrismaClient,
userId: string | undefined,
digest: Buffer,
): Promise<boolean> {
const rows = await withContext(
prisma,
{ userId: userId ?? NO_USER },
(tx) => tx.$queryRaw<{ ok: boolean }[]>`SELECT auth_my_password_matches(${digest}) AS ok`,
);
return rows[0]?.ok === true;
export async function findUserForPasswordLogin(
login: PrismaClient,
by: { phone?: string | null; email?: string | null },
): Promise<(LoginUser & { password_hash: string | null }) | undefined> {
const rows = await login.$queryRaw<(LoginUser & { password_hash: string | null })[]>`
SELECT id::text, name, locale::text AS locale, password_hash
FROM auth_find_user_for_password_login(${by.phone ?? null}, ${by.email ?? null})`;
return rows[0];
}

interface MembershipRow {
Expand Down
109 changes: 109 additions & 0 deletions apps/api/src/auth/login-prisma.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import type { LoginPrivileges } from '@jantrik/db';
import { LoginPrismaService } from './login-prisma.service.js';

// The password login's own database login (P1-J), checked at start-up like the platform one.

const SAFE: LoginPrivileges = {
login: 'jantrik_login_app',
superuser: false,
bypassRls: false,
canBecome: [],
};

/** The privilege query's row (readLoginPrivileges reads pg_roles). */
const privilegeRow = (p: LoginPrivileges) => ({
login: p.login,
superuser: p.superuser,
bypass_rls: p.bypassRls,
can_become: p.canBecome,
});

/**
* A client whose privilege query answers `privileges` in turn (a row or a failure; the last one
* repeats) and whose role check (may it run the password lookup?) answers `ok` (or fails).
*/
const client = (ok: boolean | Error, privileges: (LoginPrivileges | Error)[] = [SAFE]) => {
let i = 0;
return {
$queryRaw: vi.fn((strings: TemplateStringsArray) => {
if (strings.join('').includes('pg_roles')) {
const p = privileges[Math.min(i++, privileges.length - 1)]!;
return p instanceof Error ? Promise.reject(p) : Promise.resolve([privilegeRow(p)]);
}
return ok instanceof Error ? Promise.reject(ok) : Promise.resolve([{ ok }]);
}),
};
};

const unreachable = () =>
Object.assign(new Error("Raw query failed. Message: Can't reach database server"), {
name: 'PrismaClientKnownRequestError',
code: 'P2010',
meta: { driverAdapterError: { cause: { kind: 'DatabaseNotReachable', port: 5432 } } },
});

function service(
loginCanRun: boolean | Error,
mainCanRun: boolean | Error,
privileges: (LoginPrivileges | Error)[] = [SAFE],
) {
const warn = vi.fn();
const s = Object.create(LoginPrismaService.prototype) as LoginPrismaService;
Object.assign(s, {
client: client(loginCanRun, privileges),
main: { client: client(mainCanRun) },
logger: { warn, log: vi.fn() },
retryDelaysMs: [0, 0, 0],
checkTimeoutMs: 50,
});
return { s, warn };
}

describe('LoginPrismaService startup check', () => {
it('starts when only the login login may run the password lookup', async () => {
await expect(service(true, false).s.onModuleInit()).resolves.toBeUndefined();
});

it.each([
['DATABASE_URL uses the login login', true, true],
['DATABASE_LOGIN_URL uses the app login', false, false],
['the two are swapped', false, true],
])('refuses to start when %s', async (_case, login, main) => {
await expect(service(login, main).s.onModuleInit()).rejects.toThrow(/mixed up/);
});

it('only warns when the role check itself fails after the privilege check passed', async () => {
const { s, warn } = service(new Error('connect ECONNREFUSED'), false);
await expect(s.onModuleInit()).resolves.toBeUndefined();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('ECONNREFUSED'));
});
});

describe('LoginPrismaService login privileges (fail closed)', () => {
it('refuses a superuser login at once, naming DATABASE_LOGIN_URL and the login', async () => {
const { s } = service(true, false, [{ ...SAFE, login: 'postgres', superuser: true }]);
await expect(s.onModuleInit()).rejects.toThrow(/DATABASE_LOGIN_URL.*postgres is a superuser/);
});

it('refuses a login with BYPASSRLS', async () => {
const { s } = service(true, false, [{ ...SAFE, bypassRls: true }]);
await expect(s.onModuleInit()).rejects.toThrow(/DATABASE_LOGIN_URL.*has BYPASSRLS/);
});

it('refuses a login that can become a superuser role', async () => {
const { s } = service(true, false, [{ ...SAFE, canBecome: ['postgres'] }]);
await expect(s.onModuleInit()).rejects.toThrow(/can become postgres/);
});

it('waits while the database is unreachable, then checks as usual', async () => {
const { s } = service(true, false, [unreachable(), unreachable(), SAFE]);
await expect(s.onModuleInit()).resolves.toBeUndefined();
});

it('refuses to start unchecked when the database never answers', async () => {
const { s } = service(true, false, [unreachable()]);
await expect(s.onModuleInit()).rejects.toThrow(
/DATABASE_LOGIN_URL\).*DatabaseNotReachable\. The password login does not start unchecked/,
);
});
});
95 changes: 95 additions & 0 deletions apps/api/src/auth/login-prisma.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
createPrismaClient,
loginPrivilegeProblems,
readLoginPrivileges,
type PrismaClient,
} from '@jantrik/db';
import {
STARTUP_CHECK_TIMEOUT_MS,
STARTUP_RETRY_DELAYS_MS,
runStartupCheck,
startupErrorLabel,
} from '../common/startup-check.js';
import type { Env } from '../config/env.js';
import { PrismaService } from '../prisma/prisma.service.js';

/**
* The password login's own database login (DATABASE_LOGIN_URL, role jantrik_login_app, P1-J).
* It may run one function, auth_find_user_for_password_login, and nothing else; the rest of the
* API (jantrik_app) may not run that function, so an SQL injection in an ordinary request never
* reaches a password hash. Used by AuthService.loginWithPassword only
* (login-isolation.spec.ts checks who imports it). A small pool: one lookup per login.
*/
@Injectable()
export class LoginPrismaService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(LoginPrismaService.name);
readonly client: PrismaClient;
/** Waits between failed start-up checks (about 3 minutes in all; tests shorten them). */
retryDelaysMs: readonly number[] = STARTUP_RETRY_DELAYS_MS;
/** How long one start-up check may take. */
checkTimeoutMs = STARTUP_CHECK_TIMEOUT_MS;

constructor(
config: ConfigService<Env, true>,
private readonly main: PrismaService,
) {
this.client = createPrismaClient(config.get('DATABASE_LOGIN_URL', { infer: true }), {
max: 4,
});
}

/**
* First the login's privileges, failing closed like the API's own login (PrismaService): never
* a superuser, BYPASSRLS, or a login that can become such a role; while the check cannot run it
* is asked again for about 3 minutes, then the start is refused.
*
* Then refuse to start when the URLs are mixed up (DATABASE_URL given the login login, or the
* other way round): the separation would silently disappear. An error in this second check only
* warns (the first has just shown the database answers); logins fail on their own then.
*/
async onModuleInit(): Promise<void> {
await runStartupCheck({
run: () => readLoginPrivileges(this.client),
verdict: (p) => {
const problems = loginPrivilegeProblems(p);
return problems.length === 0
? true
: `DATABASE_LOGIN_URL must use the password login's login (jantrik_login_app): ` +
`${p.login} ${problems.join(', ')}. See docs/auth.md.`;
},
retryDelaysMs: this.retryDelaysMs,
checkTimeoutMs: this.checkTimeoutMs,
logger: this.logger,
what: "the password login's database login (DATABASE_LOGIN_URL)",
unchecked: 'The password login does not start unchecked.',
label: startupErrorLabel,
});

const canRun = (client: PrismaClient) =>
client.$queryRaw<{ ok: boolean }[]>`
SELECT has_function_privilege(
'public.auth_find_user_for_password_login(text, text)', 'EXECUTE') AS ok`.then(
([row]) => row?.ok === true,
);
let login: boolean;
let main: boolean;
try {
[login, main] = await Promise.all([canRun(this.client), canRun(this.main.client)]);
} catch (error) {
this.logger.warn(`Could not check the database roles: ${(error as Error).message}`);
return;
}
if (!login || main) {
throw new Error(
'Database roles are mixed up: DATABASE_LOGIN_URL must use the password login (jantrik_login_app) ' +
'and DATABASE_URL the app login (jantrik_app). See docs/auth.md.',
);
}
}

async onModuleDestroy(): Promise<void> {
await this.client.$disconnect();
}
}
Loading