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

fix(plugin-auth): an administrator's impersonation session is not held by the target's forced password reset or password expiry (#24762)

Clause-②: no

Impersonating a user who must change their password used to strand the administrator: the impersonation session was refused `403 PASSWORD_RESET_REQUIRED` on every protected route, and the console showed the target's change-password screen. An impersonation session is minted from the administrator's own session, which has passed its own posture check, so it is not the user's password sign-in, and a `credential`-scope posture holds the password sign-in alone (`AUTH_GATE_SCOPES`).

- **What moves.** On a session that carries `impersonatedBy`, the session gate (`user.authGate`, stamped in `customSession`) now shows only the first `account`-scope posture the user holds. `PASSWORD_RESET_REQUIRED` and `PASSWORD_EXPIRED` no longer hold it. `MFA_REQUIRED` still does, so an impersonation session of a user who owes MFA enrolment is still refused `403 MFA_REQUIRED`, including when the user also owes a password change.
- **Unchanged.** The user's own sign-in stays held until they change the password. The forced reset's revocation (`revokeSessionsAndKeys`, on by default) still ends every session of the user, impersonation sessions included. API keys, the print door's refusal of an impersonation session, and the impersonation door's own check of the administrator's posture are unchanged.
7 changes: 6 additions & 1 deletion content/docs/permissions/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -981,7 +981,12 @@ logged. While `mustChangePassword` is set, the user is blocked with
`403 PASSWORD_RESET_REQUIRED` on every protected route until they complete a
password change. It is the same gate as password expiry, under its own code,
and like expiry it holds password sign-in only: the user's API keys are not
held by it.
held by it. Nor is an administrator's impersonation session, which is minted
from the administrator's own session and is not the user's password sign-in:
an administrator can impersonate the user to verify their access before the
user has changed the password, while the user's own sign-in stays blocked.
Enforced MFA (`MFA_REQUIRED`) holds the account, so it still holds an
impersonation session of that user.

#### Set / Reset a Password

Expand Down
53 changes: 52 additions & 1 deletion packages/plugins/plugin-auth/src/auth-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3665,7 +3665,7 @@ describe('AuthManager', () => {
findOne: vi.fn(),
}, { permissions: [{ name: ADMIN_FULL_ACCESS, ...ADMIN_FULL_ACCESS_CAPABILITIES }] });

const getSessionCallback = async (dataEngine: any) => {
const getSessionCallback = async (dataEngine: any, extra: Record<string, unknown> = {}) => {
let capturedConfig: any;
(betterAuth as any).mockImplementation((config: any) => {
capturedConfig = config;
Expand All @@ -3677,6 +3677,7 @@ describe('AuthManager', () => {
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
dataEngine,
...extra,
});
await manager.getAuthInstance();
warnSpy.mockRestore();
Expand Down Expand Up @@ -3772,6 +3773,56 @@ describe('AuthManager', () => {
expect(result.user).toBe(user);
expect(result.user.positions).toBeUndefined();
});

// [#24762, ruling 6288774214 items 1–3] What `user.authGate` the producer
// stamps on an impersonation session (`session.impersonatedBy` set) of a
// held user: only an `account`-scope posture (`AUTH_GATE_SCOPES`) holds
// it, the first one the user's list reports. The user's own session keeps
// the list's first entry. The same cases on a real boot, through the
// transport seams' 403 envelope, are `@objectstack/verify`'s
// `held-session-impersonation-target.pin.test.ts`.
describe('the posture stamped on an impersonation session (ADR-0069, AUTH_GATE_SCOPES)', () => {
const LAPSED = () => new Date(Date.now() - 30 * 86_400_000).toISOString();
const IMPERSONATION = { impersonatedBy: 'u-admin' };
// Every posture computable at once: enforced MFA with no grace, and a
// one-day expiry. Each row below decides which postures its user holds.
const POLICY = { mfaRequired: true, mfaGracePeriodDays: 0, passwordExpiryDays: 1 };
const sessionGateFor = async (row: Record<string, unknown>, session: Record<string, unknown>) => {
const engine = makeDataEngine({ platformAdmin: false });
// The block's double, its `findOne` answering the posture read of the user row.
engine.findOne = vi.fn(async (object: string, q?: any) => {
assertEngineFindOnePredicate(object, q);
return object === 'sys_user' && q?.where?.id === 'u-1' ? { id: 'u-1', ...row } : null;
}) as any;
const callback = await getSessionCallback(engine, POLICY);
const result = await callback({ user: { id: 'u-1', email: 'a@b.com' }, session });
return result.user.authGate?.code;
};
const RESET = { must_change_password: true, two_factor_enabled: true, password_changed_at: new Date().toISOString() };
const EXPIRED = { must_change_password: false, two_factor_enabled: true, password_changed_at: LAPSED() };
const MFA = { must_change_password: false, two_factor_enabled: false, mfa_required_at: LAPSED(), password_changed_at: new Date().toISOString() };
const RESET_AND_MFA = { ...MFA, must_change_password: true };

it('a forced-reset user: their own session is held, an impersonation session of them is not', async () => {
expect(await sessionGateFor(RESET, {})).toBe('PASSWORD_RESET_REQUIRED');
expect(await sessionGateFor(RESET, IMPERSONATION)).toBeUndefined();
});

it('an expired-password user: the same, the other credential-scope posture', async () => {
expect(await sessionGateFor(EXPIRED, {})).toBe('PASSWORD_EXPIRED');
expect(await sessionGateFor(EXPIRED, IMPERSONATION)).toBeUndefined();
});

it('an MFA-held user: the account-scope posture holds the impersonation session too', async () => {
expect(await sessionGateFor(MFA, {})).toBe('MFA_REQUIRED');
expect(await sessionGateFor(MFA, IMPERSONATION)).toBe('MFA_REQUIRED');
});

it('a user held by both: their own session shows the reset, the impersonation session MFA_REQUIRED', async () => {
expect(await sessionGateFor(RESET_AND_MFA, {})).toBe('PASSWORD_RESET_REQUIRED');
expect(await sessionGateFor(RESET_AND_MFA, IMPERSONATION)).toBe('MFA_REQUIRED');
});
});
});

// ADR-0069 D1: breached-password rejection enables better-auth's native
Expand Down
44 changes: 37 additions & 7 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
API_KEY_DEFAULT_EXPIRY_DAYS,
API_KEY_INACTIVITY_DAYS,
API_KEY_MAX_EXPIRY_DAYS,
accountScopeAuthGate,
hasPlatformAdminStanding,
resolveUserAuthzGrants,
} from '@objectstack/core';
Expand Down Expand Up @@ -4593,10 +4594,16 @@ export class AuthManager {
// revokes the session in place when exceeded (next request → 401).
await this.enforceSessionControls((session as any)?.id, (session as any)?.createdAt);

// An impersonation session carries the administrator who started it
// (`impersonatedBy`, written by the admin plugin's impersonation and
// stored as `sys_session.impersonated_by`); which postures hold the
// session depends on it — see computeAuthGate().
const impersonatedBy = (session as any)?.impersonatedBy;
const authGate = await this.computeAuthGate(
user.id,
(session as any)?.activeOrganizationId,
(user as any)?.twoFactorEnabled === true,
{ impersonation: typeof impersonatedBy === 'string' && impersonatedBy.trim() !== '' },
);

return {
Expand Down Expand Up @@ -8897,15 +8904,36 @@ export class AuthManager {
/**
* ADR-0069 — the auth-policy gate posture for a SESSION: the first, most
* urgent posture {@link resolveUserAuthGates} reports for its user in its
* active organization, else undefined. Every scope holds a session, because
* a session IS the password sign-in (#23287, ruling C′ item 1).
* active organization that holds this session, else undefined.
*
* What a posture holds is its declared scope (`AUTH_GATE_SCOPES`, #23287,
* ruling C′ item 1): `account` holds every credential of the user,
* `credential` holds the password sign-in alone. Which postures hold a
* session therefore depends on what the session is:
*
* - a session the user signed in to themselves is held by every scope: it
* IS the password sign-in a `credential` posture holds;
* - an IMPERSONATION session (`options.impersonation`, read off
* `session.impersonatedBy`) is not the user's password sign-in. It is
* minted from the administrator's own session, which passed its own
* posture check at the impersonation door. So only an `account`-scope
* posture holds it: the first one the list reports, wherever it sits
* (`accountScopeAuthGate`, the reading the API-key admission seam gives
* a key, the other credential that is not the password sign-in). A target
* held by both the forced reset and enforced MFA answers `MFA_REQUIRED`
* on it, never nothing (#24762, ruling 6288774214 items 1 and 2).
*
* The other callers ask for a user's own session (`options` omitted), so
* their answer is the list's first entry, as it always was.
*/
private async computeAuthGate(
userId: string,
activeOrgId: string | undefined,
_twoFactorEnabledHint: boolean,
options: { impersonation?: boolean } = {},
): Promise<AuthGate | undefined> {
const gates = await this.resolveUserAuthGates(userId, { organizationId: activeOrgId });
if (options.impersonation === true) return accountScopeAuthGate(gates) ?? undefined;
return gates[0];
}

Expand All @@ -8914,7 +8942,8 @@ export class AuthManager {
* `userId` holds right now, most urgent first; `[]` when no policy holds
* them. The ONE per-user posture computation (`IAuthService.resolveUserAuthGates`):
*
* - the session gate takes its first entry ({@link computeAuthGate}, onto
* - the session gate takes its first entry, and on an impersonation session
* its first `account`-scope entry ({@link computeAuthGate}, onto
* `user.authGate` in `customSession`);
* - the API-key admission seam (`resolveApiKeyAdmission`, `@objectstack/core`)
* asks it for a key's owner and holds the key on an `account`-scope entry
Expand All @@ -8925,10 +8954,11 @@ export class AuthManager {
* organization may require MFA above the global floor.
*
* Order, most urgent first: the administrator's forced reset, then natural
* password expiry, then enforced MFA. The session shows the first; a key is
* held only by an `account`-scope entry, wherever it sits in the list — a
* user whose password expired AND who owes MFA enrolment holds their keys
* on the MFA entry even though their session shows the expiry.
* password expiry, then enforced MFA. The user's own session shows the
* first; a key, and an impersonation session, are held only by an
* `account`-scope entry, wherever it sits in the list — a user whose
* password expired AND who owes MFA enrolment holds their keys on the MFA
* entry even though their session shows the expiry.
*
* No-op (no read) when no gate feature is enabled. Fails OPEN on any lookup
* error, answering `[]` — a transient hiccup must never lock a compliant user
Expand Down
Loading
Loading