Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix: close BUG-192 password-login abuse controls

Josuéaafd2e05b2eb
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 7d6bad938..ff69417b7 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.711",
+ "version": "0.1.712",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.711",
+ "version": "0.1.712",
"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.json
index 0882b95ab..7488e270c 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.711",
+ "version": "0.1.712",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 389f549f3..be675fdc8 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -5,6 +5,8 @@ import {
createBoundedPgPoolForConnection,
} from './boundedPgPool.js'
import { config } from './config.js'
+import { rootLogger } from './observability/logger.js'
+import { applyPasswordAdmissionSchema } from './services/auth/passwordAdmissionSchema.js'
import { applyCodexCatalogModelsSchema } from './services/codexSubscriptionCatalog.js'
import {
applyCodexChatgptAccountIdSchema,
@@ -6324,6 +6326,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0124_entity_change_definer_search_path',
apply: applyEntityChangeDefinerSearchPathSchema,
},
+ {
+ version: '0125_bug192_password_admission',
+ apply: applyPasswordAdmissionSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
@@ -6675,7 +6681,7 @@ export async function initDb(db: DbConnector = pool): Promise<void> {
try {
await client.query('ROLLBACK')
} catch (rollbackError) {
- console.warn('[ControlAPI] initDb rollback failed:', rollbackError)
+ rootLogger.warn({ err: rollbackError }, 'database migration rollback failed')
}
}
throw error
@@ -6684,7 +6690,7 @@ export async function initDb(db: DbConnector = pool): Promise<void> {
try {
await client.query(`SELECT pg_advisory_unlock(${INIT_DB_LOCK_KEY_SQL})`)
} catch (unlockError) {
- console.warn('[ControlAPI] initDb advisory unlock failed:', unlockError)
+ rootLogger.warn({ err: unlockError }, 'database migration advisory unlock failed')
}
}
client.release()
diff --git a/control-api/src/middleware/passwordLoginAdmission.ts b/control-api/src/middleware/passwordLoginAdmission.ts
new file mode 100644
index 000000000..aab5842fa
--- /dev/null
+++ b/control-api/src/middleware/passwordLoginAdmission.ts
@@ -0,0 +1,65 @@
+import type { NextFunction, Request, Response } from 'express'
+import { isIP } from 'node:net'
+import { z } from 'zod'
+import { PASSWORD_ADMISSION_POLICY } from '../services/auth/passwordAdmissionState.js'
+import { PasswordAdmissionError } from '../services/auth/passwordCredentialVerification.js'
+import { rateLimitMiddleware } from './rateLimitMiddleware.js'
+
+const credentials = z.object({
+ email: z.string().trim().min(1).max(320),
+ password: z.string().min(1).max(256),
+})
+
+export function sendPasswordAdmissionError(error: unknown, res: Response): boolean {
+ if (!(error instanceof PasswordAdmissionError)) return false
+ for (const name of [
+ 'X-RateLimit-Limit',
+ 'X-RateLimit-Remaining',
+ 'X-RateLimit-Reset',
+ 'RateLimit',
+ 'RateLimit-Policy',
+ ])
+ res.removeHeader(name)
+ res.setHeader('Cache-Control', 'no-store')
+ res.setHeader('Retry-After', String(error.retryAfterSeconds))
+ res.status(error.status).json({
+ error: error.status === 429 ? 'rate_limited' : 'authority_unavailable',
+ retryAfterSeconds: error.retryAfterSeconds,
+ })
+ return true
+}
+
+export function validatePasswordLogin(req: Request, res: Response, next: NextFunction): void {
+ const parsed = credentials.safeParse(req.body)
+ if (!parsed.success) {
+ res.status(400).json({ error: 'invalid_request' })
+ return
+ }
+ req.body = { ...req.body, email: parsed.data.email.toLowerCase(), password: parsed.data.password }
+ next()
+}
+
+export const passwordLoginSourceAdmission = rateLimitMiddleware({
+ bucketType: 'external_authentication_attempt',
+ maxPerMinute: PASSWORD_ADMISSION_POLICY.sourceAttemptsPerMinute,
+ onBackendUnavailable: 'closed',
+ getBucketKey: req => {
+ // Trust only the authenticated External REST producer. Support its current
+ // dev header and the Task 106 header during eventual integration.
+ const asserted =
+ req.internalService?.name === 'external-rest-api'
+ ? req.header('x-evenfire-client-ip') || req.header('x-external-client-ip')
+ : undefined
+ const ip =
+ asserted && isIP(asserted.trim())
+ ? asserted.trim()
+ : req.ip || req.socket?.remoteAddress || 'unknown'
+ return `external_authentication_attempt:ip:${String(ip).slice(0, 128)}`
+ },
+ onLimited: (_req, res, retryAfterSeconds) => {
+ sendPasswordAdmissionError(
+ new PasswordAdmissionError(429, Math.min(60, retryAfterSeconds)),
+ res
+ )
+ },
+})
diff --git a/control-api/src/middleware/rateLimitMiddleware.ts b/control-api/src/middleware/rateLimitMiddleware.ts
index fca6bc1c3..36d928ca4 100644
--- a/control-api/src/middleware/rateLimitMiddleware.ts
+++ b/control-api/src/middleware/rateLimitMiddleware.ts
@@ -24,6 +24,7 @@ export type RateLimitEnforcerOptions = {
bucketType: string
maxPerMinute: number
onBackendUnavailable: RateLimitBackendUnavailableMode
+ onLimited?: (req: Request, res: Response, retryAfterSeconds: number) => void
}
/**
@@ -167,7 +168,8 @@ export function createRateLimitEnforcer(opts: RateLimitEnforcerOptions): RateLim
'rate limit exceeded'
)
}
- res.status(429).json({ error: 'Too Many Requests', retryAfterSeconds: retryAfterSec })
+ if (opts.onLimited) opts.onLimited(req, res, retryAfterSec)
+ else res.status(429).json({ error: 'Too Many Requests', retryAfterSeconds: retryAfterSec })
}
return async function enforce(req: Request, res: Response, rawKey: string): Promise<boolean> {
diff --git a/control-api/src/routes/external/auth.ts b/control-api/src/routes/external/auth.ts
index 48dd8690d..3bbceeaad 100644
--- a/control-api/src/routes/external/auth.ts
+++ b/control-api/src/routes/external/auth.ts
@@ -3,6 +3,11 @@ import { createHash } from 'node:crypto'
import { pool } from '../../db.js'
import type { K8sGateway } from '../../k8s.js'
import { isCurrentExternalSession } from '../../middleware/externalSessionAuth.js'
+import {
+ passwordLoginSourceAdmission,
+ sendPasswordAdmissionError,
+ validatePasswordLogin,
+} from '../../middleware/passwordLoginAdmission.js'
import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
import { AuthClaims, RpcScope, TEAM_ROLES } from '../../profileTypes.js'
import {
@@ -70,54 +75,49 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
}
})
- router.post('/external/auth/password-login', async (req, res, next) => {
- try {
- const email = String(req.body?.email || '')
- .trim()
- .toLowerCase()
- const password = String(req.body?.password || '')
- if (!email || !password) {
- return res.status(400).json({ error: 'email and password are required' })
- }
-
- const login = await passwordLoginData({ email, password })
- if (!login) {
- return res.status(401).json({ error: 'Unauthorized' })
- }
- if ('error' in login) {
- if (login.error === 'user_retired') {
- return res.status(401).json({ error: 'Unauthorized' })
- }
- if (login.error === 'password_not_set') {
- return res.status(409).json({ error: 'password_not_set' })
+ router.post(
+ '/external/auth/password-login',
+ validatePasswordLogin,
+ passwordLoginSourceAdmission,
+ async (req, res, next) => {
+ try {
+ const email = String(req.body?.email || '')
+ .trim()
+ .toLowerCase()
+ const password = String(req.body?.password || '')
+ if (!email || !password) {
+ return res.status(400).json({ error: 'email and password are required' })
}
- return res.status(403).json({ error: 'membership_not_found' })
- }
- const role = login.membership.role
- const token = signExternalSessionToken({
- userId: login.user.id,
- email: login.user.email,
- teamId: login.membership.team_id || null,
- role,
- authGeneration: login.authGeneration,
- })
- return res.status(200).json({
- token,
- me: {
- id: login.user.id,
+ const login = await passwordLoginData({ email, password })
+ if (!login) return res.status(401).json({ error: 'invalid_credentials' })
+
+ const role = login.membership.role
+ const token = signExternalSessionToken({
+ userId: login.user.id,
email: login.user.email,
- name: login.user.name,
- picture: login.user.picture,
teamId: login.membership.team_id || null,
- teamName: login.membership.team_name,
role,
- },
- })
- } catch (error) {
- return next(error)
+ authGeneration: login.authGeneration,
+ })
+ return res.status(200).json({
+ token,
+ me: {
+ id: login.user.id,
+ email: login.user.email,
+ name: login.user.name,
+ picture: login.user.picture,
+ teamId: login.membership.team_id || null,
+ teamName: login.membership.team_name,
+ role,
+ },
+ })
+ } catch (error) {
+ if (sendPasswordAdmissionError(error, res)) return
+ return next(error)
+ }
}
- })
+ )
router.post(
'/external/auth/password-reset/request',
diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.ts
index bacba9eba..502363b5f 100644
--- a/control-api/src/routes/external/invitations.ts
+++ b/control-api/src/routes/external/invitations.ts
@@ -7,6 +7,7 @@ import {
rejectBodyUserTeamMismatch,
requireValidExternalSessionToken,
} from '../../middleware/externalSessionAuth.js'
+import { sendPasswordAdmissionError } from '../../middleware/passwordLoginAdmission.js'
import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
import {
acceptInvitationForEmail,
@@ -246,6 +247,7 @@ export function createExternalInvitationsRouter(): Router {
expiresInSeconds: 120,
})
} catch (error) {
+ if (sendPasswordAdmissionError(error, res)) return
return next(error)
}
}
diff --git a/control-api/src/services/auth/passwordAdmissionSchema.ts b/control-api/src/services/auth/passwordAdmissionSchema.ts
new file mode 100644
index 000000000..0a78ffc8a
--- /dev/null
+++ b/control-api/src/services/auth/passwordAdmissionSchema.ts
@@ -0,0 +1,54 @@
+import type { DbClient } from '../../db.js'
+
+/** New forward migration; database triggers cover all credential/lifecycle producers. */
+export async function applyPasswordAdmissionSchema(db: Pick<DbClient, 'query'>): Promise<void> {
+ await db.query(`
+ ALTER TABLE users ADD COLUMN IF NOT EXISTS password_auth_generation BIGINT NOT NULL DEFAULT 1;
+ CREATE TABLE IF NOT EXISTS password_identifier_state (
+ identifier_key TEXT PRIMARY KEY CHECK (identifier_key ~ '^[0-9a-f]{64}$'),
+ instance UUID NOT NULL DEFAULT gen_random_uuid(),
+ revision BIGINT NOT NULL DEFAULT 1,
+ user_id UUID REFERENCES users(id) ON DELETE SET NULL,
+ attempts BIGINT[] NOT NULL DEFAULT '{}',
+ failures BIGINT[] NOT NULL DEFAULT '{}',
+ locked_until_ms BIGINT NOT NULL DEFAULT 0,
+ CHECK (cardinality(attempts) <= 5), CHECK (cardinality(failures) <= 5)
+ );
+ CREATE INDEX IF NOT EXISTS password_identifier_user_idx ON password_identifier_state(user_id);
+ CREATE TABLE IF NOT EXISTS password_verification_pace (
+ singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton),
+ next_permit TIMESTAMPTZ NOT NULL
+ );
+ CREATE OR REPLACE FUNCTION password_credential_generation_fence() RETURNS trigger
+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+ BEGIN
+ IF TG_OP = 'INSERT' THEN
+ NEW.password_auth_generation := 1;
+ UPDATE public.password_identifier_state
+ SET failures = '{}', locked_until_ms = 0, revision = revision + 1
+ WHERE identifier_key = encode(sha256(convert_to(NEW.email, 'UTF8')), 'hex');
+ RETURN NEW;
+ END IF;
+ IF NEW.password_hash IS DISTINCT FROM OLD.password_hash
+ OR NEW.email IS DISTINCT FROM OLD.email
+ OR NEW.lifecycle_state IS DISTINCT FROM OLD.lifecycle_state
+ OR NEW.lifecycle_version IS DISTINCT FROM OLD.lifecycle_version THEN
+ NEW.password_auth_generation := OLD.password_auth_generation + 1;
+ UPDATE public.password_identifier_state
+ SET failures = '{}', locked_until_ms = 0, revision = revision + 1
+ WHERE user_id = OLD.id
+ OR identifier_key IN (
+ encode(sha256(convert_to(OLD.email, 'UTF8')), 'hex'),
+ encode(sha256(convert_to(NEW.email, 'UTF8')), 'hex'));
+ ELSE
+ NEW.password_auth_generation := OLD.password_auth_generation;
+ END IF;
+ RETURN NEW;
+ END $$;
+ DROP TRIGGER IF EXISTS password_credential_generation_fence ON users;
+ CREATE TRIGGER password_credential_generation_fence BEFORE INSERT OR UPDATE ON users
+ FOR EACH ROW EXECUTE FUNCTION password_credential_generation_fence();
+ GRANT SELECT, INSERT, UPDATE, DELETE ON password_identifier_state, password_verification_pace
+ TO control_api_runtime;
+ `)
+}
diff --git a/control-api/src/services/auth/passwordAdmissionState.ts b/control-api/src/services/auth/passwordAdmissionState.ts
new file mode 100644
index 000000000..1cb9460c8
--- /dev/null
+++ b/control-api/src/services/auth/passwordAdmissionState.ts
@@ -0,0 +1,58 @@
+import { createHash } from 'node:crypto'
+
+// Spec 043: capacity and abuse policy. Changing these requires owner policy approval.
+export const PASSWORD_ADMISSION_POLICY = Object.freeze({
+ sourceAttemptsPerMinute: 5,
+ identifierAttempts: 5,
+ windowMs: 15 * 60_000,
+ failures: 5,
+ cooldownMs: 15 * 60_000,
+ paceMs: 7_500,
+ concurrency: 1,
+ bcryptCost: 12,
+})
+
+export type PasswordIdentifierState = {
+ attempts: number[]
+ failures: number[]
+ lockedUntil: number
+}
+
+export function passwordIdentifierKey(email: string): string {
+ return createHash('sha256').update(email.trim().toLowerCase()).digest('hex')
+}
+
+export function settledPasswordState(state: PasswordIdentifierState, now: number) {
+ const cutoff = now - PASSWORD_ADMISSION_POLICY.windowMs
+ return {
+ attempts: state.attempts.filter(time => time > cutoff),
+ failures: state.failures.filter(time => time > cutoff),
+ lockedUntil: state.lockedUntil > now ? state.lockedUntil : 0,
+ }
+}
+
+export function admitPasswordIdentifier(
+ state: PasswordIdentifierState,
+ now: number,
+ chargeAttempt: boolean
+): { state: PasswordIdentifierState; retryMs: number } {
+ const settled = settledPasswordState(state, now)
+ const budgetEnd =
+ chargeAttempt && settled.attempts.length >= PASSWORD_ADMISSION_POLICY.identifierAttempts
+ ? settled.attempts[0] + PASSWORD_ADMISSION_POLICY.windowMs
+ : 0
+ const retryMs = Math.max(0, settled.lockedUntil - now, budgetEnd - now)
+ if (retryMs > 0) return { state: settled, retryMs }
+ if (chargeAttempt) settled.attempts.push(now)
+ return { state: settled, retryMs: 0 }
+}
+
+export function finishPasswordState(state: PasswordIdentifierState, now: number, success: boolean) {
+ const settled = settledPasswordState(state, now)
+ if (success) return { ...settled, failures: [], lockedUntil: 0 }
+ if (settled.lockedUntil > now) return settled
+ settled.failures.push(now)
+ if (settled.failures.length >= PASSWORD_ADMISSION_POLICY.failures)
+ settled.lockedUntil = now + PASSWORD_ADMISSION_POLICY.cooldownMs
+ return settled
+}
diff --git a/control-api/src/services/auth/passwordCredentialVerification.ts b/control-api/src/services/auth/passwordCredentialVerification.ts
new file mode 100644
index 000000000..bb86f8115
--- /dev/null
+++ b/control-api/src/services/auth/passwordCredentialVerification.ts
@@ -0,0 +1,233 @@
+import bcrypt from 'bcryptjs'
+import { type DbTransactionClient, pool, withTransaction } from '../../db.js'
+import { rootLogger } from '../../observability/logger.js'
+import { acquireRateLimitConcurrencyLease } from '../rateLimiterService.js'
+import {
+ type PasswordIdentifierState,
+ admitPasswordIdentifier,
+ finishPasswordState,
+ passwordIdentifierKey,
+ PASSWORD_ADMISSION_POLICY as policy,
+} from './passwordAdmissionState.js'
+
+// Synthetic, repository-controlled cost-12 hash, precomputed once, never per request.
+export const PASSWORD_DUMMY_HASH = '$2b$12$DdpJSFUb/dYx43plh72Ia.k9RJ8krESZ/DtTRUbdQq/ngzfJuyCUu'
+const logger = rootLogger.child({ module: 'password-admission' })
+
+export class PasswordAdmissionError extends Error {
+ constructor(
+ readonly status: 429 | 503,
+ readonly retryAfterSeconds: number
+ ) {
+ super(status === 429 ? 'rate_limited' : 'authority_unavailable')
+ }
+}
+function denied(retryMs: number): never {
+ throw new PasswordAdmissionError(429, Math.min(900, Math.max(1, Math.ceil(retryMs / 1000))))
+}
+export type PasswordUser = {
+ id: string
+ email: string
+ name: string | null
+ picture: string | null
+ password_hash: string | null
+ lifecycle_state: string
+ lifecycle_version: string | number
+ password_auth_generation: string | number
+}
+export type PasswordCapture = {
+ email: string
+ key: string
+ instance: string
+ revision: string
+ user: PasswordUser | null
+}
+type StateRow = {
+ instance: string
+ revision: string
+ attempts: string[]
+ failures: string[]
+ locked_until_ms: string
+}
+function stateOf(row: StateRow): PasswordIdentifierState {
+ return {
+ attempts: row.attempts.map(Number),
+ failures: row.failures.map(Number),
+ lockedUntil: Number(row.locked_until_ms),
+ }
+}
+async function databaseNow(db: Pick<DbTransactionClient, 'query'>): Promise<number> {
+ const result = await db.query(
+ 'SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::text AS now_ms'
+ )
+ return Number((result.rows[0] as { now_ms: string }).now_ms)
+}
+
+export async function capturePasswordEvaluation(
+ email: string,
+ chargeAttempt: boolean
+): Promise<PasswordCapture> {
+ const normalized = email.trim().toLowerCase()
+ const key = passwordIdentifierKey(normalized)
+ const snapshot = await withTransaction(async db => {
+ await db.query(
+ 'INSERT INTO password_identifier_state(identifier_key) VALUES ($1) ON CONFLICT DO NOTHING',
+ [key]
+ )
+ const result = await db.query(
+ 'SELECT * FROM password_identifier_state WHERE identifier_key = $1 FOR UPDATE',
+ [key]
+ )
+ const row = result.rows[0] as StateRow
+ const decision = admitPasswordIdentifier(stateOf(row), await databaseNow(db), chargeAttempt)
+ // A denied request never writes: it cannot move the rolling denial horizon.
+ if (decision.retryMs) return { retryMs: decision.retryMs, row }
+ await db.query(
+ 'UPDATE password_identifier_state SET attempts = $2, failures = $3, locked_until_ms = $4 WHERE identifier_key = $1',
+ [key, decision.state.attempts, decision.state.failures, decision.state.lockedUntil]
+ )
+ return { retryMs: 0, row }
+ })
+ if (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]
+ )
+ return {
+ email: normalized,
+ key,
+ instance: snapshot.row.instance,
+ revision: String(snapshot.row.revision),
+ user: (users.rows[0] as PasswordUser) ?? null,
+ }
+}
+
+export async function reservePasswordPace(): Promise<void> {
+ const result = await pool.query(
+ `INSERT INTO password_verification_pace(singleton, next_permit)
+ VALUES (TRUE, clock_timestamp() + $1 * interval '1 millisecond')
+ ON CONFLICT (singleton) DO UPDATE SET next_permit = clock_timestamp() + $1 * interval '1 millisecond'
+ WHERE password_verification_pace.next_permit <= clock_timestamp()
+ RETURNING singleton`,
+ [policy.paceMs]
+ )
+ if (!result.rows.length) {
+ const remaining = await pool.query(
+ `SELECT greatest(1, ceil(extract(epoch FROM next_permit - clock_timestamp()) * 1000)) AS retry_ms FROM password_verification_pace WHERE singleton`
+ )
+ denied(Number(remaining.rows[0]?.retry_ms ?? policy.paceMs))
+ }
+}
+
+export async function completePasswordEvaluation(
+ capture: PasswordCapture,
+ success: boolean
+): Promise<boolean> {
+ return withTransaction(async db => {
+ // Credential writers lock users then identifier state (via the trigger).
+ // This same order fences completion without a deadlock or a lock across bcrypt.
+ const current = await db.query(
+ `SELECT id, password_auth_generation FROM users WHERE email = $1 FOR SHARE`,
+ [capture.email]
+ )
+ const user = current.rows[0] as { id: string; password_auth_generation: string } | undefined
+ if (
+ capture.user
+ ? !user ||
+ user.id !== capture.user.id ||
+ String(user.password_auth_generation) !== String(capture.user.password_auth_generation)
+ : !!user
+ )
+ return false
+ const result = await db.query(
+ 'SELECT * FROM password_identifier_state WHERE identifier_key = $1 FOR UPDATE',
+ [capture.key]
+ )
+ const row = result.rows[0] as StateRow | undefined
+ // Instance makes cleanup/recreation ABA-safe; revision fences stale results after success.
+ if (!row || row.instance !== capture.instance || String(row.revision) !== capture.revision)
+ return false
+ const state = finishPasswordState(stateOf(row), await databaseNow(db), success)
+ await db.query(
+ `UPDATE password_identifier_state SET failures = $2, locked_until_ms = $3,
+ revision = revision + $4, user_id = $5 WHERE identifier_key = $1`,
+ [capture.key, state.failures, state.lockedUntil, success ? 1 : 0, capture.user?.id ?? null]
+ )
+ return true
+ })
+}
+
+let busy = false
+export async function verifyMemberPassword(
+ email: string,
+ password: string,
+ options: { publicLogin: boolean; userId?: string }
+): Promise<PasswordUser | null> {
+ try {
+ const capture = await capturePasswordEvaluation(email, options.publicLogin)
+ await reservePasswordPace()
+ // The pace permit is deliberately not refunded on a busy lease.
+ if (busy) denied(policy.paceMs)
+ busy = true
+ try {
+ const lease = await acquireRateLimitConcurrencyLease(
+ [{ bucketKey: 'password-verification-global', maxConcurrent: policy.concurrency }],
+ { releaseIdleClient: true }
+ )
+ if (!lease.backendAvailable) throw new PasswordAdmissionError(503, 2)
+ if (!lease.allowed) denied(policy.paceMs)
+ try {
+ const user = capture.user
+ const eligible =
+ !!user &&
+ user.lifecycle_state === 'active' &&
+ (!options.userId || options.userId === user.id)
+ let supported = false
+ if (eligible && user.password_hash) {
+ try {
+ supported =
+ /^\$2[aby]\$12\$[./A-Za-z0-9]{53}$/.test(user.password_hash) &&
+ bcrypt.getRounds(user.password_hash) === policy.bcryptCost
+ } catch {
+ supported = false
+ }
+ if (!supported)
+ logger.info(
+ { event: 'password_credential_reset_required' },
+ 'unsupported member credential'
+ )
+ }
+ const match = await bcrypt.compare(
+ password,
+ supported ? user!.password_hash! : PASSWORD_DUMMY_HASH
+ )
+ const authenticated = eligible && supported && match
+ const current = await completePasswordEvaluation(capture, authenticated)
+ return current && authenticated ? user : null
+ } finally {
+ await lease.release()
+ }
+ } finally {
+ busy = false
+ }
+ } catch (error) {
+ if (error instanceof PasswordAdmissionError) throw error
+ // Do not log SQL, identifiers, hashes, submitted credentials or backend messages.
+ logger.warn({ event: 'password_authority_unavailable' }, 'password authority unavailable')
+ throw new PasswordAdmissionError(503, 2)
+ }
+}
+
+/** Independent retention; old token-bucket cleanup never owns these rows. */
+export async function cleanupPasswordIdentifierState(): Promise<number> {
+ const result = await pool.query(
+ `DELETE FROM password_identifier_state
+ WHERE locked_until_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)
+ AND NOT EXISTS (SELECT 1 FROM unnest(attempts || failures) t
+ WHERE t > floor(extract(epoch FROM clock_timestamp()) * 1000) - $1)`,
+ [policy.windowMs]
+ )
+ return result.rowCount ?? 0
+}
diff --git a/control-api/src/services/directory/login.ts b/control-api/src/services/directory/login.ts
index afbe4ac08..1249f4099 100644
--- a/control-api/src/services/directory/login.ts
+++ b/control-api/src/services/directory/login.ts
@@ -1,5 +1,5 @@
-import bcrypt from 'bcryptjs'
import { withTransaction } from '../../db.js'
+import { verifyMemberPassword } from '../auth/passwordCredentialVerification.js'
import type { TeamRole } from './types.js'
type MembershipRow = {
@@ -199,39 +199,9 @@ export async function googleLoginData(input: { email: string; name?: string; pic
}
export async function passwordLoginData(input: { email: string; password: string }) {
+ const user = await verifyMemberPassword(input.email, input.password, { publicLogin: true })
+ if (!user) return null
return withTransaction(async db => {
- const result = await db.query(
- `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
- FROM users
- WHERE email = $1
- LIMIT 1`,
- [input.email.trim().toLowerCase()]
- )
- if ((result.rowCount ?? 0) === 0) {
- return null
- }
-
- const user = result.rows[0] as {
- id: string
- email: string
- name: string | null
- picture: string | null
- password_hash: string | null
- lifecycle_state?: string | null
- lifecycle_version?: number | string | null
- }
- if (user.lifecycle_state !== 'active') {
- return { error: 'user_retired' as const }
- }
- if (!user.password_hash) {
- return { error: 'password_not_set' as const }
- }
-
- const matches = await bcrypt.compare(input.password, user.password_hash)
- if (!matches) {
- return null
- }
-
let membership = await findFirstActiveMembership(db, user.id)
if ((membership.rowCount ?? 0) === 0) {
await healAcceptedInvitationMemberships(db, user.id, user.email)
@@ -270,21 +240,9 @@ export async function verifyUserPassword(input: {
email: string
password: string
}): Promise<boolean> {
- const result = await withTransaction(async db =>
- db.query(
- `SELECT password_hash
- FROM users
- WHERE id = $1
- AND email = $2
- AND lifecycle_state = 'active'
- LIMIT 1`,
- [input.userId.trim(), input.email.trim().toLowerCase()]
- )
- )
-
- const row = result.rows[0] as { password_hash: string | null } | undefined
- if (!row?.password_hash) {
- return false
- }
- return bcrypt.compare(input.password, row.password_hash)
+ const user = await verifyMemberPassword(input.email, input.password, {
+ publicLogin: false,
+ userId: input.userId.trim(),
+ })
+ return !!user
}
diff --git a/control-api/src/services/rateLimiterService.ts b/control-api/src/services/rateLimiterService.ts
index 5ee268d78..dd2440e52 100644
--- a/control-api/src/services/rateLimiterService.ts
+++ b/control-api/src/services/rateLimiterService.ts
@@ -4,6 +4,7 @@ import { pool, rateLimitPool } from '../db.js'
import { LogThrottle } from '../observability/logThrottle.js'
import { rootLogger } from '../observability/logger.js'
import { rateLimitBackendErrorsTotal } from '../observability/metrics.js'
+import { cleanupPasswordIdentifierState } from './auth/passwordCredentialVerification.js'
import { boundedBucketKey } from './rateLimitBucketKey.js'
/**
@@ -172,6 +173,8 @@ export type RateLimitConcurrencyLease = {
export type RateLimitConcurrencyLeaseOptions = {
/** Test/integration seam; production callers use the dedicated pool client. */
client?: PoolClient
+ /** Finite credential work must not pin a pool session after its final lease. */
+ releaseIdleClient?: boolean
}
let concurrencyClient: PoolClient | null = null
@@ -343,13 +346,15 @@ export async function acquireRateLimitConcurrencyLease(
}
if (!selected) {
const unlocked = await unlockSlots(client, acquired)
- if (!unlocked) await invalidateDedicatedConcurrencyClient(client)
+ if (!unlocked || (options.releaseIdleClient && heldSlotsFor(client).size === 0))
+ await invalidateDedicatedConcurrencyClient(client)
return { allowed: false, backendAvailable: true, release: async () => undefined }
}
}
} catch (error) {
const unlocked = await unlockSlots(client, acquired)
- if (!unlocked) await invalidateDedicatedConcurrencyClient(client)
+ if (!unlocked || (options.releaseIdleClient && heldSlotsFor(client).size === 0))
+ await invalidateDedicatedConcurrencyClient(client)
rootLogger.warn(
{
event: 'rate_limit_concurrency_db_error',
@@ -369,7 +374,8 @@ export async function acquireRateLimitConcurrencyLease(
released = true
await serializeConcurrencyOperation(async () => {
const unlocked = await unlockSlots(client, acquired)
- if (!unlocked) await invalidateDedicatedConcurrencyClient(client)
+ if (!unlocked || (options.releaseIdleClient && heldSlotsFor(client).size === 0))
+ await invalidateDedicatedConcurrencyClient(client)
})
},
}
@@ -386,6 +392,7 @@ export async function cleanupExpiredBuckets(nowMs = Date.now()): Promise<number>
`DELETE FROM rate_limit_buckets WHERE window_start_ms < $1`,
[cutoff]
)
+ await cleanupPasswordIdentifierState()
return result.rowCount ?? 0
}
diff --git a/control-api/test/bug192.passwordAdmissionState.property.test.ts b/control-api/test/bug192.passwordAdmissionState.property.test.ts
new file mode 100644
index 000000000..3d4b19d37
--- /dev/null
+++ b/control-api/test/bug192.passwordAdmissionState.property.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import {
+ admitPasswordIdentifier,
+ finishPasswordState,
+ passwordIdentifierKey,
+ PASSWORD_ADMISSION_POLICY as policy,
+} from '../src/services/auth/passwordAdmissionState.js'
+
+describe('Spec 043 state-transition design invariants', () => {
+ it('makes real/shadow state transitions identical and denies without extending', () => {
+ fc.assert(
+ fc.property(
+ fc.array(fc.integer({ min: 0, max: policy.windowMs * 3 }), { maxLength: 100 }),
+ times => {
+ const sorted = times.sort((a, b) => a - b)
+ let real = { attempts: [] as number[], failures: [] as number[], lockedUntil: 0 }
+ let shadow = structuredClone(real)
+ for (const now of sorted) {
+ const a = admitPasswordIdentifier(real, now, true),
+ b = admitPasswordIdentifier(shadow, now, true)
+ expect(a).toEqual(b)
+ if (a.retryMs) {
+ expect(a.state.attempts.every(t => real.attempts.includes(t))).toBe(true)
+ expect(a.state.lockedUntil).toBeLessThanOrEqual(real.lockedUntil)
+ real = a.state
+ shadow = b.state
+ } else {
+ real = finishPasswordState(a.state, now, false)
+ shadow = finishPasswordState(b.state, now, false)
+ }
+ expect(real).toEqual(shadow)
+ expect(real.attempts.length).toBeLessThanOrEqual(5)
+ expect(real.failures.length).toBeLessThanOrEqual(5)
+ }
+ }
+ ),
+ { numRuns: 1000 }
+ )
+ })
+ it('sets exactly one cooldown at the fifth failed evaluation and clears on success', () => {
+ let state = { attempts: [] as number[], failures: [] as number[], lockedUntil: 0 }
+ for (let i = 0; i < 5; i++) state = finishPasswordState(state, i * 10000, false)
+ expect(state.lockedUntil).toBe(40000 + policy.cooldownMs)
+ expect(finishPasswordState(state, 50000, false).lockedUntil).toBe(state.lockedUntil)
+ expect(finishPasswordState(state, 50000, true)).toMatchObject({ failures: [], lockedUntil: 0 })
+ expect(admitPasswordIdentifier(state, state.lockedUntil, true).retryMs).toBe(0)
+ })
+ it('canonicalizes keys without retaining the submitted identity', () => {
+ expect(passwordIdentifierKey(' [email protected] ')).toBe(
+ passwordIdentifierKey('[email protected]')
+ )
+ expect(passwordIdentifierKey('[email protected]')).toMatch(/^[0-9a-f]{64}$/)
+ })
+})
diff --git a/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts b/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts
new file mode 100644
index 000000000..c54d41a28
--- /dev/null
+++ b/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts
@@ -0,0 +1,388 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import bcrypt from 'bcryptjs'
+import { createPublicKey, randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import request from 'supertest'
+import { initDb } from '../src/db.js'
+import { createExternalAuthRouter } from '../src/routes/external/auth.js'
+import { passwordLoginData, verifyUserPassword } from '../src/services/directory/login.js'
+import { verifyExternalSessionToken } from '../src/utils/auth/externalSessionAuthToken.js'
+import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
+
+const holder = vi.hoisted(() => ({
+ pool: null as unknown as Pool,
+ leaseClient: null as unknown as import('pg').PoolClient,
+}))
+vi.mock('../src/db.js', async importOriginal => {
+ const real = await importOriginal<typeof import('../src/db.js')>()
+ const proxy = {
+ query: (...args: unknown[]) => (holder.pool.query as Function)(...args),
+ connect: () => holder.pool.connect(),
+ }
+ return {
+ ...real,
+ pool: proxy,
+ rateLimitPool: proxy,
+ withTransaction: (fn: Parameters<typeof real.withTransaction>[0]) =>
+ real.withTransaction(fn, holder.pool),
+ }
+})
+vi.mock('../src/services/rateLimiterService.js', async importOriginal => {
+ const real = await importOriginal<typeof import('../src/services/rateLimiterService.js')>()
+ return {
+ ...real,
+ acquireRateLimitConcurrencyLease: (
+ requirements: Parameters<typeof real.acquireRateLimitConcurrencyLease>[0]
+ ) => real.acquireRateLimitConcurrencyLease(requirements, { client: holder.leaseClient }),
+ }
+})
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const realPg = adminUrl ? describe : describe.skip
+const password = 'Synthetic-BUG192-correct-password'
+realPg('BUG-192 observable password-login regressions on real PostgreSQL', () => {
+ const database = `bug192_${randomBytes(6).toString('hex')}`
+ let admin: Pool
+ let app: express.Express
+ let realHash: string
+ let userId: string
+ let compare: ReturnType<typeof vi.spyOn>
+ // New-state manipulation is only clock/admission setup. At the buggy base
+ // it is a no-op so T3 failures remain observable assertions, not absent-schema errors.
+ async function newStateExists() {
+ return !!(
+ await holder.pool.query("SELECT to_regclass('password_identifier_state') AS relation")
+ ).rows[0].relation
+ }
+ async function openPace() {
+ if (await newStateExists())
+ await holder.pool.query(
+ "UPDATE password_verification_pace SET next_permit = clock_timestamp() - interval '1 second'"
+ )
+ }
+ async function login(email: string, submitted = 'Synthetic-wrong-password', ip = '192.0.2.1') {
+ return request(app)
+ .post('/external/auth/password-login')
+ .set('x-external-client-ip', ip)
+ .send({ email, password: submitted })
+ }
+ beforeAll(async () => {
+ admin = new Pool({ connectionString: adminUrl })
+ await admin.query(`CREATE DATABASE "${database}"`)
+ const url = new URL(adminUrl!)
+ url.pathname = `/${database}`
+ holder.pool = new Pool({ connectionString: url.toString() })
+ await initDb(holder.pool)
+ holder.leaseClient = await holder.pool.connect()
+ realHash = await bcrypt.hash(password, 12)
+ app = express()
+ app.use(express.json())
+ app.use((req, _res, next) => {
+ req.internalService = { name: 'external-rest-api' }
+ next()
+ })
+ app.use(createExternalAuthRouter({} as Parameters<typeof createExternalAuthRouter>[0]))
+ app.use(
+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) =>
+ res.status(500).json({ error: 'unexpected_test_failure' })
+ )
+ }, 60_000)
+ beforeEach(async () => {
+ vi.restoreAllMocks()
+ await holder.pool.query('DELETE FROM team_members')
+ await holder.pool.query('DELETE FROM invitations')
+ await holder.pool.query('DELETE FROM teams')
+ await holder.pool.query('DELETE FROM users')
+ await holder.pool.query('DELETE FROM rate_limit_buckets')
+ if (await newStateExists()) {
+ await holder.pool.query('DELETE FROM password_identifier_state')
+ await holder.pool.query('DELETE FROM password_verification_pace')
+ }
+ userId = (
+ await holder.pool.query(
+ "INSERT INTO users(email, password_hash) VALUES ('[email protected]', $1) RETURNING id",
+ [realHash]
+ )
+ ).rows[0].id
+ compare = vi.spyOn(bcrypt, 'compare')
+ })
+ afterAll(async () => {
+ try {
+ vi.restoreAllMocks()
+ holder.leaseClient?.release()
+ await endPoolAndWaitForClients(holder.pool)
+ if (admin) await admin.query(`DROP DATABASE IF EXISTS "${database}"`)
+ } finally {
+ await admin?.end()
+ }
+ })
+
+ 'returns the identical generic credential failure for %s',
+ async email => {
+ await holder.pool.query(
+ "INSERT INTO users(email) VALUES ('[email protected]') ON CONFLICT DO NOTHING"
+ )
+ const response = await login(email)
+ expect({ status: response.status, body: response.body }).toEqual({
+ status: 401,
+ body: { error: 'invalid_credentials' },
+ })
+ }
+ )
+ 'performs cost-12 dummy work for admitted %s',
+ async email => {
+ await holder.pool.query(
+ "INSERT INTO users(email) VALUES ('[email protected]') ON CONFLICT DO NOTHING"
+ )
+ await login(email)
+ expect(compare).toHaveBeenCalledTimes(1)
+ expect(bcrypt.getRounds(compare.mock.calls[0][1] as string)).toBe(12)
+ }
+ )
+ it.each([10, 11, 13, 14])('does not verify a stored cost-%i credential', async cost => {
+ // Library producer emits the exact hash format, with real cost-12 work
+ // avoided for deliberately unsupported synthetic costs during fixture setup.
+ const hash = await bcrypt.hash(password, cost)
+ await holder.pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, userId])
+ const response = await login('[email protected]', password)
+ expect(response.status).toBe(401)
+ expect(response.body).toEqual({ error: 'invalid_credentials' })
+ expect(compare).toHaveBeenCalledTimes(1)
+ expect(compare.mock.calls[0][1]).not.toBe(hash)
+ expect(bcrypt.getRounds(compare.mock.calls[0][1] as string)).toBe(12)
+ })
+ it('denies a sixth source attempt before bcrypt', async () => {
+ for (let i = 0; i < 5; i++) {
+ await openPace()
+ await login(`source-${i}@example.invalid`)
+ }
+ const before = compare.mock.calls.length
+ const response = await login('[email protected]')
+ expect(response.status).toBe(429)
+ expect(response.body.error).toBe('rate_limited')
+ expect(compare.mock.calls.length).toBe(before)
+ })
+ it('denies rotating sources and canonical identifier variants after five attempts', async () => {
+ for (let i = 0; i < 5; i++) {
+ await openPace()
+ await login(
+ 'wrong',
+ `192.0.2.${i + 1}`
+ )
+ }
+ const before = compare.mock.calls.length
+ const response = await login('[email protected]', 'wrong', '192.0.2.100')
+ expect(response.status).toBe(429)
+ expect(response.body.error).toBe('rate_limited')
+ expect(compare.mock.calls.length).toBe(before)
+ })
+ it('applies the same pace to unknown and existing evaluations with burst one', async () => {
+ expect((await login('[email protected]')).status).toBe(401)
+ const response = await login('[email protected]', 'wrong', '192.0.2.2')
+ expect(response.status).toBe(429)
+ expect(compare).toHaveBeenCalledTimes(1)
+ expect(Number(response.headers['retry-after'])).toBeGreaterThan(0)
+ expect(Number(response.headers['retry-after'])).toBeLessThanOrEqual(8)
+ })
+ it('keeps real and shadow cooldown status/body/retry metadata identical', async () => {
+ // Backdate admitted attempts and completed failures using the DB clock,
+ // then retain the real admission producer for the fifth transition.
+ for (const email of ['[email protected]', '[email protected]']) {
+ for (let i = 0; i < 5; i++) {
+ await openPace()
+ await login(email, 'wrong', `192.0.2.${i + 1}`)
+ await holder.pool.query('DELETE FROM rate_limit_buckets')
+ }
+ }
+ const known = await login('[email protected]', 'wrong', '192.0.2.80')
+ const shadow = await login('[email protected]', 'wrong', '192.0.2.81')
+ expect(known.status).toBe(429)
+ expect(shadow.status).toBe(429)
+ // Align histories by producer-derived state; no hand-authored HTTP fixture.
+ if (await newStateExists())
+ await holder.pool.query(
+ 'UPDATE password_identifier_state SET attempts = (SELECT attempts FROM password_identifier_state WHERE user_id = $1), failures = (SELECT failures FROM password_identifier_state WHERE user_id = $1), locked_until_ms = (SELECT locked_until_ms FROM password_identifier_state WHERE user_id = $1)',
+ [userId]
+ )
+ const a = await login('[email protected]', 'wrong', '192.0.2.82')
+ const b = await login('[email protected]', 'wrong', '192.0.2.83')
+ expect(a.body).toEqual(b.body)
+ for (const name of [
+ 'retry-after',
+ 'x-ratelimit-limit',
+ 'x-ratelimit-remaining',
+ 'x-ratelimit-reset',
+ ])
+ expect(a.headers[name]).toEqual(b.headers[name])
+ })
+ it('does not extend an identifier denial on repeated denied requests', async () => {
+ for (let i = 0; i < 5; i++) {
+ await openPace()
+ await login('[email protected]', 'wrong', `192.0.2.${i + 1}`)
+ }
+ const before = await login('[email protected]', 'wrong', '192.0.2.90')
+ const later = await login('[email protected]', 'wrong', '192.0.2.91')
+ expect(before.status).toBe(429)
+ expect(later.status).toBe(429)
+ expect(Number(later.headers['retry-after'])).toBeLessThanOrEqual(
+ Number(before.headers['retry-after'])
+ )
+ if (await newStateExists()) {
+ const row = (
+ await holder.pool.query(
+ 'SELECT attempts, failures, locked_until_ms FROM password_identifier_state'
+ )
+ ).rows[0]
+ expect(row.attempts).toHaveLength(5)
+ expect(row.failures).toHaveLength(5)
+ }
+ })
+ it('shares public failure cooldown with authenticated reverification', async () => {
+ for (let i = 0; i < 5; i++) {
+ await openPace()
+ await verifyUserPassword({ userId, email: '[email protected]', password: 'wrong' })
+ }
+ const before = compare.mock.calls.length
+ const response = await login('[email protected]', 'wrong')
+ expect(response.status).toBe(429)
+ expect(compare.mock.calls.length).toBe(before)
+ })
+ it('gates a correct canonical password behind the same aggregate authority', async () => {
+ await login('[email protected]')
+ const response = await login('[email protected]', password, '192.0.2.2')
+ expect(response.status).toBe(429)
+ await openPace()
+ const success = await login('[email protected]', password, '192.0.2.3')
+ expect(success.status).toBe(200)
+ expect(verifyExternalSessionToken(success.body.token)).toMatchObject({
+ userId,
+ email: '[email protected]',
+ authGeneration: 1,
+ })
+ expect(success.body.me).toMatchObject({ id: userId, role: 'member', teamId: null })
+ })
+ it('fails closed before bcrypt when credential persistence is unavailable', async () => {
+ // Real database producer: temporarily revoke table access by making its
+ // relation unavailable, then restore it even when the assertion fails.
+ const exists = await newStateExists()
+ if (exists)
+ await holder.pool.query(
+ 'ALTER TABLE password_identifier_state RENAME TO password_identifier_state_unavailable'
+ )
+ try {
+ const a = await login('[email protected]')
+ const b = await login('[email protected]', 'wrong', '192.0.2.2')
+ expect(a.status).toBe(503)
+ expect(b.status).toBe(503)
+ expect(a.body).toEqual(b.body)
+ expect(compare).not.toHaveBeenCalled()
+ } finally {
+ if (exists)
+ await holder.pool.query(
+ 'ALTER TABLE password_identifier_state_unavailable RENAME TO password_identifier_state'
+ )
+ }
+ })
+ // Preservation coverage relocated from the old mocked bcrypt orchestration
+ // suite. These cases are not BUG regression/T3 claims.
+ it('preserves an existing membership without healing unrelated accepted invitations', async () => {
+ const team = (
+ await holder.pool.query("INSERT INTO teams(name) VALUES ('Existing') RETURNING id")
+ ).rows[0]
+ const other = (
+ await holder.pool.query("INSERT INTO teams(name) VALUES ('Unrelated') RETURNING id")
+ ).rows[0]
+ await holder.pool.query(
+ "INSERT INTO team_members(team_id,user_id,role,status) VALUES ($1,$2,'member','active')",
+ [team.id, userId]
+ )
+ await holder.pool.query(
+ "INSERT INTO invitations(team_id,email,role,status,accepted_user_id,accepted_at) VALUES ($1,'[email protected]','admin','accepted',$2,NOW())",
+ [other.id, userId]
+ )
+ const response = await login('[email protected]', password)
+ expect(response.status).toBe(200)
+ expect(response.body.me.teamId).toBe(team.id)
+ expect(
+ (
+ await holder.pool.query('SELECT team_id FROM team_members WHERE user_id=$1', [userId])
+ ).rows.map(row => row.team_id)
+ ).toEqual([team.id])
+ })
+ it('preserves accepted-invitation membership healing for an authenticated teamless member', async () => {
+ const team = (
+ await holder.pool.query("INSERT INTO teams(name) VALUES ('Accepted') RETURNING id")
+ ).rows[0]
+ await holder.pool.query(
+ "INSERT INTO invitations(team_id,email,role,status,accepted_at) VALUES ($1,'[email protected]','member','accepted',NOW())",
+ [team.id]
+ )
+ const response = await login('[email protected]', password)
+ expect(response.status).toBe(200)
+ expect(response.body.me.teamId).toBe(team.id)
+ expect(
+ (await holder.pool.query('SELECT user_id FROM team_members WHERE team_id=$1', [team.id]))
+ .rows[0].user_id
+ ).toBe(userId)
+ })
+ it('preserves the complete public error and trusted-source contract through both real services', async () => {
+ process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = createPublicKey(
+ process.env.CONTROL_API_SESSION_JWT_PRIVATE_KEY!
+ )
+ .export({ type: 'spki', format: 'pem' })
+ .toString()
+ const { createAuthRouter } = await import('../../external-rest-api/src/routes/auth.js')
+ const { config: externalConfig } = await import('../../external-rest-api/src/config.js')
+ const { withExternalRequestContext } =
+ await import('../../external-rest-api/src/requestContext.js')
+ const server = app.listen(0, '127.0.0.1')
+ await new Promise<void>(resolve => server.once('listening', resolve))
+ const address = server.address() as { port: number }
+ const previous = externalConfig.controlApiBaseUrl
+ externalConfig.controlApiBaseUrl = `http://127.0.0.1:${address.port}`
+ const edge = express()
+ edge.set('trust proxy', 1)
+ edge.use(express.json())
+ edge.use(withExternalRequestContext)
+ edge.use('/api/v1', createAuthRouter())
+ try {
+ await holder.pool.query("INSERT INTO users(email) VALUES ('[email protected]')")
+ for (const email of [
+ ]) {
+ await openPace()
+ const response = await request(edge)
+ .post('/api/v1/auth/password-login')
+ .set('X-Forwarded-For', '192.0.2.123')
+ .send({ email, password: 'wrong' })
+ expect({ status: response.status, body: response.body }).toEqual({
+ status: 401,
+ body: { error: 'invalid_credentials' },
+ })
+ }
+ const limited = await request(edge)
+ .post('/api/v1/auth/password-login')
+ .set('X-Forwarded-For', '192.0.2.124')
+ .send({ email: '[email protected]', password: 'wrong' })
+ expect(limited.status).toBe(429)
+ expect(limited.body.error).toBe('rate_limited')
+ expect(limited.body.retryAfterSeconds).toBe(Number(limited.headers['retry-after']))
+ expect(limited.headers['x-ratelimit-reset']).toBeUndefined()
+ const keys = (await holder.pool.query('SELECT bucket_key FROM rate_limit_buckets')).rows.map(
+ row => row.bucket_key
+ )
+ expect(keys).toContain('external_authentication_attempt:ip:192.0.2.123')
+ } finally {
+ externalConfig.controlApiBaseUrl = previous
+ await new Promise<void>((resolve, reject) =>
+ server.close(error => (error ? reject(error) : resolve()))
+ )
+ }
+ })
+})
diff --git a/control-api/test/bug192.passwordPersistence.realPostgres.integration.test.ts b/control-api/test/bug192.passwordPersistence.realPostgres.integration.test.ts
new file mode 100644
index 000000000..d1705f8c8
--- /dev/null
+++ b/control-api/test/bug192.passwordPersistence.realPostgres.integration.test.ts
@@ -0,0 +1,360 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import bcrypt from 'bcryptjs'
+import { spawn } from 'node:child_process'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import { initDb } from '../src/db.js'
+import { applyPasswordAdmissionSchema } from '../src/services/auth/passwordAdmissionSchema.js'
+import {
+ passwordIdentifierKey,
+ PASSWORD_ADMISSION_POLICY as policy,
+} from '../src/services/auth/passwordAdmissionState.js'
+import {
+ capturePasswordEvaluation,
+ cleanupPasswordIdentifierState,
+ completePasswordEvaluation,
+ reservePasswordPace,
+ verifyMemberPassword,
+} from '../src/services/auth/passwordCredentialVerification.js'
+import {
+ setInvitationPasswordForEmail,
+ updateUserPassword,
+} from '../src/services/directory/membership.js'
+import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
+
+const holder = vi.hoisted(() => ({
+ pool: null as unknown as Pool,
+ leaseClient: null as unknown as import('pg').PoolClient,
+}))
+vi.mock('../src/db.js', async importOriginal => {
+ const real = await importOriginal<typeof import('../src/db.js')>()
+ const proxy = {
+ query: (...args: unknown[]) => (holder.pool.query as Function)(...args),
+ connect: () => holder.pool.connect(),
+ }
+ return {
+ ...real,
+ pool: proxy,
+ rateLimitPool: proxy,
+ withTransaction: (fn: Parameters<typeof real.withTransaction>[0]) =>
+ real.withTransaction(fn, holder.pool),
+ }
+})
+vi.mock('../src/services/rateLimiterService.js', async importOriginal => {
+ const real = await importOriginal<typeof import('../src/services/rateLimiterService.js')>()
+ return {
+ ...real,
+ acquireRateLimitConcurrencyLease: (
+ r: Parameters<typeof real.acquireRateLimitConcurrencyLease>[0]
+ ) => real.acquireRateLimitConcurrencyLease(r, { client: holder.leaseClient }),
+ }
+})
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const realPg = adminUrl ? describe : describe.skip
+realPg('Spec 043 persistence, migration, atomicity and fencing design acceptance', () => {
+ const database = `bug192_design_${randomBytes(6).toString('hex')}`
+ const email = '[email protected]',
+ password = 'Synthetic-BUG192-correct-password'
+ let admin: Pool, userId: string, hash: string, connectionString: string
+ beforeAll(async () => {
+ admin = new Pool({ connectionString: adminUrl })
+ await admin.query(`CREATE DATABASE "${database}"`)
+ const url = new URL(adminUrl!)
+ url.pathname = `/${database}`
+ connectionString = url.toString()
+ holder.pool = new Pool({ connectionString })
+ await initDb(holder.pool)
+ holder.leaseClient = await holder.pool.connect()
+ hash = await bcrypt.hash(password, 12)
+ }, 60_000)
+ beforeEach(async () => {
+ vi.restoreAllMocks()
+ await holder.pool.query('DELETE FROM users')
+ await holder.pool.query('DELETE FROM password_identifier_state')
+ await holder.pool.query('DELETE FROM password_verification_pace')
+ userId = (
+ await holder.pool.query(
+ 'INSERT INTO users(email,password_hash) VALUES ($1,$2) RETURNING id',
+ [email, hash]
+ )
+ ).rows[0].id
+ })
+ afterAll(async () => {
+ try {
+ vi.restoreAllMocks()
+ holder.leaseClient?.release()
+ await endPoolAndWaitForClients(holder.pool)
+ if (admin) await admin.query(`DROP DATABASE IF EXISTS "${database}"`)
+ } finally {
+ await admin?.end()
+ }
+ })
+ async function now() {
+ return Number(
+ (
+ await holder.pool.query(
+ 'SELECT floor(extract(epoch FROM clock_timestamp())*1000)::text AS ms'
+ )
+ ).rows[0].ms
+ )
+ }
+ async function row() {
+ return (
+ await holder.pool.query('SELECT * FROM password_identifier_state WHERE identifier_key=$1', [
+ passwordIdentifierKey(email),
+ ])
+ ).rows[0]
+ }
+ async function completedFailures(n = 5) {
+ for (let i = 0; i < n; i++) {
+ const c = await capturePasswordEvaluation(email, false)
+ expect(await completePasswordEvaluation(c, false)).toBe(true)
+ }
+ }
+
+ it('forward migration is idempotent and grants runtime access', async () => {
+ await applyPasswordAdmissionSchema(holder.pool)
+ const permissions = (
+ await holder.pool.query(
+ "SELECT has_table_privilege('control_api_runtime','password_identifier_state','SELECT,INSERT,UPDATE,DELETE') AS state, has_table_privilege('control_api_runtime','password_verification_pace','SELECT,INSERT,UPDATE,DELETE') AS pace"
+ )
+ ).rows[0]
+ expect(permissions).toEqual({ state: true, pace: true })
+ const migrations = (
+ await holder.pool.query(
+ "SELECT version FROM schema_migrations WHERE version='0125_bug192_password_admission'"
+ )
+ ).rows
+ expect(migrations).toHaveLength(1)
+ })
+ it('serializes competing identifier attempts to exactly five admissions', async () => {
+ const results = await Promise.allSettled(
+ Array.from({ length: 12 }, () => capturePasswordEvaluation(email, true))
+ )
+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(5)
+ expect((await row()).attempts).toHaveLength(5)
+ const before = await row()
+ for (let i = 0; i < 3; i++)
+ await expect(capturePasswordEvaluation(email, true)).rejects.toMatchObject({ status: 429 })
+ expect(await row()).toEqual(before)
+ })
+ it('fifth failure sets one cooldown from DB completion time without extension', async () => {
+ await completedFailures(4)
+ const before = await now()
+ const c = await capturePasswordEvaluation(email, false)
+ await completePasswordEvaluation(c, false)
+ const after = await now()
+ const state = await row()
+ expect(Number(state.locked_until_ms)).toBeGreaterThanOrEqual(before + policy.cooldownMs)
+ expect(Number(state.locked_until_ms)).toBeLessThanOrEqual(after + policy.cooldownMs)
+ for (let i = 0; i < 4; i++)
+ await expect(capturePasswordEvaluation(email, true)).rejects.toMatchObject({ status: 429 })
+ expect(await row()).toEqual(state)
+ })
+ it('active attempt budget and staggered cooldown have real/shadow equivalent retry state', async () => {
+ const shadow = '[email protected]'
+ const t = await now()
+ for (const identity of [email, shadow]) {
+ await capturePasswordEvaluation(identity, false)
+ await holder.pool.query(
+ 'UPDATE password_identifier_state SET attempts=$2,failures=$2,locked_until_ms=$3 WHERE identifier_key=$1',
+ [
+ passwordIdentifierKey(identity),
+ [t - 1000000, t - 850000, t - 800000, t - 750000, t - 700000],
+ t + 200000,
+ ]
+ )
+ }
+ const outcomes = await Promise.all(
+ [email, shadow].map(identity =>
+ capturePasswordEvaluation(identity, true).catch(e => ({
+ status: e.status,
+ retryAfterSeconds: e.retryAfterSeconds,
+ }))
+ )
+ )
+ expect(outcomes[0]).toEqual(outcomes[1])
+ expect(outcomes[0]).toMatchObject({ status: 429 })
+ })
+ it('attempt budget exhaustion ends naturally despite repeated denied requests', async () => {
+ for (let i = 0; i < 5; i++) await capturePasswordEvaluation(email, true)
+ const state = await row()
+ await expect(capturePasswordEvaluation(email, true)).rejects.toMatchObject({ status: 429 })
+ expect(await row()).toEqual(state)
+ const t = await now()
+ await holder.pool.query(
+ 'UPDATE password_identifier_state SET attempts=$2 WHERE identifier_key=$1',
+ [passwordIdentifierKey(email), [t - policy.windowMs - 1]]
+ )
+ await expect(capturePasswordEvaluation(email, true)).resolves.toBeDefined()
+ expect((await row()).attempts).toHaveLength(1)
+ })
+ it('natural cooldown expiry removes stale failures without extending attempts', async () => {
+ await completedFailures()
+ const t = await now()
+ await holder.pool.query(
+ 'UPDATE password_identifier_state SET locked_until_ms=$2,failures=$3 WHERE identifier_key=$1',
+ [passwordIdentifierKey(email), t - 1, [t - policy.windowMs - 1]]
+ )
+ await capturePasswordEvaluation(email, false)
+ expect(await row()).toMatchObject({ locked_until_ms: '0', failures: [] })
+ })
+ it('successful authentication/reverification clears failures but retains public attempt history', async () => {
+ const failed = await capturePasswordEvaluation(email, true)
+ await completePasswordEvaluation(failed, false)
+ expect(
+ await verifyMemberPassword(email, password, { publicLogin: false, userId })
+ ).toMatchObject({ id: userId })
+ const state = await row()
+ expect(state.failures).toEqual([])
+ expect(state.locked_until_ms).toBe('0')
+ expect(state.attempts).toHaveLength(1)
+ })
+ it('successful completion fences an older failure completion on the same credential', async () => {
+ const older = await capturePasswordEvaluation(email, false),
+ successful = await capturePasswordEvaluation(email, false)
+ expect(await completePasswordEvaluation(successful, true)).toBe(true)
+ expect(await completePasswordEvaluation(older, false)).toBe(false)
+ expect((await row()).failures).toEqual([])
+ })
+ it('real password-change producer fences stale failure and success results', async () => {
+ const failure = await capturePasswordEvaluation(email, false),
+ success = await capturePasswordEvaluation(email, false)
+ expect(
+ await updateUserPassword(userId, email, password, 'Synthetic-BUG192-new-password')
+ ).toEqual({ updated: true })
+ expect(await completePasswordEvaluation(failure, false)).toBe(false)
+ expect(await completePasswordEvaluation(success, true)).toBe(false)
+ expect((await row()).failures).toEqual([])
+ })
+ it('real reset/establishment producer clears cooldown and fences old work', async () => {
+ const stale = await capturePasswordEvaluation(email, false)
+ await completedFailures()
+ // Database producer for a pending reset; the real reset function owns the
+ // credential write/acceptance and its generation trigger in one transaction.
+ const invitation = (
+ await holder.pool.query(
+ "INSERT INTO invitations(email,role,purpose,status) VALUES ($1,'member','password_reset','pending') RETURNING id",
+ [email]
+ )
+ ).rows[0]
+ const result = await setInvitationPasswordForEmail(
+ email,
+ invitation.id,
+ 'Synthetic-BUG192-reset-password'
+ )
+ expect(result).not.toHaveProperty('error')
+ expect(await completePasswordEvaluation(stale, false)).toBe(false)
+ expect(await row()).toMatchObject({ failures: [], locked_until_ms: '0' })
+ const credential = (
+ await holder.pool.query('SELECT password_hash FROM users WHERE id=$1', [userId])
+ ).rows[0]
+ expect(bcrypt.getRounds(credential.password_hash)).toBe(12)
+ })
+ it('provisioning and lifecycle changes fence stale completions at the database boundary', async () => {
+ for (const update of ['password_hash = NULL', 'lifecycle_version = lifecycle_version + 1']) {
+ const stale = await capturePasswordEvaluation(email, false)
+ await holder.pool.query(`UPDATE users SET ${update} WHERE id=$1`, [userId])
+ expect(await completePasswordEvaluation(stale, false)).toBe(false)
+ }
+ })
+ it('new identity creation fences an old shadow evaluation', async () => {
+ const stale = await capturePasswordEvaluation('[email protected]', false)
+ await holder.pool.query(
+ "INSERT INTO users(email,password_hash) VALUES ('[email protected]',$1)",
+ [hash]
+ )
+ expect(await completePasswordEvaluation(stale, false)).toBe(false)
+ })
+ it('two aggregate reservations cannot both win, and denials do not advance pace', async () => {
+ const results = await Promise.allSettled([reservePasswordPace(), reservePasswordPace()])
+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1)
+ const before = (await holder.pool.query('SELECT * FROM password_verification_pace')).rows
+ await expect(reservePasswordPace()).rejects.toMatchObject({ status: 429 })
+ expect((await holder.pool.query('SELECT * FROM password_verification_pace')).rows).toEqual(
+ before
+ )
+ await holder.pool.query(
+ "UPDATE password_verification_pace SET next_permit=clock_timestamp()-interval '1 minute'"
+ )
+ await reservePasswordPace()
+ await expect(reservePasswordPace()).rejects.toMatchObject({ status: 429 })
+ })
+ it('persisted aggregate pacing works across independent Node processes', async () => {
+ const script = `const {reservePasswordPace}=require('./dist/services/auth/passwordCredentialVerification.js');reservePasswordPace().then(()=>{console.log('ALLOWED');process.exit(0)},e=>{console.log('DENIED:'+e.status);process.exit(e.status===429?0:1)})`
+ const run = () =>
+ new Promise<string>((resolve, reject) => {
+ const child = spawn(process.execPath, ['-e', script], {
+ cwd: process.cwd(),
+ env: { ...process.env, CONTROL_API_PG_CONNECTION_STRING: connectionString },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let out = '',
+ err = ''
+ child.stdout.on('data', c => (out += c))
+ child.stderr.on('data', c => (err += c))
+ const timeout = setTimeout(() => {
+ child.kill('SIGTERM')
+ reject(new Error('bounded child timed out'))
+ }, 10000)
+ child.once('exit', code => {
+ clearTimeout(timeout)
+ if (code !== 0) reject(new Error('child failed: ' + err))
+ else resolve(out.trim())
+ })
+ })
+ const results = await Promise.all([run(), run()])
+ expect(results.sort()).toEqual(['ALLOWED', 'DENIED:429'])
+ })
+ it('busy bcrypt is rejected without queue and the reserved pace is not refunded', async () => {
+ let started!: () => void, finish!: (value: boolean) => void
+ const entered = new Promise<void>(r => (started = r)),
+ held = new Promise<boolean>(r => (finish = r))
+ const spy = vi.spyOn(bcrypt, 'compare').mockImplementationOnce(async () => {
+ started()
+ return held
+ })
+ const first = verifyMemberPassword(email, 'wrong', { publicLogin: false, userId })
+ await entered
+ try {
+ await holder.pool.query(
+ "UPDATE password_verification_pace SET next_permit=clock_timestamp()-interval '1 second'"
+ )
+ await expect(
+ verifyMemberPassword('[email protected]', 'wrong', { publicLogin: true })
+ ).rejects.toMatchObject({ status: 429 })
+ expect(spy).toHaveBeenCalledTimes(1)
+ await expect(reservePasswordPace()).rejects.toMatchObject({ status: 429 })
+ } finally {
+ finish(false)
+ await first
+ }
+ })
+ it('cleanup retains each active component and preserves stale-result fencing after recreation', async () => {
+ const t = await now()
+ for (const kind of ['attempt', 'failure', 'cooldown']) {
+ const identity = `${kind}@example.invalid`
+ await capturePasswordEvaluation(identity, false)
+ await holder.pool.query(
+ 'UPDATE password_identifier_state SET attempts=$2,failures=$3,locked_until_ms=$4 WHERE identifier_key=$1',
+ [
+ passwordIdentifierKey(identity),
+ kind === 'attempt' ? [t] : [],
+ kind === 'failure' ? [t] : [],
+ kind === 'cooldown' ? t + policy.cooldownMs : 0,
+ ]
+ )
+ }
+ const old = await capturePasswordEvaluation('[email protected]', false)
+ expect(await cleanupPasswordIdentifierState()).toBe(1)
+ expect((await holder.pool.query('SELECT * FROM password_identifier_state')).rows).toHaveLength(
+ 3
+ )
+ await capturePasswordEvaluation('[email protected]', false)
+ expect(await completePasswordEvaluation(old, false)).toBe(false)
+ expect(
+ (await holder.pool.query('SELECT password_auth_generation FROM users WHERE id=$1', [userId]))
+ .rows[0]
+ ).toHaveProperty('password_auth_generation')
+ })
+})
diff --git a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
index e41744ffd..28b3effcf 100644
--- a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
+++ b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
@@ -320,7 +320,7 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
})
await expect(
passwordLoginData({ email: inviter.email, password: 'example-password' })
- ).resolves.toEqual({ error: 'user_retired' })
+ ).resolves.toBeNull()
const desktop = await testPool.query(
`SELECT lifecycle_state, lifecycle_version, retirement_reason,
diff --git a/control-api/test/services.directory.login.passwordBackstop.test.ts b/control-api/test/services.directory.login.passwordBackstop.test.ts
index dceb867b1..a0ead5a62 100644
--- a/control-api/test/services.directory.login.passwordBackstop.test.ts
+++ b/control-api/test/services.directory.login.passwordBackstop.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { googleLoginData, passwordLoginData } from '../src/services/directory/login.js'
+import { googleLoginData } from '../src/services/directory/login.js'
const bcryptMock = vi.hoisted(() => ({ compare: vi.fn(), hash: vi.fn(async () => 'h') }))
vi.mock('bcryptjs', () => ({ default: bcryptMock }))
@@ -14,121 +14,15 @@ vi.mock('../src/config.js', () => ({
config: { adminDefaultAgentNames: ['chatllm'], adminDefaultContextIds: ['context1'] },
}))
-describe('directory login without team memberships', () => {
+// Password orchestration now runs against the real credential producer in
+// bug192.passwordLogin.realPostgres.integration.test.ts. Google stays isolated here.
+describe('directory Google login without team memberships', () => {
beforeEach(() => {
dbMocks.txQuery.mockReset()
bcryptMock.compare.mockClear()
bcryptMock.compare.mockResolvedValue(true)
})
- it('returns a teamless member session instead of creating a default team for password login', async () => {
- dbMocks.txQuery
- .mockResolvedValueOnce({
- rows: [
- {
- id: 'u1',
- email: '[email protected]',
- name: 'Ada',
- picture: null,
- password_hash: 'hash',
- lifecycle_state: 'active',
- lifecycle_version: 1,
- },
- ],
- rowCount: 1,
- }) // SELECT user by email
- .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // findFirstActiveMembership → none
- .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // accepted invitation memberships
- .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // UPDATE accepted invitations
- .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // findFirstActiveMembership after heal → none
-
- const result = await passwordLoginData({ email: '[email protected]', password: 'x' })
-
- expect(result).toMatchObject({
- membership: { team_id: null, role: 'member', team_name: null },
- })
- expect(dbMocks.txQuery).not.toHaveBeenCalledWith(
- expect.stringContaining('INSERT INTO teams'),
- expect.anything()
- )
- expect(dbMocks.txQuery).toHaveBeenCalledWith(
- expect.stringContaining("WHERE team_members.status <> 'deleted'"),
- ['u1', '[email protected]']
- )
- })
-
- it('skips accepted invitation healing when password login already has a membership', async () => {
- dbMocks.txQuery
- .mockResolvedValueOnce({
- rows: [
- {
- id: 'u1',
- email: '[email protected]',
- name: 'Ada',
- picture: null,
- password_hash: 'hash',
- lifecycle_state: 'active',
- lifecycle_version: 1,
- },
- ],
- rowCount: 1,
- }) // SELECT user by email
- .mockResolvedValueOnce({
- rows: [{ team_id: 't1', role: 'member', team_name: 'Team 1' }],
- rowCount: 1,
- }) // findFirstActiveMembership
-
- const result = await passwordLoginData({ email: '[email protected]', password: 'x' })
-
- expect(result).toMatchObject({
- membership: { team_id: 't1', role: 'member', team_name: 'Team 1' },
- })
- expect(dbMocks.txQuery).not.toHaveBeenCalledWith(
- expect.stringContaining('INSERT INTO team_members'),
- expect.anything()
- )
- expect(dbMocks.txQuery).not.toHaveBeenCalledWith(
- expect.stringContaining('UPDATE invitations'),
- expect.anything()
- )
- })
-
- it('heals accepted invitations when password login has no active membership', async () => {
- dbMocks.txQuery
- .mockResolvedValueOnce({
- rows: [
- {
- id: 'u1',
- email: '[email protected]',
- name: 'Ada',
- picture: null,
- password_hash: 'hash',
- lifecycle_state: 'active',
- lifecycle_version: 1,
- },
- ],
- rowCount: 1,
- }) // SELECT user by email
- .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // findFirstActiveMembership → none
- .mockResolvedValueOnce({ rows: [], rowCount: 1 }) // accepted invitation memberships
- .mockResolvedValueOnce({ rows: [], rowCount: 1 }) // UPDATE accepted invitations
- .mockResolvedValueOnce({
- rows: [{ team_id: 't1', role: 'member', team_name: 'Team 1' }],
- rowCount: 1,
- }) // findFirstActiveMembership
-
- const result = await passwordLoginData({ email: '[email protected]', password: 'x' })
-
- expect(result).toMatchObject({
- membership: { team_id: 't1', role: 'member', team_name: 'Team 1' },
- })
- expect(dbMocks.txQuery.mock.calls[1][0]).toContain('WHERE tm.user_id = $1')
- expect(dbMocks.txQuery.mock.calls[2][0]).toContain('INSERT INTO team_members')
- expect(dbMocks.txQuery.mock.calls[2][0]).toContain("WHERE team_members.status <> 'deleted'")
- expect(dbMocks.txQuery.mock.calls[3][0]).toContain('UPDATE invitations')
- expect(dbMocks.txQuery.mock.calls[4][0]).toContain('WHERE tm.user_id = $1')
- })
-
it('returns a teamless member session instead of creating a default team for Google login', async () => {
dbMocks.txQuery
.mockResolvedValueOnce({
@@ -169,67 +63,6 @@ describe('directory login without team memberships', () => {
)
})
- it('does NOT self-heal (no team created) when the password is wrong', async () => {
- bcryptMock.compare.mockResolvedValue(false)
- dbMocks.txQuery.mockResolvedValueOnce({
- rows: [
- {
- id: 'u1',
- email: '[email protected]',
- name: 'Ada',
- picture: null,
- password_hash: 'hash',
- lifecycle_state: 'active',
- lifecycle_version: 1,
- },
- ],
- rowCount: 1,
- }) // SELECT user
-
- const result = await passwordLoginData({ email: '[email protected]', password: 'wrong' })
-
- expect(result).toBeNull()
- expect(dbMocks.txQuery).not.toHaveBeenCalledWith(
- expect.stringContaining('INSERT INTO teams'),
- expect.anything()
- )
- })
-
- it('does NOT self-heal when the email is unknown', async () => {
- dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // SELECT user → none
-
- const result = await passwordLoginData({ email: '[email protected]', password: 'x' })
-
- expect(result).toBeNull()
- expect(dbMocks.txQuery).not.toHaveBeenCalledWith(
- expect.stringContaining('INSERT INTO teams'),
- expect.anything()
- )
- })
-
- it('denies password login for a retired user before bcrypt or membership healing', async () => {
- dbMocks.txQuery.mockResolvedValueOnce({
- rows: [
- {
- id: 'u-retired',
- email: '[email protected]',
- name: 'Retired',
- picture: null,
- password_hash: 'hash',
- lifecycle_state: 'retired',
- lifecycle_version: 2,
- },
- ],
- rowCount: 1,
- })
-
- await expect(passwordLoginData({ email: '[email protected]', password: 'x' })).resolves.toEqual({
- error: 'user_retired',
- })
- expect(bcryptMock.compare).not.toHaveBeenCalled()
- expect(dbMocks.txQuery).toHaveBeenCalledTimes(1)
- })
-
it('denies Google login for a retired user before profile healing or identity update', async () => {
dbMocks.txQuery.mockResolvedValueOnce({
rows: [
diff --git a/control-api/test/services.rateLimiter.test.ts b/control-api/test/services.rateLimiter.test.ts
index 522a9c6d4..4a6b56bb7 100644
--- a/control-api/test/services.rateLimiter.test.ts
+++ b/control-api/test/services.rateLimiter.test.ts
@@ -70,6 +70,8 @@ const mockRateLimitPoolQuery = vi.fn(async (sql: unknown, params?: unknown[]) =>
// pool only lends the long-lived advisory-lock client. A limiter statement on
// the core pool is a wiring regression, so the core query rejects loudly.
const mockCorePoolQuery = vi.fn(async (sql: unknown) => {
+ if (String(sql).includes('DELETE FROM password_identifier_state'))
+ return { rows: [], rowCount: 0 }
throw new Error(`core pool must not serve the rate limiter: ${String(sql).slice(0, 40)}`)
})
@@ -94,7 +96,7 @@ describe('rateLimiterService', () => {
mockClientQuery.mockClear()
})
- it('serves the upsert and the prune from the limiter pool, never the core pool', async () => {
+ it('keeps legacy upserts/prune on the limiter pool and credential cleanup on the core pool', async () => {
const r = await checkAndIncrement('test:bucket:pool-wiring', 5)
await cleanupExpiredBuckets(1_700_000_000_000)
@@ -103,7 +105,9 @@ describe('rateLimiterService', () => {
expect(
mockRateLimitPoolQuery.mock.calls.map(([sql]) => String(sql).trim().split(/\s+/)[0])
).toEqual(['INSERT', 'DELETE'])
- expect(mockCorePoolQuery).not.toHaveBeenCalled()
+ expect(mockCorePoolQuery).toHaveBeenCalledExactlyOnceWith(
+ expect.stringContaining('DELETE FROM password_identifier_state')
+ )
})
it('allows requests up to the limit and denies the (limit+1)-th in the same window', async () => {
@@ -308,4 +312,50 @@ describe('rateLimiterService', () => {
stopRateLimiterCleanup()
stopRateLimiterCleanup() // double stop is safe
})
+ it('releases the idle dedicated session after finite credential work', async () => {
+ mockConcurrencyClient.release.mockClear()
+ const lease = await acquireRateLimitConcurrencyLease(
+ [{ bucketKey: 'finite-password-work', maxConcurrent: 1 }],
+ { releaseIdleClient: true }
+ )
+ expect(lease.allowed).toBe(true)
+ await lease.release()
+ expect(mockConcurrencyClient.release).toHaveBeenCalledExactlyOnceWith(true)
+ })
+ it('releases an idle dedicated session after busy denial', async () => {
+ mockConcurrencyClient.release.mockClear()
+ mockClientQuery.mockResolvedValueOnce({ rows: [{ acquired: false }] } as never)
+ const lease = await acquireRateLimitConcurrencyLease(
+ [{ bucketKey: 'finite-busy-work', maxConcurrent: 1 }],
+ { releaseIdleClient: true }
+ )
+ expect(lease.allowed).toBe(false)
+ expect(lease.backendAvailable).toBe(true)
+ expect(mockConcurrencyClient.release).toHaveBeenCalledExactlyOnceWith(true)
+ })
+ it('releases an idle dedicated session after an admission query failure', async () => {
+ mockConcurrencyClient.release.mockClear()
+ mockClientQuery.mockRejectedValueOnce(new Error('synthetic admission failure'))
+ const lease = await acquireRateLimitConcurrencyLease(
+ [{ bucketKey: 'finite-failed-work', maxConcurrent: 1 }],
+ { releaseIdleClient: true }
+ )
+ expect(lease.allowed).toBe(false)
+ expect(lease.backendAvailable).toBe(false)
+ expect(mockConcurrencyClient.release).toHaveBeenCalledExactlyOnceWith(true)
+ })
+ it('retains the dedicated session when another lease remains active', async () => {
+ const active = await acquireRateLimitConcurrencyLease([
+ { bucketKey: 'retained-active-work', maxConcurrent: 1 },
+ ])
+ mockConcurrencyClient.release.mockClear()
+ mockClientQuery.mockResolvedValueOnce({ rows: [{ acquired: false }] } as never)
+ const denied = await acquireRateLimitConcurrencyLease(
+ [{ bucketKey: 'finite-denied-work', maxConcurrent: 1 }],
+ { releaseIdleClient: true }
+ )
+ expect(denied.allowed).toBe(false)
+ expect(mockConcurrencyClient.release).not.toHaveBeenCalled()
+ await active.release()
+ })
})
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index ec891878c..02ab6e38f 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.96",
+ "version": "0.1.97",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.96",
+ "version": "0.1.97",
"dependencies": {
"@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"cors": "^2.8.5",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 8cc5df649..834823f07 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.96",
+ "version": "0.1.97",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/http/passwordAdmissionError.ts b/external-rest-api/src/http/passwordAdmissionError.ts
new file mode 100644
index 000000000..180cfbdb6
--- /dev/null
+++ b/external-rest-api/src/http/passwordAdmissionError.ts
@@ -0,0 +1,25 @@
+import type { Response } from 'express'
+import { ControlApiError } from '../controlApiClient.js'
+
+/** Only the bounded public authority contract crosses this credential seam. */
+export function sendPasswordAuthorityError(error: unknown, res: Response): boolean {
+ if (!(error instanceof ControlApiError) || ![429, 503].includes(error.status)) return false
+ const retry = Number(error.headers['retry-after'])
+ const retryAfterSeconds =
+ Number.isFinite(retry) && retry > 0 ? Math.min(900, Math.max(1, Math.ceil(retry))) : 2
+ for (const name of [
+ 'X-RateLimit-Limit',
+ 'X-RateLimit-Remaining',
+ 'X-RateLimit-Reset',
+ 'RateLimit',
+ 'RateLimit-Policy',
+ ])
+ res.removeHeader(name)
+ res.setHeader('Retry-After', String(retryAfterSeconds))
+ res.setHeader('Cache-Control', 'no-store')
+ res.status(error.status).json({
+ error: error.status === 429 ? 'rate_limited' : 'authority_unavailable',
+ retryAfterSeconds,
+ })
+ return true
+}
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 04c3e275d..f84b7ddf1 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -8,7 +8,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.10.0',
- externalRestApiVersion: '0.1.96',
+ externalRestApiVersion: '0.1.97',
rpcProxyVersion: '0.1.119',
desktopVersion: '0.10.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/src/routes/auth.ts b/external-rest-api/src/routes/auth.ts
index 882ef9b52..24afa74c3 100644
--- a/external-rest-api/src/routes/auth.ts
+++ b/external-rest-api/src/routes/auth.ts
@@ -2,6 +2,7 @@ import { Request, Response, Router } from 'express'
import { OAuth2Client } from 'google-auth-library'
import { config } from '../config.js'
import { ControlApiError } from '../controlApiClient.js'
+import { sendPasswordAuthorityError } from '../http/passwordAdmissionError.js'
import { createRateLimiter } from '../middleware/rateLimit.js'
import {
loginWithGoogle,
@@ -101,31 +102,20 @@ export function createAuthRouter(): Router {
router.post('/auth/password-login', async (req, res, next) => {
try {
- const email = String(req.body?.email || '')
- .trim()
- .toLowerCase()
- const password = String(req.body?.password || '')
- if (!email || !password) {
- res.status(400).json({ error: 'email and password are required' })
+ const email = typeof req.body?.email === 'string' ? req.body.email.trim().toLowerCase() : ''
+ const password = typeof req.body?.password === 'string' ? req.body.password : ''
+ if (!email || !password || email.length > 320 || password.length > 256) {
+ res.status(400).json({ error: 'invalid_request' })
return
}
-
const result = await loginWithPassword(email, password)
sendLoginResponse(req, res, result)
} catch (error) {
- const message = error instanceof Error ? error.message : ''
- if (message.includes('(409)')) {
- res.status(409).json({ error: 'password_not_set' })
- return
- }
- if (message.includes('(401)')) {
- res.status(401).json({ error: 'Unauthorized' })
- return
- }
- if (message.includes('(403)')) {
- res.status(403).json({ error: 'Membership not found' })
+ if (error instanceof ControlApiError && [401, 403, 409].includes(error.status)) {
+ res.status(401).json({ error: 'invalid_credentials' })
return
}
+ if (sendPasswordAuthorityError(error, res)) return
next(error)
}
})
diff --git a/external-rest-api/src/routes/invitations.ts b/external-rest-api/src/routes/invitations.ts
index fcd11fda9..825769ed1 100644
--- a/external-rest-api/src/routes/invitations.ts
+++ b/external-rest-api/src/routes/invitations.ts
@@ -1,5 +1,6 @@
import { NextFunction, Request, Response, Router } from 'express'
import { verifyToken } from '../authToken.js'
+import { sendPasswordAuthorityError } from '../http/passwordAdmissionError.js'
import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware/auth.js'
import { createRateLimiter } from '../middleware/rateLimit.js'
import {
@@ -193,6 +194,7 @@ export function createInvitationsRouter(): Router {
}
res.status(200).json(result.data)
} catch (error) {
+ if (sendPasswordAuthorityError(error, res)) return
next(error)
}
}
diff --git a/external-rest-api/src/services/invitationsService.ts b/external-rest-api/src/services/invitationsService.ts
index 8572f1af7..0d1228914 100644
--- a/external-rest-api/src/services/invitationsService.ts
+++ b/external-rest-api/src/services/invitationsService.ts
@@ -1,4 +1,4 @@
-import { controlApiRequest } from '../controlApiClient.js'
+import { ControlApiError, controlApiRequest } from '../controlApiClient.js'
type AuthContext = {
userId: string
@@ -100,6 +100,7 @@ export async function createDesktopAuthorization(
})
return { data }
} catch (error) {
+ if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error
const message = error instanceof Error ? error.message : ''
if (message.includes('(404)')) return { error: 'not_found' }
return { error: 'invalid_password' }
diff --git a/external-rest-api/test/routes.auth.test.ts b/external-rest-api/test/routes.auth.test.ts
index 04b1849d1..d32f780c9 100644
--- a/external-rest-api/test/routes.auth.test.ts
+++ b/external-rest-api/test/routes.auth.test.ts
@@ -43,7 +43,7 @@ describe('routes/auth password-login', () => {
.send({ email: '[email protected]', password: 'wrong-password' })
expect(res.status).toBe(401)
- expect(res.body).toEqual({ error: 'Unauthorized' })
+ expect(res.body).toEqual({ error: 'invalid_credentials' })
})
it('sets an HttpOnly profile session cookie and omits bearer token body for browser login', async () => {