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
21 changes: 21 additions & 0 deletions .changeset/credential-change-ends-prior-access.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/plugin-auth': patch
---

fix(plugin-auth)!: a credential change ends access issued before it

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value, metadata type or export is added, removed, renamed or re-shaped, and nothing stored is rewritten: what moves is the answer the auth doors give to an email-change link, a second-factor challenge or a password sign-in that predates the account's last password change, which is now the answer a link, challenge or password that was never valid gets. There is nothing for a migration to rewrite and no tombstone. -->

Once an account's password changes, the following, issued for that account before the change, no longer grant access after it:

- An email-change link (any link the email-change flow begun at `POST /api/v1/auth/change-email` mails, at either of its steps and to either address: the confirmation sent to the current address, and the link sent to the new one) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too.
- A second-factor challenge opened by a password sign-in before the change answers what a challenge that was never opened answers. The person signs in again with the new password.
- A door that ends the account's sessions when it sets the password ends every session opened before its password write: both reset doors, `POST /api/v1/auth/change-password` with `revokeOtherSessions: true` (the session it installs is kept), and the one-step invitation acceptance (ahead of the session it opens).
- A password sign-in during which the account's password changes is refused with what a wrong password answers at that door, and leaves no session.

The moment of the change is the last time the account's local password was written over, so every door that replaces a password counts, an administrator's `POST /api/v1/auth/admin/set-user-password` included. An account's first password is not a change. A check that cannot read the record refuses. Access issued after the change, and an account that never changed its local password, are untouched. No request, response or metadata shape changes.

**BREAKING** for a client that opens an email-change link, completes a second-factor challenge, or finishes a password sign-in after the account's password changed underneath it: each is now refused as above, with the code a never-issued link, a never-opened challenge or a wrong password already answers, so a client that handles those answers needs no change. The fix for a person: request a new email-change link, or sign in again with the new password.
16 changes: 16 additions & 0 deletions content/docs/permissions/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,22 @@ code still outstanding for that user: a completed reset, the user's own
what one that was never issued answers (`400 INVALID_TOKEN` at
`reset-password`); a link or code requested after the change works as usual.

A change to a user's password also ends the following, issued before it. An
email-change link minted before the change answers what a link that was never
issued answers at `GET /api/v1/auth/verify-email` (`401 INVALID_TOKEN`, or the
`error=INVALID_TOKEN` redirect to its callback), and a second-factor challenge
opened by a password sign-in before the change answers what a challenge that
was never opened answers; the person asks again. A door that ends the
account's sessions — a completed reset, `change-password` with
`revokeOtherSessions: true` (the session it installs is kept) and the one-step
invitation acceptance — ends every session opened before its password write,
and a password sign-in during which the password changes is refused with what
a wrong password answers. The change's moment is the last time the account's
local password was written over, so an administrator's `set-user-password`
counts too, and an account's first password is not a change; an email-change
link carries its issue time in whole seconds, so one minted in the same second
as the change is refused as well.

#### Setting a first local password

`POST /api/v1/auth/set-initial-password` sets an **initial** local password for a
Expand Down
77 changes: 77 additions & 0 deletions packages/plugins/plugin-auth/src/auth-manager-after-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ import { BANNED_USER_CODE, causeBannedUserRefusal } from './banned-user-refusal-
import type { AuthManager } from './auth-manager.js';
import { refusalCodeOf } from './auth-session-audit.js';
import { passwordSignInDoorOf } from './auth-manager-sign-in-lockout.js';
import {
endSessionsAfterCredentialWrite,
refuseSignInAcrossCredentialChange,
RESET_DOOR_PATHS,
RESET_DOOR_SUBJECT,
} from './credential-change-ends-prior-access.js';
import { narrowDirectoryForExternalCaller } from './external-directory-door.js';
import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js';
import { refuseIntrospectionForBannedSubject } from './oauth-token-read-ban-refusal.js';
Expand Down Expand Up @@ -165,8 +171,74 @@ async function refusedAfterTheCredential(returned: unknown): Promise<boolean> {
return after.includes(code);
}

/**
* What a wrong password answers at `door`: better-auth's own refusal there
* (1.7.12), its code read off the vendor's own tables — `BASE_ERROR_CODES` for
* the email door, the phone-number plugin's `$ERROR_CODES` for the phone door —
* so no code is minted here.
*/
async function wrongPasswordAt(ctx: any, door: 'email' | 'phone'): Promise<Error> {
const { APIError } = await import('better-auth/api');
const { BASE_ERROR_CODES } = await import('@better-auth/core/error');
const phoneCodes = door === 'phone' ? ctx?.context?.getPlugin?.('phone-number')?.$ERROR_CODES : undefined;
const phoneRefusal = phoneCodes?.INVALID_PHONE_NUMBER_OR_PASSWORD;
return APIError.from('UNAUTHORIZED', phoneRefusal ?? BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);
}

/** Whether the endpoint answered a success (no `APIError` on `returned`). */
async function endpointSucceeded(ctx: any): Promise<boolean> {
try {
const { isAPIError } = await import('better-auth/api');
return !isAPIError(ctx?.context?.returned);
} catch {
return !(ctx?.context?.returned instanceof Error);
}
}

/**
* A door that ends the account's sessions when it sets the password ends them
* again now that the password is written (`credential-change-ends-prior-
* access.ts`): both reset doors, and `/change-password` asked to end the other
* sessions, which keeps the session it installed.
*/
async function endSessionsOnceThePasswordIsWritten(this: Pick<AfterHookHost, 'logDurabilityDegradation'>, ctx: any): Promise<void> {
const resetDoor = RESET_DOOR_PATHS.has(ctx?.path);
const changeDoor = ctx?.path === '/change-password' && ctx?.body?.revokeOtherSessions === true;
if (!resetDoor && !changeDoor) return;
if (!(await endpointSucceeded(ctx))) return;
const internal = ctx?.context?.internalAdapter;
const subject: unknown = resetDoor ? ctx?.context?.[RESET_DOOR_SUBJECT] : actingUserIdOf(ctx);
const installed: unknown = ctx?.context?.returned?.token;
if (typeof subject !== 'string' || !subject || !internal || (changeDoor && (typeof installed !== 'string' || !installed))) {
this.logDurabilityDegradation(
'AuthManager: a password was set by a door that ends the account\'s sessions, but the sessions were NOT '
+ 'ended again once the password was written: the account it set could not be named. The door ended '
+ 'them before the write, as it always has. Remedy: none per request; report it, the next such door '
+ 'ends them again.',
new Error('the account of a session-ending password door could not be named'),
{ object: 'sys_session', path: String(ctx?.path) },
);
return;
}
await endSessionsAfterCredentialWrite(internal, subject, changeDoor ? (installed as string) : undefined);
}

/** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */
export async function globalAfterHook(this: AfterHookHost, ctx: any) {
// ── A credential change ends access issued before it ──────────────
// FIRST: a password sign-in during which the account's password changed
// is refused, its session ended and the response left without one, ahead
// of every after-hook that reads the new session — the second-factor
// plugin's among them, which then opens no challenge. Its refusal is what
// a wrong password answers at that door; the lockout settlement below
// reads it as one, and it is thrown once that settlement has run.
// `credential-change-ends-prior-access.ts` states the rule.
const signInDoor = passwordSignInDoorOf(ctx);
const signInAcrossChange = signInDoor
? await refuseSignInAcrossCredentialChange(ctx, () => wrongPasswordAt(ctx, signInDoor.door))
: undefined;
if (signInAcrossChange) ctx.context.returned = signInAcrossChange;

// ── #8243: impersonation must actually take effect for a bearer ──
// FIRST among the after-hooks that touch the response, because the
// bearer plugin's own after-hook runs behind this one and must see
Expand Down Expand Up @@ -310,12 +382,17 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
// on a match, so it stays after the settlement and the refusal's
// `login_failed` row above. The phone door goes on to the hooks below,
// as before.
if (signInAcrossChange) throw signInAcrossChange;
if (door === 'email') {
await causeBannedUserRefusal(ctx);
return;
}
}

// ── A credential change ends access issued before it ──────────────
// Ahead of the password-change after-effects below, which return.
await endSessionsOnceThePasswordIsWritten.call(this, ctx);

// ── ADR-0069 D1: on a successful change/reset — stamp
// password_changed_at (expiry) and commit password history.
//
Expand Down
40 changes: 39 additions & 1 deletion packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ import { setAuthActorResolver } from './auth-actor-attribution.js';
import { AuthManager } from './auth-manager.js';
import { passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js';
import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js';
import {
endEmailChangeTokenIssuedBeforeCredentialChange,
endTwoFactorChallengeIssuedBeforeCredentialChange,
noteSignInCredential,
RESET_DOOR_SUBJECT,
} from './credential-change-ends-prior-access.js';
import {
isLastLocalCredentialHolder,
LAST_LOCAL_CREDENTIAL_CODE,
Expand Down Expand Up @@ -196,7 +202,12 @@ export async function globalBeforeHook(
this: BeforeHookHost,
ctx: any,
setShouldSkipSessionRefresh: typeof import('better-auth/api').setShouldSkipSessionRefresh,
): Promise<ReturnType<typeof ssoDiscoveryCompanionContext> | Response | void> {
): Promise<
| ReturnType<typeof ssoDiscoveryCompanionContext>
| Awaited<ReturnType<typeof endEmailChangeTokenIssuedBeforeCredentialChange>>
| Response
| void
> {
// ── #4586: hand the attribution scope its actor resolver ─────
// FIRST, and unconditionally: this global before-hook is the one
// seam every better-auth endpoint passes through (`matcher: () =>
Expand Down Expand Up @@ -251,6 +262,15 @@ export async function globalBeforeHook(
// see `auth-manager-sign-in-lockout.ts`.
await recordLockoutRequest.call(this, ctx);

// ── A credential change ends access issued before it ──────────
// An email-change link minted before the account's last credential
// change answers what a link never issued answers, and a second-factor
// challenge opened before it is ended. `credential-change-ends-prior-
// access.ts` states the rule and its one predicate.
const endedEmailChange = await endEmailChangeTokenIssuedBeforeCredentialChange(ctx);
if (endedEmailChange) return endedEmailChange;
await endTwoFactorChallengeIssuedBeforeCredentialChange(ctx);

// ── [#33203] Cloud-managed: no reset door sets a local password ──
// A hosted environment sets no local password for anyone, a platform
// administrator included (ruling 10 of cloud#4465, `cloud-managed.ts`).
Expand Down Expand Up @@ -314,6 +334,10 @@ export async function globalBeforeHook(
const resetSubject = resetDoor
? await resolveResetDoorUserId(ctx, this.config.phoneOtp?.allowedAttempts ?? 3)
: undefined;
// The account a reset door sets the password of, for the after-hook, which
// ends its sessions again once the password is written
// (`credential-change-ends-prior-access.ts`).
if (resetSubject?.ok && resetSubject.userId && ctx?.context) ctx.context[RESET_DOOR_SUBJECT] = resetSubject.userId;
if (resetSubject?.ok && resetSubject.userId) {
const source = await readUserSource(this.getDataEngine(), resetSubject.userId);
if (source.ok && isPendingSsoSource(source.value)) {
Expand Down Expand Up @@ -942,6 +966,20 @@ export async function globalBeforeHook(
const passwordDoor = passwordSignInDoorOf(ctx);
if (passwordDoor) {
if (passwordDoor.identifier) await this.admitSignInAttempt(passwordDoor.identifier, ctx, passwordDoor.door);
// A sign-in during which the account's password changes is refused: the
// first of its two readings (`credential-change-ends-prior-access.ts`).
// Each door's account is the one the vendor's own lookup at that door
// names, read through the vendor's adapter, so the reading needs no data
// engine.
const { door, identifier } = passwordDoor;
await noteSignInCredential(ctx, async () => {
if (!identifier) return undefined;
const id: unknown =
door === 'phone'
? (await ctx.context.adapter.findOne({ model: 'user', where: [{ field: 'phoneNumber', value: identifier }] }))?.id
: (await ctx.context.internalAdapter.findUserByEmail(identifier.toLowerCase()))?.user?.id;
return typeof id === 'string' && id.length > 0 ? id : undefined;
});
return;
}

Expand Down
Loading
Loading