Skip to content

Commit 4ed2092

Browse files
fix(plugin-auth): audit the forced-reset flag and its clear under the person who caused them (#31820)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9NNU55MLPfTn3FA66UzcuCo)_ Fixes #31804 Clause-②: no. Only the audit row's content changes: no route, option or field. Measured on base 5b7269f and head: both doors answer the same status and body and write the same values (CONTROL pins below). Metadata-protocol: none `domain:server#3` · dev session `session_01ADHkmShTSNgBjG5FV5GMXD` ## 维护者速读 - 改了什么:管理员重设密码(`/auth/admin/set-user-password`)写 `must_change_password=true`、用户自己改密码(`/auth/change-password`)写 `must_change_password=false`,这两次写入现在带上调用者,`sys_audit_log` 的 `actor` 和 `user_id` 分别记管理员和用户本人(模拟登录时另记 `impersonated_by`)。 - 为什么改:卡 #31804。main 上这两行审计的 `actor`、`user_id` 都是空,看不出是谁改的密码状态。 - 风险与回滚:只加归属,不改授权:两次写入仍以系统身份执行,写的值和两个入口的响应都不变。改密码的归属只给账号本人:没有会话(邮件链接重设)或会话属于别人时,仍记系统。附带:管理员建用户(`create-user`)的同一次写入也会记到管理员名下。回滚即还原本 PR。 - 先看:`admin-user-endpoints.ts` 的 `stampMustChangePassword` 与 `runAdminSetUserPassword` 里的 `runAttributedToUser`;`auth-manager-password-session-policy.ts` 的 `stampPasswordChangedAt`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/password-reset-ends-sessions.test.ts -t 'a password-state write'`,预期 4 条全绿。 - 需要你做的:无,席位落地。 ## What changes **Step 0, on `origin/main` 5b7269f.** A scratch probe (not committed) drove both doors over a real `ObjectQL` on better-sqlite3 with plugin-audit's real `installAuditWriters` and read the `sys_audit_log` rows for the user. The card's reading reproduces on `main`: | Write | Door | `actor` | `user_id` | |---|---|---|---| | `must_change_password` false → true | admin set-user-password | null | null | | `last_login_at` (sign-in stamp) | sign-in | the user | the user | | `password_changed_at` + `must_change_password` true → false | change-password | null | null | The same probe on this head: the set row names the administrator (`actor` = `user_id` = the admin), the clear row names the user, the sign-in stamp row and the sign-up stamp row are unchanged. **How #30989 carried identity into the audit writer** (the mechanism this PR reuses; no second one): | Hop | Where | What it carries | |---|---|---| | request scope | `auth-manager-request-routing.ts` `runWithAuthActorScope` around `auth.handler`; a framework route opens it itself with `runAttributedToUser(actor, …)` | one `AsyncLocalStorage` scope per request | | who | `auth-manager-before-hook.ts` `setAuthActorResolver` (the session's user and `impersonatedBy`); SCIM: the verified connection (`scimRequestConnectionId`) | resolved lazily, once per request | | write context | `auth-actor-attribution.ts` `authSystemWriteContext()` | `isSystem: true` plus `attributedUserId` / `impersonatedBy` / `performedBy`, or `actor: svc:scim:…` for SCIM | | engine → audit | ObjectQL `buildProvenance`; plugin-audit `audit-writers.ts` | `user_id` = `session.userId ?? provenance.attributedUserId`; `actor` = that, else `session.actor` | Both writes built their context as a bare `{ isSystem: true, positions: [], permissions: [] }`, so nothing reached the attribution channel. - **The forced reset** (`admin-user-endpoints.ts`): `stampMustChangePassword` builds its context as `{ ...SYSTEM_CTX, ...(await authSystemWriteContext()) }`, and `runAdminSetUserPassword` runs the stamp inside `runAttributedToUser(actor, …)` with the actor the route admitted (`gateAdmin`, which adds `impersonatedBy` from an impersonation session). Only the stamp is wrapped: the credential write and the revocation keep their contexts. - **The user's change** (`auth-manager-password-session-policy.ts` `stampPasswordChangedAt`): the context is `{ ...SYSTEM_CTX, ...attribution }` when the seam's `attributedUserId` is the stamped account itself, else the bare system context. On `/change-password` the stamped account is the session's own (`passwordChangeAfterEffectsAccount`), so the clear names the user. The same stamp runs after `/reset-password` and `/sign-up/email`: the emailed-link reset carries no session and stays the system's, and a request whose session names another account never credits that account's holder. - **Authorization is unchanged.** Both writes keep `isSystem: true`, `positions: []` and `permissions: []`; the attribution keys are read by no security middleware (`auth-actor-attribution.ts` header). No field-protection or read-only strip is crossed: the written fields and values are byte-identical. - **Bounded rider, declared.** `stampMustChangePassword` is also the create-user door's stamp, and that route already runs inside `runAttributedToUser(actor, …)` (`auth-plugin.ts`), so the administrator-created user's `must_change_password` set is now credited to the creating administrator too. Same defect class, same line, no other claim on the file, no new gate family; pinned below. ## Tests New pins, in the existing harnesses (no new test file): - `password-reset-ends-sessions.test.ts`, top-level `describe('a password-state write names the person who caused it')`, real `ObjectQL` + better-sqlite3 + `AuthManager.handleRequest`, observed on the raw engine `update` (the #30989 observation point, `scim-transaction-scope.test.ts`): - forced reset: the `must_change_password: true` write carries `attributedUserId` = the administrator, `isSystem: true`, no `userId`; CONTROL: 200, `data.mustChangePassword: true`, the patch is exactly `{ id, must_change_password: true }`, the stored flag is set; - forced reset from an impersonation session: `impersonatedBy` rides beside the administrator; - change-password: the clear carries `attributedUserId` = the user; CONTROL: 200, patch keys `id`, `must_change_password`, `password_changed_at`, stored flag cleared; CONTROL: the sign-in stamp is the user's, as before; - negative pin: a stamp inside another account's scope stays the system's, inside the holder's own scope it is credited; CONTROL: the emailed-link `/reset-password` stamp stays the system's. - `admin-user-endpoints.test.ts`, top-level `describe` for the create-user rider: inside the route's scope the stamp context is the system's plus `attributedUserId`; outside it, the bare system context. No existing test was changed. <details><summary>Ablations (each mutation landed on disk, went red, restored: blob == HEAD, git diff HEAD empty)</summary> `node scripts/ablation-replace.mjs`, tests import `src` (no dist leg): 1. `admin-user-endpoints.ts`: `context: { ...SYSTEM_CTX, ...(await authSystemWriteContext()) },` → `context: SYSTEM_CTX,` — the forced-reset pin and the impersonation pin red (`attributedUserId: "admin_password_state"` expected, `null` received; `impersonatedBy: "admin_at_keyboard"` expected, `null` received); the create-user rider pin red on the same mutation. 2. `auth-manager-password-session-policy.ts`: the attributed-context ternary → the bare `SYSTEM_CTX` — the change-password pin and the own-holder half of the negative pin red (`attributedUserId` = the user expected, `null` received). 3. same file: `attribution.attributedUserId === userId ?` → `attribution.attributedUserId !== undefined ?` — the negative pin red (`attributedUserId: null` expected, `"someone_else"` received). A first attempt at (2) with the bare replacement `SYSTEM_CTX` was refused by the tool before running (the replacement text already occurs in the file) and ran nothing; it was re-run with a unique spelling. </details> ## Acceptance notes - The real-writer measurement is step 0's scratch probe: a committed plugin-auth test cannot import plugin-audit without a new devDependency (`package.json`, lockfile) or a `CROSS_PACKAGE_TEST_INPUTS` + `turbo.json` entry, both outside this card's file surface. The committed pins observe the engine context, as #30989's plugin-auth half does; plugin-audit's `audit-writers.test.ts` already pins `provenance.attributedUserId` → `user_id` / `actor`. ## Verification All at head `d47e8cd6` (base `5b7269ff`; `origin/main` has since moved by commits touching none of `plugin-auth`, `plugin-audit` or `objectql`, so no merge). - `pnpm --filter @objectstack/plugin-auth test` — Test Files 246 passed (246), Tests 4411 passed | 10 skipped (4421); lock VERDICT command-exit 0. - `pnpm --filter @objectstack/plugin-auth typecheck` (after a full closure build with declarations) — exit 0; `check:test-typecheck` OK, the ledger held (10 files / 72 errors / 23 signatures, unchanged). - Package lint, `eslint --no-inline-config packages/plugins/plugin-auth` (the package has no `lint` script) — exit 0. - New pins alone: `vitest run src/password-reset-ends-sessions.test.ts -t 'a password-state write'` 4/4; `src/admin-user-endpoints.test.ts` 100/100. <details><summary>Derived gate list (dispatch-gates --commands, 68 families) and --ran reconciliation</summary> `node scripts/pm/dispatch-gates.mjs --ran FILE` — 68 derived, 67 run, 1 NOT-MEASURED, 0 UNRUN. Every run family exited 0. - `check-plugin-teardown-shape.mjs --self-test` first exited 3 (fixture commit unreachable on the shallow clone); after `git fetch --unshallow origin main` it exited 0 (48 cases). - `check:dts-closure` first exited 1: the first closure build ran with `OS_SKIP_DTS=1`; after a forced build with declarations it exited 0 (81 packages, 256/256 declaration files). - NOT MEASURED: `check:dual-build-cjs-loads` (exit 3, PREREQUISITE NOT MET: 43 packages outside this card's build closure have no `dist`). CI's run is the reading. </details> Dogfood battery: n/a (no `!` in the title, no `(narrowing)` arm). --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmShTSNgBjG5FV5GMXD)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0a4d8b1 commit 4ed2092

5 files changed

Lines changed: 243 additions & 6 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): the forced-reset flag and its clear are audited under the person who caused them
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
An administrator's forced password reset (`POST /api/v1/auth/admin/set-user-password`) and the user's own password change (`POST /api/v1/auth/change-password`) each write `sys_user.must_change_password`, and plugin-audit recorded both writes with a null `actor` and `user_id`, as if the system had made them. Both writes now carry their caller on the attribution seam every identity write already uses (`authSystemWriteContext`), so the `sys_audit_log` row for the set names the administrator (and, from an impersonation session, the administrator at the keyboard as `impersonated_by`), and the row for the clear names the user.
11+
12+
- **Unchanged.** Both writes still run as the system: what they may write, the values they write and both doors' answers are the same. The sign-in stamp row is unchanged. A password change is credited only to the account's own holder: a request whose session names nobody (the emailed-link reset) or another account leaves the row the system's, as before.
13+
- **Also attributed.** The administrator-created user's `must_change_password` set (`POST /api/v1/auth/admin/create-user`) goes through the same write and is now credited to the creating administrator.

‎packages/plugins/plugin-auth/src/admin-user-endpoints.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1601,3 +1601,29 @@ describe('create-user in multi-org mode: the new user joins the administrator\'s
16011601
expect((action?.params ?? []).map((p) => p.name ?? p.field)).not.toContain('organizationId');
16021602
});
16031603
});
1604+
1605+
describe("create-user: the must_change_password stamp names the administrator the route's scope carries", () => {
1606+
// `auth-plugin.ts` runs this door inside `runAttributedToUser(actor, …)`; the
1607+
// stamp builds its context with `authSystemWriteContext()`, so the
1608+
// `sys_user` write carries the administrator on the attribution channel
1609+
// (plugin-audit's `user_id` / `actor`) and still authorizes as the system.
1610+
it('inside the scope: attributed, still the system; outside it: the system alone', async () => {
1611+
const { runAttributedToUser } = await import('./auth-actor-attribution.js');
1612+
const stampContext = (m: ReturnType<typeof makeDeps>) => {
1613+
const stamp = callsOf(m.engineUpdate).filter(([object, row]) => object === 'sys_user' && 'must_change_password' in row);
1614+
expect(stamp).toHaveLength(1);
1615+
return (stamp[0] as unknown as [string, unknown, { context: Record<string, unknown> }])[2].context;
1616+
};
1617+
1618+
const scoped = makeDeps();
1619+
const res = await runAttributedToUser(ACTOR, () =>
1620+
runAdminCreateUser(scoped.deps, makeRequest({ email: 'new.user@example.com', generatePassword: true }), ACTOR),
1621+
);
1622+
expect(res.status).toBe(200);
1623+
expect(stampContext(scoped)).toEqual({ isSystem: true, positions: [], permissions: [], attributedUserId: ACTOR.id });
1624+
1625+
const bare = makeDeps();
1626+
expect((await runAdminCreateUser(bare.deps, makeRequest({ email: 'new.user@example.com', generatePassword: true }), ACTOR)).status).toBe(200);
1627+
expect(stampContext(bare)).toEqual({ isSystem: true, positions: [], permissions: [] });
1628+
});
1629+
});

‎packages/plugins/plugin-auth/src/admin-user-endpoints.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ export interface EndpointResult {
225225
}
226226

227227
import { generatePlaceholderEmail } from './placeholder-email.js';
228+
import { authSystemWriteContext, runAttributedToUser } from './auth-actor-attribution.js';
228229
import { revokeSessionsAndApiKeys, type ForcedResetRevocationOutcome } from './forced-reset-revocation.js';
229230
import { reconcileMembership, type MembershipPolicy } from './reconcile-membership.js';
230231
import { resolveDefaultOrgId } from './tenancy-service.js';
@@ -441,8 +442,13 @@ async function stampMustChangePassword(
441442
const engine = deps.getDataEngine();
442443
if (!engine) return false;
443444
try {
445+
// The write authorizes as the system, exactly as before; the attribution
446+
// seam (`authSystemWriteContext`) only adds the administrator the caller's
447+
// scope names, so plugin-audit's mirror row for this field write records
448+
// who issued the forced change instead of the system. Outside a scope it
449+
// adds nothing.
444450
await engine.update('sys_user', { id: userId, must_change_password: value }, {
445-
context: SYSTEM_CTX,
451+
context: { ...SYSTEM_CTX, ...(await authSystemWriteContext()) },
446452
});
447453
if (value) deps.noteMustChangePasswordIssued();
448454
return true;
@@ -1148,9 +1154,15 @@ export async function runAdminSetUserPassword(
11481154
return mapAuthApiError(error, 'set-user-password failed');
11491155
}
11501156

1151-
const stamped = mustChangePassword
1152-
? await stampMustChangePassword(deps, userId, true)
1153-
: await stampMustChangePassword(deps, userId, false);
1157+
// The flag write is credited to the administrator this route admitted (and,
1158+
// from an impersonation session, the administrator at the keyboard beside
1159+
// them), through the same attribution seam every identity write uses. This
1160+
// route drives the write itself, outside `AuthManager.handleRequest`, so it
1161+
// opens the seam with the actor already in hand. Attribution only: the route
1162+
// authorized the caller above, and the write still runs as the system.
1163+
const stamped = await runAttributedToUser(actor, () =>
1164+
stampMustChangePassword(deps, userId, mustChangePassword),
1165+
);
11541166

11551167
// Revoked AFTER the new password is set, so a session the old password
11561168
// opened cannot outlive the reset, and never before it: a revocation that

‎packages/plugins/plugin-auth/src/auth-manager-password-session-policy.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545

4646
import type { AuthManager } from './auth-manager.js';
4747
import type { AuthGate } from '@objectstack/core';
48+
import { authSystemWriteContext } from './auth-actor-attribution.js';
4849
import { recoverInternalFieldsForSystemRead } from './internal-field-readback.js';
4950
import { effectiveMfaLevel, effectiveSessionLimits } from './organization-access-policy.js';
5051

@@ -267,12 +268,21 @@ export async function stampPasswordChangedAt(this: Pick<PasswordSessionPolicyHos
267268
if (!engine || !userId) return;
268269
try {
269270
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] };
271+
// The stamp is credited to the account's own holder when this request's
272+
// session names them (a `/change-password`, impersonation included):
273+
// the attribution seam's answer, attribution only, so the write still
274+
// authorizes as the system. A request whose session names nobody, or
275+
// somebody else (a token-carrying `/reset-password` sent beside another
276+
// account's cookie), stays the system's: the holder of that session did
277+
// not change this account's password.
278+
const attribution = await authSystemWriteContext();
279+
const context = attribution.attributedUserId === userId ? { ...SYSTEM_CTX, ...attribution } : SYSTEM_CTX;
270280
// #2766 V1 — a completed password change also satisfies any pending
271281
// admin-issued force-change flag, so clear it in the same write.
272282
await engine.update(
273283
'sys_user',
274284
{ id: userId, password_changed_at: new Date(), must_change_password: false },
275-
{ context: SYSTEM_CTX } as any,
285+
{ context } as any,
276286
);
277287
} catch (e) {
278288
// Never break a valid password change — the new password IS set.

‎packages/plugins/plugin-auth/src/password-reset-ends-sessions.test.ts‎

Lines changed: 177 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,13 @@
2727
* door every session the account held is still a `sys_session` row
2828
* afterwards, stamped `revoked_at` and `revoke_reason: password_reset`, and
2929
* it still answers 401; the control, an administrator's forced reset over
30-
* the same engine, stamps `admin_password_reset` instead.
30+
* the same engine, stamps `admin_password_reset` instead;
31+
* - a password-state write names the person who caused it: the forced
32+
* reset's `must_change_password` set names the administrator (and the
33+
* administrator at the keyboard of an impersonation session), the user's
34+
* own `/change-password` clear names the user, both still as the system;
35+
* the stamp is never credited to another session's holder, and the
36+
* sign-in stamp and the emailed-link reset are unchanged.
3137
*/
3238

3339
import { describe, it, expect, afterAll, afterEach, vi } from 'vitest';
@@ -38,6 +44,7 @@ import { runAdminSetUserPassword, type AdminUserEndpointDeps } from './admin-use
3844
import { authIdentityObjects } from './manifest.js';
3945
import { REVOKE_SESSIONS_ON_PASSWORD_RESET_RETIRED } from '@objectstack/spec/system';
4046
import { assertPasswordResetEndsSessions } from './password-reset-ends-sessions.js';
47+
import { runAttributedToUser } from './auth-actor-attribution.js';
4148
import { memoizeScrypt } from './__tests__/scrypt-memo.testkit';
4249
import { sqliteEnginePool } from './__tests__/sqlite-engine-pool.testkit';
4350
// better-auth's first module load is paid here, at module load, not inside the
@@ -504,3 +511,172 @@ describe('ADR-0069 D2: an account whose failed_login_count is NULL is counted an
504511
expect(Number((await lockoutRow(a.engine)).failed_login_count)).toBe(0);
505512
}, 60_000);
506513
});
514+
515+
describe('a password-state write names the person who caused it', () => {
516+
// The `sys_user` writes that set and clear `must_change_password` reach the
517+
// engine as the system (their authorization, unchanged) and name their
518+
// caller on the attribution seam (`auth-actor-attribution.ts`): the
519+
// execution context's `attributedUserId`, and `impersonatedBy` from an
520+
// impersonation session. plugin-audit's ledger writer turns that channel
521+
// into `sys_audit_log.user_id` and `actor` (its own `audit-writers.test.ts`
522+
// pins the `provenance.attributedUserId` read), the way the sign-in stamp
523+
// is already attributed. Observed on the raw engine, beneath every caller,
524+
// so the context is the one the audit writer's hooks are built from.
525+
const THIRD = 'Th1rd!Password-After-Change';
526+
const ADMIN = 'admin_password_state';
527+
528+
interface UserWrite {
529+
patch: Record<string, unknown>;
530+
context: Record<string, unknown>;
531+
}
532+
533+
/** Every `sys_user` update with the context it reached the engine with. Call-through. */
534+
function observeUserUpdates(engine: ObjectQL): UserWrite[] {
535+
const writes: UserWrite[] = [];
536+
const original = engine.update.bind(engine);
537+
vi.spyOn(engine, 'update').mockImplementation((async (object: string, data: Record<string, unknown>, options?: { context?: Record<string, unknown> }) => {
538+
if (object === 'sys_user') writes.push({ patch: { ...data }, context: { ...(options?.context ?? {}) } });
539+
return original(object as never, data as never, options as never);
540+
}) as never);
541+
return writes;
542+
}
543+
544+
/** The one write that touched `field`. */
545+
const writeOf = (writes: UserWrite[], field: string): UserWrite => {
546+
const hits = writes.filter((w) => field in w.patch);
547+
expect(hits, JSON.stringify(writes.map((w) => Object.keys(w.patch)))).toHaveLength(1);
548+
return hits[0];
549+
};
550+
551+
/** The authorization half and the attribution half of a write's context. */
552+
const credit = (w: UserWrite) => ({
553+
isSystem: w.context.isSystem,
554+
userId: w.context.userId ?? null,
555+
attributedUserId: w.context.attributedUserId ?? null,
556+
impersonatedBy: w.context.impersonatedBy ?? null,
557+
});
558+
559+
async function userOf(a: Account): Promise<{ id: string; must_change_password: unknown }> {
560+
const [user] = (await a.engine.find('sys_user', { where: { email: EMAIL }, limit: 1 }, SYS)) as Array<{
561+
id: string;
562+
must_change_password: unknown;
563+
}>;
564+
return user;
565+
}
566+
567+
/** An administrator's forced reset through the door `auth-plugin.ts` mounts, with the deps it hands it. */
568+
function forcedReset(a: Account, userId: string, actor: { id: string; email?: string; impersonatedBy?: string }) {
569+
const m = a.manager;
570+
const deps = {
571+
getAuthApi: () => m.getApi(),
572+
getAuthContext: () => m.getAuthContext(),
573+
getDataEngine: () => m.getDataEngine(),
574+
assertPasswordComplexity: (pw: string) => m.checkPasswordComplexity(pw),
575+
noteMustChangePasswordIssued: () => m.noteMustChangePasswordIssued(),
576+
phoneNumberEnabled: () => m.isPhoneNumberEnabled(),
577+
getMembershipPolicy: () => m.getMembershipPolicy(),
578+
logger: { warn() {}, info() {}, error() {}, debug() {} },
579+
} as unknown as AdminUserEndpointDeps;
580+
return runAdminSetUserPassword(
581+
deps,
582+
new Request(`${AUTH}/admin/set-user-password`, {
583+
method: 'POST',
584+
headers: { 'Content-Type': 'application/json', origin: BASE },
585+
body: JSON.stringify({ userId, newPassword: SECOND }),
586+
}),
587+
actor as never,
588+
);
589+
}
590+
591+
it("the administrator's forced reset: the must_change_password write names the administrator, and still runs as the system", async () => {
592+
const a = await signedInAccount();
593+
const user = await userOf(a);
594+
const writes = observeUserUpdates(a.engine);
595+
596+
const forced = await forcedReset(a, user.id, { id: ADMIN, email: 'admin@example.com' });
597+
598+
// CONTROL: the door's answer and the value it writes are unchanged.
599+
expect(forced.status, JSON.stringify(forced.body)).toBe(200);
600+
expect(forced.body.data?.mustChangePassword).toBe(true);
601+
const flag = writeOf(writes, 'must_change_password');
602+
expect(flag.patch).toEqual({ id: user.id, must_change_password: true });
603+
expect((await userOf(a)).must_change_password).toBeTruthy();
604+
// The authorization half is the system's, as before; the attribution half names the administrator.
605+
expect(flag.context).toMatchObject({ isSystem: true, positions: [], permissions: [] });
606+
expect(credit(flag)).toEqual({ isSystem: true, userId: null, attributedUserId: ADMIN, impersonatedBy: null });
607+
}, 60_000);
608+
609+
it('from an impersonation session, the administrator at the keyboard rides beside the admitted actor', async () => {
610+
const a = await signedInAccount();
611+
const user = await userOf(a);
612+
const writes = observeUserUpdates(a.engine);
613+
614+
const forced = await forcedReset(a, user.id, { id: ADMIN, impersonatedBy: 'admin_at_keyboard' });
615+
616+
expect(forced.status, JSON.stringify(forced.body)).toBe(200);
617+
expect(credit(writeOf(writes, 'must_change_password'))).toEqual({
618+
isSystem: true,
619+
userId: null,
620+
attributedUserId: ADMIN,
621+
impersonatedBy: 'admin_at_keyboard',
622+
});
623+
}, 60_000);
624+
625+
it("the user's own change-password: the clear names the user; the sign-in stamp before it is unchanged", async () => {
626+
const a = await signedInAccount();
627+
const user = await userOf(a);
628+
expect((await forcedReset(a, user.id, { id: ADMIN })).status).toBe(200);
629+
const writes = observeUserUpdates(a.engine);
630+
631+
const signedIn = await post(a.manager, '/sign-in/email', { email: EMAIL, password: SECOND });
632+
expect(signedIn.status, await signedIn.clone().text()).toBe(200);
633+
// CONTROL: the sign-in stamp is the user's, as it already was.
634+
expect(credit(writeOf(writes, 'last_login_at'))).toEqual({
635+
isSystem: true,
636+
userId: null,
637+
attributedUserId: user.id,
638+
impersonatedBy: null,
639+
});
640+
641+
const changed = await post(
642+
a.manager,
643+
'/change-password',
644+
{ currentPassword: SECOND, newPassword: THIRD },
645+
{ cookie: cookieFrom(signedIn) },
646+
);
647+
// CONTROL: the door's answer and the values it writes are unchanged.
648+
expect(changed.status, await changed.clone().text()).toBe(200);
649+
const clear = writeOf(writes, 'must_change_password');
650+
expect(Object.keys(clear.patch).sort()).toEqual(['id', 'must_change_password', 'password_changed_at']);
651+
expect(clear.patch).toMatchObject({ id: user.id, must_change_password: false });
652+
expect((await userOf(a)).must_change_password).toBeFalsy();
653+
expect(clear.context).toMatchObject({ isSystem: true, positions: [], permissions: [] });
654+
expect(credit(clear)).toEqual({ isSystem: true, userId: null, attributedUserId: user.id, impersonatedBy: null });
655+
}, 60_000);
656+
657+
it("a stamp is credited only to the account's own holder: another session's holder, or none, leaves it the system's", async () => {
658+
const a = await signedInAccount();
659+
const user = await userOf(a);
660+
const stamp = (a.manager as never as { stampPasswordChangedAt(u: string): Promise<void> }).stampPasswordChangedAt.bind(a.manager);
661+
const writes = observeUserUpdates(a.engine);
662+
663+
await runAttributedToUser('someone_else', () => stamp(user.id));
664+
await runAttributedToUser(user.id, () => stamp(user.id));
665+
expect(writes.map(credit)).toEqual([
666+
{ isSystem: true, userId: null, attributedUserId: null, impersonatedBy: null },
667+
{ isSystem: true, userId: null, attributedUserId: user.id, impersonatedBy: null },
668+
]);
669+
670+
// CONTROL: the emailed-link reset carries no session, so its stamp stays the system's.
671+
writes.length = 0;
672+
const token = await requestResetToken(a);
673+
const reset = await post(a.manager, '/reset-password', { token, newPassword: SECOND });
674+
expect(reset.status, await reset.clone().text()).toBe(200);
675+
expect(credit(writeOf(writes, 'must_change_password'))).toEqual({
676+
isSystem: true,
677+
userId: null,
678+
attributedUserId: null,
679+
impersonatedBy: null,
680+
});
681+
}, 60_000);
682+
});

0 commit comments

Comments
 (0)