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 app login can no longer read users.password_hash (P1-J): SELECT o…
…n users is granted column by column without it, the login lookup returns only the hash's parameters and salt, and two definer functions for the current user compare a digest inside the database and say whether a password is set. Tests pin the readable columns, that no login but the owner may read the column, and which app-runnable functions touch it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
omerFixesBugs and claude committed Nov 16, 2026
commit 356c44827a0f2fefa82a2d01253ef1417a14f98c
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
-- P1-J: the app login (jantrik_app) never reads a password hash, its own or anyone's, so an SQL
-- injection in a request cannot take staff hashes away to crack offline (docs/database.md → users).

-- ───────────── users: SELECT by column, every column but password_hash ─────────────
-- A table-level SELECT covers every column (a column REVOKE would change nothing), so the table
-- grant goes and the columns are granted one by one. A new users column needs its own GRANT.
-- UPDATE on password_hash stays (P1-B): setting a password writes it.
REVOKE SELECT ON users FROM jantrik_app;
GRANT SELECT (id, phone, email, name, name_bn, password_changed_at, locale, color_scheme,
created_at, updated_at)
ON users TO jantrik_app;

-- ───────────── auth_find_user_for_login(): parameters and salt, never the digest ─────────────
-- It returned password_hash of any user by phone or email, which made the column grant above
-- pointless. It now returns the PHC string up to its last `$` (argon2id, version 19, m, t, p and
-- the salt); the API hashes the typed password with them and auth_my_password_matches() compares.
-- Only the format Jantrik writes is accepted (a 32-byte digest); anything else gives NULL, as a
-- corrupt hash would fail today. A changed result type needs DROP + CREATE. Privileges are set
-- BEFORE the ownership change (see fix_definer_function_privileges).
DROP FUNCTION auth_find_user_for_login(text, text);
CREATE FUNCTION auth_find_user_for_login(p_phone text, p_email text)
RETURNS TABLE (id uuid, name text, locale locale, password_params text)
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = pg_catalog, public, pg_temp
AS $$
SELECT u.id, u.name, u.locale,
substring(u.password_hash FROM
'^(\$argon2id\$v=19\$m=[0-9]{1,10},t=[0-9]{1,10},p=[0-9]{1,3}\$[A-Za-z0-9+/]{11,64})\$[A-Za-z0-9+/]{43}$')
FROM users u
WHERE (p_phone IS NOT NULL AND u.phone = p_phone)
OR (p_email IS NOT NULL AND lower(u.email) = lower(p_email))
LIMIT 1
$$;
REVOKE ALL ON FUNCTION auth_find_user_for_login(text, text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION auth_find_user_for_login(text, text) TO jantrik_app;
ALTER FUNCTION auth_find_user_for_login(text, text) OWNER TO jantrik_auth;

-- ───────────── auth_my_password_matches(digest): the comparison, inside the database ─────────────
-- True when the current user's (app.user_id) stored hash has this SHA-256. The API sends the
-- SHA-256 of the hash it computed from the typed password, so the digest never leaves the
-- database, and what travels is fixed-size. No user parameter: scoped by context, like
-- auth_list_my_memberships().
CREATE FUNCTION auth_my_password_matches(p_digest bytea)
RETURNS boolean
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = pg_catalog, public, pg_temp
AS $$
SELECT EXISTS (
SELECT 1 FROM users u
WHERE u.id = app_current_user_id()
AND u.password_hash IS NOT NULL
AND sha256(convert_to(u.password_hash, 'UTF8')) = p_digest
)
$$;
REVOKE ALL ON FUNCTION auth_my_password_matches(bytea) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION auth_my_password_matches(bytea) TO jantrik_app;
ALTER FUNCTION auth_my_password_matches(bytea) OWNER TO jantrik_auth;

-- ───────────── auth_my_password_is_set(): GET /me/password's hasPassword ─────────────
CREATE FUNCTION auth_my_password_is_set()
RETURNS boolean
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = pg_catalog, public, pg_temp
AS $$
SELECT EXISTS (
SELECT 1 FROM users u
WHERE u.id = app_current_user_id() AND u.password_hash IS NOT NULL
)
$$;
REVOKE ALL ON FUNCTION auth_my_password_is_set() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION auth_my_password_is_set() TO jantrik_app;
ALTER FUNCTION auth_my_password_is_set() OWNER TO jantrik_auth;
2 changes: 2 additions & 0 deletions packages/db/test/auth-functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const FUNCTIONS = [
'auth_resolve_tenant',
'auth_find_refresh_token',
'app_find_or_create_user',
'auth_my_password_matches',
'auth_my_password_is_set',
];

describe('auth SECURITY DEFINER functions', () => {
Expand Down
58 changes: 58 additions & 0 deletions packages/db/test/schema-safety.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,69 @@ describe('schema safety net', () => {
expect(scoped.map((r) => r.fn).sort()).toEqual([
'app_find_or_create_user',
'auth_list_my_memberships',
'auth_my_password_is_set',
'auth_my_password_matches',
'search_student_ids',
]);
expect(scoped.filter((r) => !r.scoped)).toEqual([]);
});

// P1-J: no login reads a password hash. jantrik_app reads users column by column, and the list
// is pinned here: a new column, or a table-level SELECT coming back, is a deliberate change.
it('the app login reads users by column, never password_hash', async () => {
const [table] = await app.$queryRaw<{ table_select: boolean }[]>`
SELECT has_table_privilege('jantrik_app', 'users', 'SELECT') AS table_select`;
expect(table).toEqual({ table_select: false });
const columns = await app.$queryRaw<{ col: string }[]>`
SELECT a.attname::text AS col
FROM pg_attribute a
WHERE a.attrelid = 'users'::regclass AND a.attnum > 0 AND NOT a.attisdropped
AND has_column_privilege('jantrik_app', 'users', a.attname, 'SELECT')
ORDER BY a.attname`;
expect(columns.map((c) => c.col)).toEqual([
'color_scheme',
'created_at',
'email',
'id',
'locale',
'name',
'name_bn',
'password_changed_at',
'phone',
'updated_at',
]);
});

it('no login role but the owner, and not PUBLIC, may read users.password_hash', async () => {
const readers = await app.$queryRaw<{ name: string }[]>`
SELECT r.rolname::text AS name
FROM pg_roles r
WHERE (r.rolcanlogin OR r.rolname = 'public') AND NOT r.rolsuper
AND r.oid <> (SELECT relowner FROM pg_class WHERE oid = 'users'::regclass)
AND has_column_privilege(r.oid, 'users'::regclass, 'password_hash', 'SELECT')
UNION ALL
SELECT 'PUBLIC' WHERE has_column_privilege('public', 'users', 'password_hash', 'SELECT')`;
expect(readers).toEqual([]);
});

// The hash must not come back through a function either: every definer function jantrik_app
// may run that touches password_hash is listed here, and none returns a column of that name.
it('only the three login functions the app may run touch password_hash, and none returns it', async () => {
const rows = await app.$queryRaw<{ fn: string; result: string }[]>`
SELECT p.proname::text AS fn, pg_get_function_result(p.oid) AS result
FROM pg_proc p
WHERE p.pronamespace = 'public'::regnamespace AND p.prosecdef
AND has_function_privilege('jantrik_app', p.oid, 'EXECUTE')
AND p.prosrc ILIKE '%password_hash%'
ORDER BY 1`;
expect(rows.map((r) => r.fn)).toEqual([
'auth_find_user_for_login',
'auth_my_password_is_set',
'auth_my_password_matches',
]);
expect(rows.filter((r) => /password_hash/i.test(r.result))).toEqual([]);
});

// The login steps run before a platform session exists (the API has checked the password and
// the second factor). Everything else needs a live session of an active admin.
const PRE_SESSION_PLATFORM = [
Expand Down
170 changes: 170 additions & 0 deletions packages/db/test/users-password-hash.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { createHash } from 'node:crypto';
import { hash } from '@node-rs/argon2';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { findOrCreateUser, withContext, withTenant, type PrismaClient } from '../src/index.js';
import { appClient, createTenant, ownerClient, randomPhone } from './helpers.js';

// P1-J: the app login (jantrik_app) never reads a password hash, its own or anyone's. The
// login gets the hash's parameters and salt, and the database compares (docs/database.md → users).

const sha256 = (s: string): Buffer => createHash('sha256').update(s, 'utf8').digest();
/** The PHC string up to its last `$`: algorithm, version, parameters and salt, no digest. */
const paramsOf = (phc: string): string => phc.slice(0, phc.lastIndexOf('$'));
const NIL = '00000000-0000-0000-0000-000000000000';

describe('users.password_hash is out of the app login’s reach (P1-J)', () => {
let app: PrismaClient;
let owner: PrismaClient;
let tenantId: string;
let staff: { id: string; phone: string; hash: string };
let coMember: { id: string; phone: string };
let noPassword: { id: string; phone: string };

/** Sets the user's own hash as that user (the app login keeps UPDATE on the column). */
const setOwnHash = (userId: string, passwordHash: string | null) =>
withContext(app, { userId }, (tx) =>
tx.user.update({ where: { id: userId }, data: { passwordHash }, select: { id: true } }),
);

beforeAll(async () => {
app = appClient();
owner = ownerClient();
tenantId = (await createTenant(app)).id;
const make = (role: 'ADMIN' | 'TEACHER') => {
const phone = randomPhone();
return withTenant(app, tenantId, async (tx) => {
const id = await findOrCreateUser(tx, phone, `Person ${role}`);
await tx.membership.create({ data: { tenantId, userId: id, role } });
return { id, phone };
});
};
const s = await make('ADMIN');
staff = { ...s, hash: await hash('a long enough password') };
await setOwnHash(staff.id, staff.hash);
coMember = await make('TEACHER');
await setOwnHash(coMember.id, await hash('another long password'));
noPassword = await make('TEACHER');
});

afterAll(async () => {
await app.$disconnect();
await owner.$disconnect();
});

it('cannot select password_hash: not its own, not a co-member’s, not with SELECT *', async () => {
await expect(
withContext(
app,
{ userId: staff.id },
(tx) => tx.$queryRaw`SELECT password_hash FROM users WHERE id = ${staff.id}::uuid`,
),
).rejects.toThrow(/permission denied/i);
await expect(
withContext(
app,
{ tenantId, userId: coMember.id },
(tx) => tx.$queryRaw`SELECT password_hash FROM users WHERE id = ${staff.id}::uuid`,
),
).rejects.toThrow(/permission denied/i);
await expect(
withContext(app, { userId: staff.id }, (tx) => tx.$queryRaw`SELECT * FROM users`),
).rejects.toThrow(/permission denied/i);
// Not in a filter either (a WHERE on the column needs SELECT on it).
await expect(
withContext(
app,
{ tenantId, userId: coMember.id },
(tx) => tx.$queryRaw`SELECT id FROM users WHERE password_hash LIKE '$argon2id$%'`,
),
).rejects.toThrow(/permission denied/i);
});

it('every other column stays readable', async () => {
const rows = await withContext(
app,
{ tenantId, userId: coMember.id },
(tx) => tx.$queryRaw<{ id: string }[]>`
SELECT id::text, phone, email, name, name_bn, password_changed_at, locale, color_scheme,
created_at, updated_at
FROM users WHERE id = ${staff.id}::uuid`,
);
expect(rows.map((r) => r.id)).toEqual([staff.id]);
});

it('the login lookup returns the parameters and salt, never the digest', async () => {
const rows = await app.$queryRaw<Record<string, unknown>[]>`
SELECT * FROM auth_find_user_for_login(${staff.phone}, NULL)`;
expect(rows).toHaveLength(1);
expect(Object.keys(rows[0]!).sort()).toEqual(['id', 'locale', 'name', 'password_params']);
expect(rows[0]!['password_params']).toBe(paramsOf(staff.hash));
expect(staff.hash.startsWith(`${paramsOf(staff.hash)}$`)).toBe(true);
});

it('no parameters for a user without a password or with a hash in another format', async () => {
const paramsFor = async (phone: string) =>
(
await app.$queryRaw<{ password_params: string | null }[]>`
SELECT password_params FROM auth_find_user_for_login(${phone}, NULL)`
)[0]?.password_params;
expect(await paramsFor(noPassword.phone)).toBeNull();

const odd = randomPhone();
const oddId = await withTenant(app, tenantId, async (tx) => {
const id = await findOrCreateUser(tx, odd, 'Odd Hash');
await tx.membership.create({ data: { tenantId, userId: id, role: 'STAFF' } });
return id;
});
const good = await hash('a long enough password');
for (const stored of [
'not-a-real-hash',
good.replace('$argon2id$', '$argon2i$'),
good.replace('$v=19$', '$v=16$'),
`${paramsOf(good)}$AAAA`, // a digest that is not 32 bytes
`${good}$extra`,
]) {
await setOwnHash(oddId, stored);
expect(await paramsFor(odd), stored).toBeNull();
}
});

it('auth_my_password_matches compares inside the database, for the current user only', async () => {
const matches = (userId: string | null, digest: Buffer) =>
withContext(
app,
userId ? { userId } : {},
async (tx) =>
(
await tx.$queryRaw<{ ok: boolean }[]>`
SELECT auth_my_password_matches(${digest}) AS ok`
)[0]!.ok,
);
expect(await matches(staff.id, sha256(staff.hash))).toBe(true);
expect(await matches(staff.id, sha256(`${staff.hash}x`))).toBe(false);
expect(await matches(coMember.id, sha256(staff.hash))).toBe(false);
expect(await matches(noPassword.id, sha256(staff.hash))).toBe(false);
expect(await matches(NIL, sha256(staff.hash))).toBe(false);
expect(await matches(null, sha256(staff.hash))).toBe(false);
});

it('auth_my_password_is_set says whether the current user has a password', async () => {
const isSet = (userId: string | null) =>
withContext(
app,
userId ? { userId } : {},
async (tx) =>
(await tx.$queryRaw<{ set: boolean }[]>`SELECT auth_my_password_is_set() AS set`)[0]!.set,
);
expect(await isSet(staff.id)).toBe(true);
expect(await isSet(noPassword.id)).toBe(false);
expect(await isSet(null)).toBe(false);
});

it('the app login still writes its own hash; the owner reads it as that user', async () => {
const next = await hash('a third long password');
await setOwnHash(coMember.id, next);
const row = await withContext(owner, { userId: coMember.id }, (tx) =>
tx.user.findUniqueOrThrow({ where: { id: coMember.id }, select: { passwordHash: true } }),
);
expect(row.passwordHash).toBe(next);
});
});
14 changes: 12 additions & 2 deletions packages/db/test/users-rls.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { findOrCreateUser, withContext, withTenant, type PrismaClient } from '../src/index.js';
import { appClient, createTenant, randomPhone } from './helpers.js';
import { appClient, createTenant, ownerClient, randomPhone } from './helpers.js';

async function addMember(app: PrismaClient, tenantId: string, phone: string, name: string) {
return withTenant(app, tenantId, async (tx) => {
Expand Down Expand Up @@ -102,8 +102,18 @@ describe('RLS on users', () => {
const row = await withContext(app, { userId: id }, (tx) =>
tx.user.findUniqueOrThrow({ where: { id } }),
);
expect(row).toMatchObject({ locale: 'en', nameBn: 'নাম', passwordHash: 'x' });
expect(row).toMatchObject({ locale: 'en', nameBn: 'নাম' });
expect(row.passwordChangedAt).toEqual(changedAt);
// The app writes the hash but may not read it back (P1-J): the owner checks it, as that user.
const owner = ownerClient();
try {
const { passwordHash } = await withContext(owner, { userId: id }, (tx) =>
tx.user.findUniqueOrThrow({ where: { id }, select: { passwordHash: true } }),
);
expect(passwordHash).toBe('x');
} finally {
await owner.$disconnect();
}
});

it.each([
Expand Down