Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(auth): bind RP-1010-05 password reverification principal
Josué132ff719d781
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 40685ff8f..f76517e58 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.732",+ "version": "0.1.733","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.732",+ "version": "0.1.733","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex edf241fcb..fadc4179a 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.732",+ "version": "0.1.733","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/auth/passwordCredentialVerification.ts b/control-api/src/services/auth/passwordCredentialVerification.tsindex 88230144e..d53e7c9d4 100644--- a/control-api/src/services/auth/passwordCredentialVerification.ts+++ b/control-api/src/services/auth/passwordCredentialVerification.ts@@ -67,10 +67,33 @@ async function databaseNow(db: Pick<DbTransactionClient, 'query'>): Promise<numbexport async function capturePasswordEvaluation(email: string,chargeAttempt: boolean-): Promise<PasswordCapture> {+): Promise<PasswordCapture>+export async function capturePasswordEvaluation(+ email: string,+ chargeAttempt: boolean,+ userId: string+): Promise<PasswordCapture | null>+export async function capturePasswordEvaluation(+ email: string,+ chargeAttempt: boolean,+ userId?: string+): Promise<PasswordCapture | null> {const normalized = email.trim().toLowerCase()const key = passwordIdentifierKey(normalized)const snapshot = await withTransaction(async db => {+ let principal: PasswordUser | null = null+ if (userId !== undefined) {+ // Authenticated capture binds its principal before any identifier effect.+ // Match completion/credential writers: user first, then identifier; no lock spans bcrypt.+ const users = await db.query(+ `SELECT id, email, name, picture, password_hash, lifecycle_state,+ lifecycle_version, password_auth_generation FROM users+ WHERE email = $1 AND id::text = $2 FOR SHARE`,+ [normalized, userId]+ )+ principal = (users.rows[0] as PasswordUser) ?? null+ if (!principal) return null+ }await db.query('INSERT INTO password_identifier_state(identifier_key) VALUES ($1) ON CONFLICT DO NOTHING',[key]@@ -83,28 +106,33 @@ export async function capturePasswordEvaluation(const now = await databaseNow(db)const decision = admitPasswordIdentifier(stateOf(row), now, chargeAttempt)// A denied request never writes: it cannot move the rolling denial horizon.- if (decision.retryMs) return { retryMs: decision.retryMs, row }+ if (decision.retryMs) return { retryMs: decision.retryMs, row, principal }const expiresAt = now + policy.evaluationMsawait db.query('UPDATE password_identifier_state SET attempts = $2, failures = $3, locked_until_ms = $4, retained_until_ms = greatest(retained_until_ms, $5) WHERE identifier_key = $1',[key, decision.state.attempts, decision.state.failures, decision.state.lockedUntil, expiresAt])- return { retryMs: 0, row, expiresAt }+ return { retryMs: 0, row, expiresAt, principal }})+ if (!snapshot) return nullif (snapshot.retryMs) denied(snapshot.retryMs)// No transaction or row lock survives into bcrypt.- const users = await pool.query(- `SELECT id, email, name, picture, password_hash, lifecycle_state,- lifecycle_version, password_auth_generation FROM users WHERE email = $1 LIMIT 1`,- [normalized]- )+ let user = snapshot.principal+ if (userId === undefined) {+ const users = await pool.query(+ `SELECT id, email, name, picture, password_hash, lifecycle_state,+ lifecycle_version, password_auth_generation FROM users WHERE email = $1 LIMIT 1`,+ [normalized]+ )+ user = (users.rows[0] as PasswordUser) ?? null+ }return {email: normalized,key,instance: snapshot.row.instance,revision: String(snapshot.row.revision),expiresAt: snapshot.expiresAt!,- user: (users.rows[0] as PasswordUser) ?? null,+ user,}}@@ -172,7 +200,11 @@ export async function verifyMemberPassword(options: { publicLogin: boolean; userId?: string }): Promise<PasswordUser | null> {try {- const capture = await capturePasswordEvaluation(email, options.publicLogin)+ const capture =+ options.userId === undefined+ ? await capturePasswordEvaluation(email, options.publicLogin)+ : await capturePasswordEvaluation(email, options.publicLogin, options.userId)+ if (!capture) return nullawait reservePasswordPace()// The pace permit is deliberately not refunded on a busy lease.if (busy) denied(policy.paceMs)@@ -183,10 +215,7 @@ export async function verifyMemberPassword(const user = capture.userlet authenticated = falsetry {- const eligible =- !!user &&- user.lifecycle_state === 'active' &&- (!options.userId || options.userId === user.id)+ const eligible = !!user && user.lifecycle_state === 'active'let supported = falseif (eligible && user.password_hash) {try {diff --git a/control-api/test/rp005.passwordPrincipal.realPostgres.integration.test.ts b/control-api/test/rp005.passwordPrincipal.realPostgres.integration.test.tsnew file mode 100644index 000000000..09ea73880--- /dev/null+++ b/control-api/test/rp005.passwordPrincipal.realPostgres.integration.test.ts@@ -0,0 +1,129 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import bcrypt from 'bcryptjs'+import { randomBytes } from 'node:crypto'+import { Pool } from 'pg'+import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const realPg = adminUrl ? describe : describe.skip+realPg('RP-1010-05 authenticated principal binding', () => {+ const database = `rp005_${randomBytes(6).toString('hex')}`+ let admin: Pool+ let db: typeof import('../src/db.js')+ let login: typeof import('../src/services/directory/login.js')+ let firstId: string+ beforeAll(async () => {+ admin = new Pool({ connectionString: adminUrl })+ await admin.query(`CREATE DATABASE "${database}"`)+ const url = new URL(adminUrl!)+ url.pathname = `/${database}`+ vi.stubEnv('CONTROL_API_PG_CONNECTION_STRING', url.toString())+ vi.resetModules()+ db = await import('../src/db.js')+ await db.initDb()+ login = await import('../src/services/directory/login.js')+ const hash = await bcrypt.hash('Synthetic-RP005-password', 12)+ firstId = String(+ (+ await db.pool.query('INSERT INTO users(email,password_hash) VALUES ($1,$2) RETURNING id', [+ '[email protected]',+ hash,+ ])+ ).rows[0].id+ )+ await db.pool.query('INSERT INTO users(email,password_hash) VALUES ($1,$2)', [+ '[email protected]',+ hash,+ ])+ }, 60_000)+ beforeEach(async () => {+ vi.restoreAllMocks()+ await db.pool.query('TRUNCATE password_identifier_state, password_verification_pace')+ })+ afterAll(async () => {+ try {+ if (db) {+ await endPoolAndWaitForClients(db.pool)+ await endPoolAndWaitForClients(db.rateLimitPool)+ }+ if (admin) await admin.query(`DROP DATABASE "${database}"`)+ } finally {+ await admin?.end()+ vi.unstubAllEnvs()+ }+ })+ it('rejects an inconsistent ID/email without changing either principal or expensive-work state', async () => {+ expect(+ await login.verifyUserPassword({+ userId: firstId,+ email: '[email protected]',+ password: 'incorrect',+ })+ ).toBe(false)+ expect((await db.pool.query('SELECT * FROM password_identifier_state')).rows).toEqual([])+ expect((await db.pool.query('SELECT * FROM password_verification_pace')).rows).toEqual([])+ })+ it.each(['[email protected]', '[email protected]'])(+ 'rejects an empty authenticated ID for %s without state effects',+ async submitted => {+ const compare = vi.spyOn(bcrypt, 'compare')+ expect(+ await login.verifyUserPassword({+ userId: ' ',+ email: submitted,+ password: 'Synthetic-RP005-password',+ })+ ).toBe(false)+ expect(compare).not.toHaveBeenCalled()+ expect((await db.pool.query('SELECT * FROM password_identifier_state')).rows).toEqual([])+ expect((await db.pool.query('SELECT * FROM password_verification_pace')).rows).toEqual([])+ }+ )+ it('leaves existing retained security state unchanged on a mismatched binding', async () => {+ const engine = await import('../src/services/auth/passwordCredentialVerification.js')+ const capture = await engine.capturePasswordEvaluation('[email protected]', false)+ await engine.completePasswordEvaluation(capture, false)+ const before = (await db.pool.query('SELECT * FROM password_identifier_state')).rows+ expect(+ await login.verifyUserPassword({+ userId: firstId,+ email: '[email protected]',+ password: 'incorrect',+ })+ ).toBe(false)+ expect((await db.pool.query('SELECT * FROM password_identifier_state')).rows).toEqual(before)+ expect((await db.pool.query('SELECT * FROM password_verification_pace')).rows).toEqual([])+ })+ it('preserves same-principal failure charging and successful canonical reverification', async () => {+ expect(+ await login.verifyUserPassword({+ userId: firstId,+ email: '[email protected]',+ password: 'incorrect',+ })+ ).toBe(false)+ expect(+ (await db.pool.query('SELECT attempts,failures FROM password_identifier_state')).rows[0]+ ).toMatchObject({ attempts: [] })+ expect(+ (await db.pool.query('SELECT failures FROM password_identifier_state')).rows[0].failures+ ).toHaveLength(1)+ await db.pool.query(+ "UPDATE password_verification_pace SET next_permit=clock_timestamp()-interval '1 second'"+ )+ expect(+ await login.verifyUserPassword({+ userId: firstId,+ email: ' [email protected] ',+ password: 'Synthetic-RP005-password',+ })+ ).toBe(true)+ expect(+ (+ await db.pool.query(+ 'SELECT attempts,failures,locked_until_ms FROM password_identifier_state'+ )+ ).rows[0]+ ).toMatchObject({ attempts: [], failures: [], locked_until_ms: '0' })+ })+})