Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
24 changes: 24 additions & 0 deletions .changeset/25824-admin-create-user-password-length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@objectstack/plugin-auth': patch
---

fix(plugin-auth)!: admin create-user refuses a password outside the deployment's length range, as set-user-password does

`POST /api/v1/auth/admin/create-user` saved an explicit password of any length up to the maximum: better-auth's own `createUser` checks only `maxPasswordLength`, never `minPasswordLength`. An administrator could create a user with a 1-character password and `mustChangePassword: false`, and the user signed in with it, while `POST /api/v1/auth/admin/set-user-password` and the user's own change-password refuse the same value. Both admin doors now resolve a password through one check of the deployment's `minPasswordLength` / `maxPasswordLength` (the `auth.password_min_length` / `password_max_length` settings, ADR-0069):

- **An explicit password outside the range** is refused with `400 INVALID_REQUEST`, "Password must be at least N characters" (or "at most N"), the answer set-user-password already gave. No new error code. The refusal comes before anything is written: no account, no membership, no permission-set grant, no audit row.
- **A generated password** (`generatePassword: true` with no password typed) is 16 characters, raised to the minimum when the minimum is above 16 and capped at the maximum when the maximum is below 16. Before, it was always 16, so on a deployment with a minimum above 16, set-user-password refused the password it had just generated, and create-user saved it below the minimum.

A password inside the range is applied exactly as before.

Clause-②: no (narrowing) — admin create-user refuses one request shape it used to run: an explicit `password` shorter than the deployment's `minPasswordLength` (one longer than `maxPasswordLength` was already refused by better-auth, now with set-user-password's code). Nothing is widened.

Metadata-protocol: none (an admin REST door's handling of a request body; nothing a metadata author writes changes)

<!-- adr-0087: not-required (no-migration-prescription) No metadata moves: no spec key, authorable spelling, object definition, stored row or stored shape is added, removed, renamed or re-shaped, and no exported declaration is removed or narrowed, so there is nothing for `objectstack migrate meta` to rewrite. What changes is how the admin create-user door handles a request body's explicit password: a value outside the deployment's configured length range is refused, as the set-user-password door already refused it. The remedy is a request edit (send a password inside the range, or `generatePassword: true`), never a rewrite of a package source or a stored row. The other categories are closed on facts: the package publishes (not unpublished); no ADR-0087 id is named or touched (not registered or already-registered); and nothing exported is removed or narrowed (not runtime-interface-only, type-surface-only or runtime-export-retired). -->

**BREAKING** for a caller that created users with passwords shorter than the deployment's minimum, or that matched the error code of a too-long one.

- **Before.** `POST /api/v1/auth/admin/create-user` with `password: 'a'` answered `200` and saved the password. A password longer than `maxPasswordLength` answered `400 PASSWORD_TOO_LONG`.
- **Now.** The short one answers `400 INVALID_REQUEST`, "Password must be at least 8 characters" (the deployment's minimum), and creates no user. The too-long one answers `400 INVALID_REQUEST`, "Password must be at most 128 characters" (the deployment's maximum), set-user-password's answer.
- **Fix.** Send a password inside the deployment's `minPasswordLength` / `maxPasswordLength` range, or send `generatePassword: true` and hand the user the returned temporary password. A client that matched `PASSWORD_TOO_LONG` on this door matches `INVALID_REQUEST` instead.
102 changes: 102 additions & 0 deletions packages/plugins/plugin-auth/src/admin-user-endpoints.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,108 @@ describe('Setup dialogs: one password rule (sys_user create_user / set_user_pass
}
});

// ── One length range for every admin door (#25824) ────────────────────────
//
// better-auth's own `createUser` checks only the maximum length, so
// create-user saved a 1-character password (and the user signed in with it)
// while set-user-password and the user's own change-password refuse it. Both
// admin doors now hold the deployment's `minPasswordLength` /
// `maxPasswordLength` in the one place they resolve a password, with the same
// refusal, before anything is written — and a generated password is sized to
// the range instead of falling outside it.
describe('admin doors: one password length range (create-user / set-user-password)', () => {
const DOORS = [
{
door: 'create-user',
explicitKey: 'password',
base: { email: 'x@example.com', name: 's', mustChangePassword: false },
run: (m: ReturnType<typeof makeDeps>, body: Record<string, unknown>) =>
runAdminCreateUser(m.deps, makeRequest(body), ACTOR),
appliedPassword: (m: ReturnType<typeof makeDeps>) =>
callsOf(m.createUser).map((c) => (c[0] as unknown as { body: { password: string } }).body.password),
},
{
door: 'set-user-password',
explicitKey: 'newPassword',
base: { userId: 'user-9', mustChangePassword: false },
run: (m: ReturnType<typeof makeDeps>, body: Record<string, unknown>) =>
runAdminSetUserPassword(m.deps, makeRequest(body), ACTOR),
appliedPassword: (m: ReturnType<typeof makeDeps>) =>
callsOf(m.authCtx.password.hash).map((c) => c[0]),
},
] as const;

for (const d of DOORS) {
for (const [shape, password, message] of [
['a 1-character password (the reported repro)', 'a', 'Password must be at least 8 characters'],
['a password one short of the minimum', 'Abcde1!', 'Password must be at least 8 characters'],
['a password one past the maximum', `Ab1!${'x'.repeat(125)}`, 'Password must be at most 128 characters'],
] as const) {
it(`${d.door}: refuses ${shape} with INVALID_REQUEST, and writes nothing`, async () => {
const m = makeDeps();
const res = await d.run(m, { ...d.base, [d.explicitKey]: password });
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('INVALID_REQUEST');
expect(res.body.error?.message).toBe(message);
expect(m.createUser).not.toHaveBeenCalled();
expect(m.authCtx.password.hash).not.toHaveBeenCalled();
expect(m.authCtx.internalAdapter.updatePassword).not.toHaveBeenCalled();
expect(m.authCtx.internalAdapter.createAccount).not.toHaveBeenCalled();
expect(m.engineUpdate).not.toHaveBeenCalled();
expect(m.engineCreate).not.toHaveBeenCalled();
});
}

for (const [shape, password] of [
['exactly the minimum', 'Abcdef1!'],
['exactly the maximum', `Ab1!${'x'.repeat(124)}`],
] as const) {
it(`${d.door}: applies a password of ${shape}`, async () => {
const m = makeDeps();
const res = await d.run(m, { ...d.base, [d.explicitKey]: password });
expect(res.status).toBe(200);
expect(d.appliedPassword(m)).toEqual([password]);
});
}

it(`${d.door}: reads the deployment's range, not a built-in 8`, async () => {
const m = makeDeps();
m.authCtx.password.config = { minPasswordLength: 12, maxPasswordLength: 128 };
const res = await d.run(m, { ...d.base, [d.explicitKey]: 'Explicit1!' });
expect(res.status).toBe(400);
expect(res.body.error?.message).toBe('Password must be at least 12 characters');
expect(d.appliedPassword(m)).toEqual([]);
});

for (const [shape, config, length] of [
['raised to a minimum above 16', { minPasswordLength: 24, maxPasswordLength: 128 }, 24],
['capped at a maximum below 16', { minPasswordLength: 8, maxPasswordLength: 14 }, 14],
] as const) {
it(`${d.door}: a generated password is sized to the range (${shape})`, async () => {
const m = makeDeps();
m.authCtx.password.config = { ...config };
const res = await d.run(m, { ...d.base, generatePassword: true });
expect(res.status).toBe(200);
const temp = (res.body.data as any).temporaryPassword as string;
expect(temp).toHaveLength(length);
expect(d.appliedPassword(m)).toEqual([temp]);
});
}
}

it('create-user: a range that cannot be read refuses, and no account is created', async () => {
const m = makeDeps({
getAuthContext: vi.fn(async () => {
throw new Error('auth context unavailable');
}),
});
const res = await runAdminCreateUser(m.deps, makeRequest({ email: 'x@example.com', password: 'Explicit1!' }), ACTOR);
expect(res.status).toBe(500);
expect(res.body.error?.code).toBe('INTERNAL_ERROR');
expect(m.createUser).not.toHaveBeenCalled();
});
});

// ── The ledger row records the admin's decisions, never a field value ──────
//
// `sys_audit_log.metadata` is free text. The ledger's read side narrows the
Expand Down
99 changes: 66 additions & 33 deletions packages/plugins/plugin-auth/src/admin-user-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,11 @@ const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] };

// ── Temporary password generation ────────────────────────────────────────
//
// Must satisfy the ADR-0069 class-mix policy (lower + upper + digit + symbol)
// and the better-auth min length regardless of deployment config, so one
// guaranteed character per class + random fill. Ambiguous glyphs (O/0, l/1)
// are excluded — these passwords are read off a dialog and typed once.
// Must satisfy the ADR-0069 class-mix policy (lower + upper + digit + symbol),
// so one guaranteed character per class + random fill. Never shorter than 12;
// a caller holding the deployment's length range sizes it to that range (see
// `temporaryPasswordLength`). Ambiguous glyphs (O/0, l/1) are excluded — these
// passwords are read off a dialog and typed once.
const LOWER = 'abcdefghijkmnopqrstuvwxyz';
const UPPER = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
const DIGIT = '23456789';
Expand Down Expand Up @@ -317,42 +318,71 @@ export function isLikelyEmail(value: string): boolean {
return dot > 0 && dot < domain.length - 1;
}

/**
* [#25824] The deployment's password length range, as better-auth resolved it:
* `emailAndPassword.minPasswordLength` / `maxPasswordLength`, which ADR-0069
* maps the `auth.password_min_length` / `password_max_length` settings onto.
*/
type PasswordLengthPolicy = AuthContextLike['password']['config'];

/** A generated password's length: 16, raised to the range's minimum and capped at its maximum. */
function temporaryPasswordLength({ minPasswordLength, maxPasswordLength }: PasswordLengthPolicy): number {
return Math.min(Math.max(16, minPasswordLength), maxPasswordLength);
}

/**
* Resolve the password for a create/set request: an explicit `password` /
* `newPassword`, or a generated temporary one when `generatePassword` is true.
* An explicit non-empty password always wins over `generatePassword` — the
* console action dialog defaults `generatePassword: true` and labels the
* password input "leave empty to generate", so typing a password is an
* unambiguous override, not a conflict.
*
* [#25824] Every admin door that sets a credential resolves it here, so this
* is where the length range is held, for an explicit and a generated password
* alike: better-auth's own `createUser` checks only the maximum, and
* create-user used to save a 1-character password that set-user-password and
* change-password refuse.
* Returns an EndpointResult on validation failure.
*/
async function resolvePassword(
deps: Pick<AdminUserEndpointDeps, 'assertPasswordComplexity'>,
body: Record<string, unknown>,
explicitKey: 'password' | 'newPassword',
lengthPolicy: PasswordLengthPolicy,
): Promise<{ password: string; generated: boolean } | EndpointResult> {
const explicit = body[explicitKey];
const generate = body.generatePassword === true;
let resolved: { password: string; generated: boolean };
if (typeof explicit !== 'string' || explicit.length === 0) {
if (generate) return { password: generateTemporaryPassword(), generated: true };
return badRequest(`${explicitKey} is required (or set generatePassword: true)`);
}
try {
await deps.assertPasswordComplexity(explicit);
} catch (error) {
const e = error as { code?: string; message?: string } | null;
return {
status: 400,
body: {
success: false,
error: {
code: e?.code ?? 'PASSWORD_POLICY_VIOLATION',
message: e?.message ?? 'Password does not meet the complexity policy',
if (!generate) return badRequest(`${explicitKey} is required (or set generatePassword: true)`);
resolved = { password: generateTemporaryPassword(temporaryPasswordLength(lengthPolicy)), generated: true };
} else {
try {
await deps.assertPasswordComplexity(explicit);
} catch (error) {
const e = error as { code?: string; message?: string } | null;
return {
status: 400,
body: {
success: false,
error: {
code: e?.code ?? 'PASSWORD_POLICY_VIOLATION',
message: e?.message ?? 'Password does not meet the complexity policy',
},
},
},
};
};
}
resolved = { password: explicit, generated: false };
}
const { minPasswordLength, maxPasswordLength } = lengthPolicy;
if (resolved.password.length < minPasswordLength) {
return badRequest(`Password must be at least ${minPasswordLength} characters`);
}
if (resolved.password.length > maxPasswordLength) {
return badRequest(`Password must be at most ${maxPasswordLength} characters`);
}
return { password: explicit, generated: false };
return resolved;
}

/**
Expand Down Expand Up @@ -688,7 +718,14 @@ export async function runAdminCreateUser(
const permissionSet =
typeof rawPermissionSet === 'string' && rawPermissionSet.trim().length > 0 ? rawPermissionSet.trim() : undefined;

const resolved = await resolvePassword(deps, body, 'password');
// [#25824] The length range is judged here, before any account exists.
let lengthPolicy: PasswordLengthPolicy;
try {
lengthPolicy = (await deps.getAuthContext()).password.config;
} catch (error) {
return mapAuthApiError(error, 'create-user failed');
}
const resolved = await resolvePassword(deps, body, 'password', lengthPolicy);
if ('status' in resolved) return resolved;

// ADR-0093 D3 amendment — in multi-org mode the new user joins the
Expand Down Expand Up @@ -1026,20 +1063,16 @@ export async function runAdminSetUserPassword(
// malformed value keeps the safe default.
const revokeSessionsAndKeys = body.revokeSessionsAndKeys !== false;

const resolved = await resolvePassword(deps, body, 'newPassword');
let authCtx: AuthContextLike;
try {
authCtx = await deps.getAuthContext();
} catch (error) {
return mapAuthApiError(error, 'set-user-password failed');
}
const resolved = await resolvePassword(deps, body, 'newPassword', authCtx.password.config);
if ('status' in resolved) return resolved;

try {
const authCtx = await deps.getAuthContext();

const { minPasswordLength, maxPasswordLength } = authCtx.password.config;
if (resolved.password.length < minPasswordLength) {
return badRequest(`Password must be at least ${minPasswordLength} characters`);
}
if (resolved.password.length > maxPasswordLength) {
return badRequest(`Password must be at most ${maxPasswordLength} characters`);
}

if (!(await authCtx.internalAdapter.findUserById(userId))) {
return { status: 404, body: { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'User not found' } } };
}
Expand Down
Loading