@fuzdev/fuz_app 0.186.0 → 0.187.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/auth/CLAUDE.md +10 -5
  2. package/dist/auth/account_queries.d.ts +8 -5
  3. package/dist/auth/account_queries.d.ts.map +1 -1
  4. package/dist/auth/account_queries.js +8 -5
  5. package/dist/auth/role_grant_offer_action_specs.d.ts +1 -1
  6. package/dist/auth/role_grant_offer_action_specs.d.ts.map +1 -1
  7. package/dist/auth/role_grant_offer_action_specs.js +2 -1
  8. package/dist/auth/role_grant_offer_actions.d.ts +12 -0
  9. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  10. package/dist/auth/role_grant_offer_actions.js +48 -20
  11. package/dist/auth/role_grant_offer_queries.d.ts +16 -3
  12. package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
  13. package/dist/auth/role_grant_offer_queries.js +24 -4
  14. package/dist/auth/role_grant_queries.d.ts +102 -11
  15. package/dist/auth/role_grant_queries.d.ts.map +1 -1
  16. package/dist/auth/role_grant_queries.js +129 -15
  17. package/dist/db/migrate.d.ts +46 -22
  18. package/dist/db/migrate.d.ts.map +1 -1
  19. package/dist/db/migrate.js +103 -85
  20. package/dist/server/app_backend.d.ts.map +1 -1
  21. package/dist/server/app_backend.js +1 -4
  22. package/dist/testing/CLAUDE.md +35 -0
  23. package/dist/testing/cross_backend/backend_both_live.d.ts +47 -0
  24. package/dist/testing/cross_backend/backend_both_live.d.ts.map +1 -0
  25. package/dist/testing/cross_backend/backend_both_live.js +566 -0
  26. package/dist/testing/cross_backend/backend_swap.d.ts.map +1 -1
  27. package/dist/testing/cross_backend/backend_swap.js +37 -201
  28. package/dist/testing/cross_backend/shared_database_backends.d.ts +175 -0
  29. package/dist/testing/cross_backend/shared_database_backends.d.ts.map +1 -0
  30. package/dist/testing/cross_backend/shared_database_backends.js +298 -0
  31. package/dist/testing/cross_backend/spine_suites.d.ts +1 -1
  32. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  33. package/dist/testing/cross_backend/spine_suites.js +1 -0
  34. package/package.json +4 -3
@@ -56,31 +56,16 @@ import '../assert_dev_env.js';
56
56
  * @module
57
57
  */
58
58
  import { afterAll, afterEach, assert, beforeAll, describe, test } from 'vitest';
59
- import { parse } from '@fuzdev/fuz_schema/schema.ts';
60
59
  import { TokenCreateOutput, TokenRevokeOutput } from '../../auth/account_action_specs.js';
61
- import { SessionAccountJson } from '../../auth/account_schema.js';
62
- import { InviteCreateOutput, InviteListOutput } from '../../auth/admin_action_specs.js';
63
- import { DAEMON_TOKEN_HEADER } from '../../auth/daemon_token.js';
60
+ import { InviteCreateOutput } from '../../auth/admin_action_specs.js';
64
61
  import { RoleGrantOfferAcceptOutput, RoleGrantOfferCreateOutput, RoleGrantOfferDeclineOutput, RoleGrantOfferHistoryOutput, RoleGrantOfferListOutput } from '../../auth/role_grant_offer_action_specs.js';
65
62
  import { ROLE_ADMIN } from '../../auth/role_schema.js';
66
63
  import { create_db } from '../../db/create_db.js';
67
- import { EnvStringbool } from '../../env/env_schemas.js';
68
- import { ERROR_ALREADY_BOOTSTRAPPED, ERROR_AUTHENTICATION_REQUIRED, ERROR_INSUFFICIENT_PERMISSIONS, ERROR_INVALID_CREDENTIALS } from '../../http/error_schemas.js';
69
- import { DbInvariantRows } from '../db_invariant_queries.js';
70
- import { assert_db_invariant_rows } from '../db_invariants.js';
64
+ import { ERROR_ALREADY_BOOTSTRAPPED, ERROR_INVALID_CREDENTIALS } from '../../http/error_schemas.js';
71
65
  import { bootstrap } from '../transports/bootstrap.js';
72
- import { create_fetch_transport } from '../transports/fetch_transport.js';
73
- import { cross_rpc_call, error_reason, expect_output } from './cross_rpc.js';
74
- import { spawn_backend } from './spawn_backend.js';
66
+ import { expect_output } from './cross_rpc.js';
67
+ import { assert_backend_invariants, backend_post_json, backend_rpc, backend_rpc_as, backend_transport, drain_backend_effects, passes_admin_gate, read_shared_database_snapshot, teardown_live_backend, to_shared_database_problems, verified_account_id, with_live_backend } from './shared_database_backends.js';
75
68
  import { SPINE_ACCOUNT_LOGIN_PATH, SPINE_ACCOUNT_LOGOUT_PATH, SPINE_ACCOUNT_PASSWORD_PATH, SPINE_ACCOUNT_SIGNUP_PATH, SPINE_ACCOUNT_STATUS_PATH, SPINE_PARTICIPANT_ROLE } from './spine_surface_constants.js';
76
- /** The env var a backend's database URL rides in on both spine families. */
77
- const DATABASE_URL_ENV = 'DATABASE_URL';
78
- /** The cookie-signing keys env var both spine families read. */
79
- const COOKIE_KEYS_ENV = 'SECRET_FUZ_COOKIE_KEYS';
80
- /** The Rust family's startup-reset gate (`make_default_rust_backend_config`). */
81
- const RESET_DB_ON_STARTUP_ENV = 'FUZ_TESTING_RESET_DB_ON_STARTUP';
82
- /** The backdoors the suite drives. */
83
- const SWAP_BACKDOORS = ['_testing_drain_effects', '_testing_db_invariants'];
84
69
  /** The member account the first backend signs up. */
85
70
  const SWAP_MEMBER_USERNAME = 'swap_member';
86
71
  const SWAP_PASSWORD = 'swap-password-before';
@@ -88,129 +73,25 @@ const SWAP_PASSWORD_CHANGED = 'swap-password-after';
88
73
  const SWAP_PASSWORD_WRONG = 'swap-password-wrong';
89
74
  /** What a phase may take past its backend's startup window (ms). */
90
75
  const SWAP_PHASE_WORK_MS = 30_000;
91
- const read_snapshot = async (db) => {
92
- const schema_version = await db.query('SELECT namespace, name, sequence, applied_at::text AS applied_at FROM schema_version ' +
93
- 'ORDER BY namespace, sequence');
94
- const tables = await db.query('SELECT schemaname, tablename FROM pg_tables ' +
95
- "WHERE schemaname NOT IN ('pg_catalog', 'information_schema') ORDER BY schemaname, tablename");
96
- const content = {};
97
- for (const { schemaname, tablename } of tables) {
98
- const [row] = await db.query('SELECT count(*)::int AS rows, ' +
99
- "md5(coalesce(string_agg(t::text, E'\\n' ORDER BY t::text), '')) AS digest " +
100
- `FROM "${schemaname}"."${tablename}" t`);
101
- content[`${schemaname}.${tablename}`] = row;
102
- }
103
- return { schema_version, tables: content };
104
- };
105
- /**
106
- * Spawn `config`, run `body`, then tear down — a teardown failure (an exit
107
- * other than `0`, an unexpected error in the log) fails the phase. A failed
108
- * body's teardown is logged beside the body's error rather than replacing it.
109
- * The handle sits in `live` while the backend runs.
110
- */
111
- const with_backend = async (config, live, body) => {
112
- const handle = await spawn_backend(config);
113
- live.handle = handle;
114
- let result;
115
- try {
116
- result = await body(handle);
117
- }
118
- catch (err) {
119
- live.handle = null;
120
- await handle.teardown().catch((teardown_error) => console.error(teardown_error));
121
- throw err;
122
- }
123
- live.handle = null;
124
- await handle.teardown();
125
- return result;
126
- };
127
- /** Tear down a backend a phase left running — one that timed out — logging a failed teardown. */
128
- const teardown_left_running = async (live) => {
129
- const { handle } = live;
130
- if (!handle)
131
- return;
132
- live.handle = null;
133
- await handle.teardown().catch((err) => console.error(err));
134
- };
135
- /** A transport on `config`'s backend, holding `cookies` when given. */
136
- const transport_for = (config, cookies, origin) => create_fetch_transport({
137
- base_url: config.base_url,
138
- ...(cookies && { initial_cookies: cookies }),
139
- ...(origin === null && { origin: null })
140
- });
141
- const rpc = (config, transport, method, params, headers = {}) => cross_rpc_call(transport, config.rpc_path, method, params, headers);
142
- /** `method` on a fresh transport holding `cookies`, its output parsed. */
143
- const rpc_as = async (config, cookies, method, params, output) => expect_output(await rpc(config, transport_for(config, cookies), method, params), output);
144
- /** A daemon-token backdoor call: Origin-free and cookie-free, as the daemon token requires. */
145
- const backdoor = (handle, method) => rpc(handle.config, transport_for(handle.config, undefined, null), method, undefined, {
146
- [DAEMON_TOKEN_HEADER]: handle.daemon_token
147
- });
148
- /** Await the backend's detached writes, so what the phase did is all on disk before teardown. */
149
- const drain = async (handle) => {
150
- const drained = await backdoor(handle, '_testing_drain_effects');
151
- assert.deepStrictEqual(drained.result, { ok: true }, `${handle.config.name}: the drain answers`);
152
- };
153
- const assert_invariants = async (handle) => {
154
- const answer = expect_output(await backdoor(handle, '_testing_db_invariants'), DbInvariantRows);
155
- assert_db_invariant_rows(answer.rows, handle.config.name);
156
- };
157
- /** A JSON `POST` to a REST route: its status, body and `Set-Cookie` lines. */
158
- const post_json = async (transport, path, body) => {
159
- const res = await transport(path, {
160
- method: 'POST',
161
- headers: { 'content-type': 'application/json' },
162
- body: JSON.stringify(body)
163
- });
164
- const text = await res.text();
165
- return {
166
- status: res.status,
167
- body: text ? JSON.parse(text) : null,
168
- set_cookies: res.headers.getSetCookie()
169
- };
170
- };
171
- const login = (config, password) => post_json(transport_for(config), SPINE_ACCOUNT_LOGIN_PATH, {
76
+ const login = (config, password) => backend_post_json(backend_transport(config), SPINE_ACCOUNT_LOGIN_PATH, {
172
77
  username: SWAP_MEMBER_USERNAME,
173
78
  password
174
79
  });
175
- /** Who a credential authenticates as on `config`'s backend: an account id, or `null` on a 401. */
176
- const verified_account_id = async (config, credential) => {
177
- const res = 'cookies' in credential
178
- ? await rpc(config, transport_for(config, credential.cookies), 'account_verify', undefined)
179
- : // Origin-free: a bearer beside an `Origin` is discarded as browser context
180
- await rpc(config, transport_for(config, undefined, null), 'account_verify', undefined, {
181
- authorization: `Bearer ${credential.bearer}`
182
- });
183
- if (res.status === 401) {
184
- assert.strictEqual(error_reason(res), ERROR_AUTHENTICATION_REQUIRED);
185
- return null;
186
- }
187
- return expect_output(res, SessionAccountJson).id;
188
- };
189
- /** The member's admin gate: `invite_list` answered (`true`) or refused 403 (`false`). */
190
- const passes_admin_gate = async (config, cookies) => {
191
- const res = await rpc(config, transport_for(config, cookies), 'invite_list', undefined);
192
- if (res.status === 403) {
193
- assert.strictEqual(error_reason(res), ERROR_INSUFFICIENT_PERMISSIONS);
194
- return false;
195
- }
196
- expect_output(res, InviteListOutput);
197
- return true;
198
- };
199
80
  /** The first backend: bootstrap, then everything the second must honor. */
200
81
  const mint_swap_credentials = async (handle, db, declined_role) => {
201
82
  const { config } = handle;
202
- const keeper = await bootstrap({ transport: transport_for(config), config });
203
- const keeper_spare = await post_json(transport_for(config), SPINE_ACCOUNT_LOGIN_PATH, {
83
+ const keeper = await bootstrap({ transport: backend_transport(config), config });
84
+ const keeper_spare = await backend_post_json(backend_transport(config), SPINE_ACCOUNT_LOGIN_PATH, {
204
85
  username: config.bootstrap.username,
205
86
  password: config.bootstrap.password
206
87
  });
207
88
  assert.strictEqual(keeper_spare.status, 200, 'the keeper logs in again');
208
89
  assert.strictEqual(keeper_spare.set_cookies.length, 1, 'a login sets exactly the session cookie');
209
- const keeper_token = await rpc_as(config, keeper.cookies, 'account_token_create', { scope: { kind: 'full' }, lifetime: { kind: 'eternal' } }, TokenCreateOutput);
210
- expect_output(await rpc(config, transport_for(config, keeper.cookies), 'invite_create', {
90
+ const keeper_token = await backend_rpc_as(config, keeper.cookies, 'account_token_create', { scope: { kind: 'full' }, lifetime: { kind: 'eternal' } }, TokenCreateOutput);
91
+ expect_output(await backend_rpc(config, backend_transport(config, keeper.cookies), 'invite_create', {
211
92
  username: SWAP_MEMBER_USERNAME
212
93
  }), InviteCreateOutput);
213
- const signup = await post_json(transport_for(config), SPINE_ACCOUNT_SIGNUP_PATH, {
94
+ const signup = await backend_post_json(backend_transport(config), SPINE_ACCOUNT_SIGNUP_PATH, {
214
95
  username: SWAP_MEMBER_USERNAME,
215
96
  password: SWAP_PASSWORD
216
97
  });
@@ -220,13 +101,13 @@ const mint_swap_credentials = async (handle, db, declined_role) => {
220
101
  assert.strictEqual(logged_in.status, 200, 'the member logs in');
221
102
  assert.strictEqual(logged_in.set_cookies.length, 1, 'a login sets exactly the session cookie');
222
103
  const member_cookies = logged_in.set_cookies;
223
- const token = await rpc_as(config, member_cookies, 'account_token_create', { scope: { kind: 'full' }, lifetime: { kind: 'eternal' } }, TokenCreateOutput);
224
- const offer = async (params) => (await rpc_as(config, keeper.cookies, 'role_grant_offer_create', { to_account_id: member.account.id, ...params }, RoleGrantOfferCreateOutput)).offer.id;
104
+ const token = await backend_rpc_as(config, member_cookies, 'account_token_create', { scope: { kind: 'full' }, lifetime: { kind: 'eternal' } }, TokenCreateOutput);
105
+ const offer = async (params) => (await backend_rpc_as(config, keeper.cookies, 'role_grant_offer_create', { to_account_id: member.account.id, ...params }, RoleGrantOfferCreateOutput)).offer.id;
225
106
  const offer_accepted_id = await offer({ role: ROLE_ADMIN });
226
107
  const offer_declined_id = await offer({ role: declined_role, to_actor_id: member.actor.id });
227
- const { offers } = await rpc_as(config, member_cookies, 'role_grant_offer_list', undefined, RoleGrantOfferListOutput);
108
+ const { offers } = await backend_rpc_as(config, member_cookies, 'role_grant_offer_list', undefined, RoleGrantOfferListOutput);
228
109
  assert.sameMembers(offers.map((o) => o.id), [offer_accepted_id, offer_declined_id]);
229
- await drain(handle);
110
+ await drain_backend_effects(handle);
230
111
  return {
231
112
  keeper_id: keeper.account.id,
232
113
  keeper_cookies: keeper.cookies,
@@ -239,19 +120,19 @@ const mint_swap_credentials = async (handle, db, declined_role) => {
239
120
  token_id: token.id,
240
121
  offer_accepted_id,
241
122
  offer_declined_id,
242
- snapshot: await read_snapshot(db)
123
+ snapshot: await read_shared_database_snapshot(db)
243
124
  };
244
125
  };
245
126
  /** The second backend: honor everything the first minted, then write over it. */
246
127
  const use_swap_credentials = async (handle, db, minted) => {
247
128
  const { config } = handle;
248
129
  // before any request but the health probe: nothing migrated, nothing written
249
- assert.deepStrictEqual(await read_snapshot(db), minted.snapshot, 'the boot applied no migration and wrote or rewrote no row');
250
- const status = await transport_for(config)(SPINE_ACCOUNT_STATUS_PATH, { method: 'GET' });
130
+ assert.deepStrictEqual(await read_shared_database_snapshot(db), minted.snapshot, 'the boot applied no migration and wrote or rewrote no row');
131
+ const status = await backend_transport(config)(SPINE_ACCOUNT_STATUS_PATH, { method: 'GET' });
251
132
  const status_body = (await status.json());
252
133
  assert.strictEqual(status.status, 401, 'an anonymous status is refused');
253
134
  assert.notStrictEqual(status_body.bootstrap_available, true, 'bootstrap is closed');
254
- const rebootstrap = await post_json(transport_for(config), config.bootstrap_path, {
135
+ const rebootstrap = await backend_post_json(backend_transport(config), config.bootstrap_path, {
255
136
  token: config.bootstrap.token,
256
137
  username: config.bootstrap.username,
257
138
  password: config.bootstrap.password
@@ -269,32 +150,32 @@ const use_swap_credentials = async (handle, db, minted) => {
269
150
  const wrong = await login(config, SWAP_PASSWORD_WRONG);
270
151
  assert.strictEqual(wrong.status, 401, 'a wrong password is refused');
271
152
  assert.strictEqual(wrong.body.error, ERROR_INVALID_CREDENTIALS);
272
- const { offers } = await rpc_as(config, member_cookies, 'role_grant_offer_list', undefined, RoleGrantOfferListOutput);
153
+ const { offers } = await backend_rpc_as(config, member_cookies, 'role_grant_offer_list', undefined, RoleGrantOfferListOutput);
273
154
  assert.sameMembers(offers.filter((o) => o.accepted_at === null && o.declined_at === null).map((o) => o.id), [minted.offer_accepted_id, minted.offer_declined_id], 'both offers are pending');
274
155
  assert.isFalse(await passes_admin_gate(config, member_cookies), 'no admin before the accept');
275
- const declined = await rpc_as(config, member_cookies, 'role_grant_offer_decline', { offer_id: minted.offer_declined_id }, RoleGrantOfferDeclineOutput);
156
+ const declined = await backend_rpc_as(config, member_cookies, 'role_grant_offer_decline', { offer_id: minted.offer_declined_id }, RoleGrantOfferDeclineOutput);
276
157
  assert.isNotNull(declined.offer.declined_at);
277
- const accepted = await rpc_as(config, member_cookies, 'role_grant_offer_accept', { offer_id: minted.offer_accepted_id }, RoleGrantOfferAcceptOutput);
158
+ const accepted = await backend_rpc_as(config, member_cookies, 'role_grant_offer_accept', { offer_id: minted.offer_accepted_id }, RoleGrantOfferAcceptOutput);
278
159
  assert.isTrue(await passes_admin_gate(config, member_cookies), 'the accepted grant confers');
279
- await assert_invariants(handle);
160
+ await assert_backend_invariants(handle);
280
161
  // the revocations of what the first spine minted: the keeper's, which
281
162
  // nothing else ends, and the member's password change, which ends every
282
163
  // session and token of the member's
283
- const logout = await post_json(transport_for(config, minted.keeper_spare_cookies), SPINE_ACCOUNT_LOGOUT_PATH, {});
164
+ const logout = await backend_post_json(backend_transport(config, minted.keeper_spare_cookies), SPINE_ACCOUNT_LOGOUT_PATH, {});
284
165
  assert.strictEqual(logout.status, 200, "the first spine's keeper session logs out");
285
- const revoked = await rpc_as(config, minted.keeper_cookies, 'account_token_revoke', { token_id: minted.keeper_token_id }, TokenRevokeOutput);
166
+ const revoked = await backend_rpc_as(config, minted.keeper_cookies, 'account_token_revoke', { token_id: minted.keeper_token_id }, TokenRevokeOutput);
286
167
  assert.isTrue(revoked.revoked, "the first spine's keeper token is revoked");
287
168
  assert.isNull(await verified_account_id(config, { cookies: minted.keeper_spare_cookies }), 'the logged-out keeper session is refused');
288
169
  assert.isNull(await verified_account_id(config, { bearer: minted.keeper_token }), 'the revoked keeper token is refused');
289
- const changed = await post_json(transport_for(config, member_cookies), SPINE_ACCOUNT_PASSWORD_PATH, { current_password: SWAP_PASSWORD, new_password: SWAP_PASSWORD_CHANGED });
170
+ const changed = await backend_post_json(backend_transport(config, member_cookies), SPINE_ACCOUNT_PASSWORD_PATH, { current_password: SWAP_PASSWORD, new_password: SWAP_PASSWORD_CHANGED });
290
171
  assert.strictEqual(changed.status, 200, `password change: ${JSON.stringify(changed.body)}`);
291
- await drain(handle);
172
+ await drain_backend_effects(handle);
292
173
  return { member_cookies, role_grant_id: accepted.role_grant_id };
293
174
  };
294
175
  /** The first backend again: what the second wrote holds. */
295
176
  const check_swap_writes = async (handle, db, minted, written) => {
296
177
  const { config } = handle;
297
- assert.deepStrictEqual((await read_snapshot(db)).schema_version, minted.snapshot.schema_version, 'the migrations are as the first boot left them');
178
+ assert.deepStrictEqual((await read_shared_database_snapshot(db)).schema_version, minted.snapshot.schema_version, 'the migrations are as the first boot left them');
298
179
  // the revocations the second spine wrote, which nothing else ended
299
180
  assert.isNull(await verified_account_id(config, { cookies: minted.keeper_spare_cookies }), 'the keeper session the other spine logged out is refused');
300
181
  assert.isNull(await verified_account_id(config, { bearer: minted.keeper_token }), 'the keeper token the other spine revoked is refused');
@@ -308,7 +189,7 @@ const check_swap_writes = async (handle, db, minted, written) => {
308
189
  const new_password = await login(config, SWAP_PASSWORD_CHANGED);
309
190
  assert.strictEqual(new_password.status, 200, 'the new password logs in');
310
191
  assert.isTrue(await passes_admin_gate(config, new_password.set_cookies), 'the grant the other spine made confers');
311
- const { offers } = await rpc_as(config, minted.keeper_cookies, 'role_grant_offer_history', {}, RoleGrantOfferHistoryOutput);
192
+ const { offers } = await backend_rpc_as(config, minted.keeper_cookies, 'role_grant_offer_history', {}, RoleGrantOfferHistoryOutput);
312
193
  const accepted = offers.find((o) => o.id === minted.offer_accepted_id);
313
194
  const declined = offers.find((o) => o.id === minted.offer_declined_id);
314
195
  assert.ok(accepted && declined, "the keeper's history lists both offers");
@@ -316,65 +197,20 @@ const check_swap_writes = async (handle, db, minted, written) => {
316
197
  assert.strictEqual(accepted.resulting_role_grant_id, written.role_grant_id);
317
198
  assert.isNotNull(declined.declined_at, 'the declined offer is declined');
318
199
  assert.isNull(declined.accepted_at);
319
- await assert_invariants(handle);
320
- await drain(handle);
321
- };
322
- /**
323
- * Why a config's startup-reset env doesn't leave the reset off, or `null` when
324
- * it does — read as the Rust spine reads it: unset or a false stringbool is
325
- * off, a true one resets, and any other value fails its boot. A config that
326
- * leaves it out reads the harness process's own, which `spawn_backend` passes
327
- * to the child.
328
- */
329
- const to_reset_problem = (config) => {
330
- const value = config.env[RESET_DB_ON_STARTUP_ENV] ?? process.env[RESET_DB_ON_STARTUP_ENV];
331
- if (value === undefined)
332
- return null;
333
- const parsed = parse(EnvStringbool, value);
334
- if (!parsed.ok) {
335
- return `${config.name}'s ${RESET_DB_ON_STARTUP_ENV} is no stringbool (${JSON.stringify(value)})`;
336
- }
337
- return parsed.value
338
- ? `${config.name} resets its database at startup (${RESET_DB_ON_STARTUP_ENV})`
339
- : null;
200
+ await assert_backend_invariants(handle);
201
+ await drain_backend_effects(handle);
340
202
  };
341
203
  /**
342
- * Throw naming each way `order`'s configs can't swap over `database_url`.
343
- * Database URLs compare as exact strings.
204
+ * Throw naming each way `order`'s configs can't swap over `database_url`
205
+ * (`to_shared_database_problems`, and `declined_role` not `admin`).
344
206
  */
345
207
  const assert_swappable = (order, database_url, declined_role) => {
346
- const { first, second } = order;
347
208
  const problems = [];
348
209
  if (declined_role === ROLE_ADMIN) {
349
210
  problems.push(`declined_role is ${ROLE_ADMIN}, the accepted offer's role — a second offer of a ` +
350
211
  'role still pending answers the first, so the two offers would be one');
351
212
  }
352
- if (first.cookie_name !== second.cookie_name) {
353
- problems.push(`cookie names differ (${first.cookie_name}, ${second.cookie_name})`);
354
- }
355
- if (first.env[COOKIE_KEYS_ENV] === undefined && second.env[COOKIE_KEYS_ENV] === undefined) {
356
- problems.push(`neither config sets ${COOKIE_KEYS_ENV}`);
357
- }
358
- else if (first.env[COOKIE_KEYS_ENV] !== second.env[COOKIE_KEYS_ENV]) {
359
- problems.push(`${COOKIE_KEYS_ENV} differs`);
360
- }
361
- for (const config of [first, second]) {
362
- const url = config.env[DATABASE_URL_ENV];
363
- if (url === undefined) {
364
- problems.push(`${config.name} sets no ${DATABASE_URL_ENV}`);
365
- }
366
- else if (url !== database_url) {
367
- problems.push(`${config.name}'s ${DATABASE_URL_ENV} is not the swap's database`);
368
- }
369
- const reset_problem = to_reset_problem(config);
370
- if (reset_problem !== null)
371
- problems.push(reset_problem);
372
- for (const method of SWAP_BACKDOORS) {
373
- if (!config.capabilities.testing_backdoors.includes(method)) {
374
- problems.push(`${config.name} doesn't declare ${method}`);
375
- }
376
- }
377
- }
213
+ problems.push(...to_shared_database_problems([order.first, order.second], database_url));
378
214
  if (problems.length > 0) {
379
215
  throw new Error(`backend swap '${order.label}': ${problems.join('; ')}`);
380
216
  }
@@ -409,21 +245,21 @@ export const describe_backend_swap_tests = (options) => {
409
245
  const state = {};
410
246
  const live = { handle: null };
411
247
  describe(label, () => {
412
- afterEach(() => teardown_left_running(live));
248
+ afterEach(() => teardown_live_backend(live));
413
249
  test(`${first.name} mints credentials over an empty database`, async () => {
414
250
  assert_swappable(order, database_url, declined_role);
415
251
  await empty_database();
416
- state.minted = await with_backend(first, live, (handle) => mint_swap_credentials(handle, get_db(), declined_role));
252
+ state.minted = await with_live_backend(first, live, (handle) => mint_swap_credentials(handle, get_db(), declined_role));
417
253
  }, timeout);
418
254
  test(`${second.name} boots over them and honors each`, async () => {
419
255
  const { minted } = state;
420
256
  assert.ok(minted, `${first.name}'s mint phase did not complete`);
421
- state.written = await with_backend(second, live, (handle) => use_swap_credentials(handle, get_db(), minted));
257
+ state.written = await with_live_backend(second, live, (handle) => use_swap_credentials(handle, get_db(), minted));
422
258
  }, timeout);
423
259
  test(`${first.name} boots again and honors what ${second.name} wrote`, async () => {
424
260
  const { minted, written } = state;
425
261
  assert.ok(minted && written, `${second.name}'s phase did not complete`);
426
- await with_backend(first, live, (handle) => check_swap_writes(handle, get_db(), minted, written));
262
+ await with_live_backend(first, live, (handle) => check_swap_writes(handle, get_db(), minted, written));
427
263
  }, timeout);
428
264
  });
429
265
  }
@@ -0,0 +1,175 @@
1
+ import '../assert_dev_env.js';
2
+ import { type Schema } from '@fuzdev/fuz_schema/schema.ts';
3
+ import type { Db } from '../../db/db.js';
4
+ import { type FetchTransport } from '../transports/fetch_transport.js';
5
+ import type { BackendConfig } from './backend_config.js';
6
+ import { type RpcResult } from './cross_rpc.js';
7
+ import { type BackendHandle } from './spawn_backend.js';
8
+ /** The backdoors every shared-database suite drives: the drain and the invariants. */
9
+ export declare const SHARED_DATABASE_BACKDOORS: readonly ["_testing_drain_effects", "_testing_db_invariants"];
10
+ /** One table's content: its row count and a digest of its rows as text, in order. */
11
+ export interface SharedDatabaseTableContent {
12
+ readonly rows: number;
13
+ readonly digest: string;
14
+ }
15
+ /**
16
+ * The migrations a database holds (with when each was applied) and every
17
+ * table's content, keyed `schema.table` — a row written, deleted or rewritten
18
+ * in place changes its table's digest.
19
+ */
20
+ export interface SharedDatabaseSnapshot {
21
+ readonly schema_version: ReadonlyArray<Record<string, unknown>>;
22
+ readonly tables: Readonly<Record<string, SharedDatabaseTableContent>>;
23
+ }
24
+ /**
25
+ * Read the migrations and every table's content over `db`. Read it after the
26
+ * backends' drains (`drain_backend_effects`), or a detached write may land
27
+ * after it.
28
+ *
29
+ * @param db - a direct connection to the shared database
30
+ * @returns the snapshot
31
+ */
32
+ export declare const read_shared_database_snapshot: (db: Db) => Promise<SharedDatabaseSnapshot>;
33
+ /**
34
+ * The tables whose content differs between two snapshots, sorted — a table
35
+ * present in only one counts as changed.
36
+ *
37
+ * @param before - the earlier snapshot
38
+ * @param after - the later snapshot
39
+ * @returns the changed tables' `schema.table` keys
40
+ */
41
+ export declare const to_changed_tables: (before: SharedDatabaseSnapshot, after: SharedDatabaseSnapshot) => Array<string>;
42
+ /**
43
+ * Each way `configs` can't share `database_url`: they must name it in
44
+ * `DATABASE_URL` (compared as exact strings, so two spellings of one database
45
+ * are refused), share the session cookie name and a set
46
+ * `SECRET_FUZ_COOKIE_KEYS` (a cookie one spine signs, another must verify),
47
+ * keep a startup reset off (`FUZ_TESTING_RESET_DB_ON_STARTUP` unset or a false
48
+ * stringbool, as the Rust spine parses it), and declare the
49
+ * `SHARED_DATABASE_BACKDOORS`.
50
+ *
51
+ * @param configs - the backends that run over the database
52
+ * @param database_url - the `postgres://` database they share
53
+ * @returns the problems, empty when they can share it
54
+ */
55
+ export declare const to_shared_database_problems: (configs: ReadonlyArray<BackendConfig>, database_url: string) => Array<string>;
56
+ /**
57
+ * A spawned backend, held where an `afterEach` or `afterAll` can reach it: a
58
+ * test that times out abandons its body, which never tears down, and the next
59
+ * spawn would find the port taken.
60
+ */
61
+ export interface LiveBackend {
62
+ handle: BackendHandle | null;
63
+ }
64
+ /**
65
+ * Spawn `config`, run `body`, then tear down — a teardown failure (an exit
66
+ * other than `0`, an unexpected error in the log) fails the caller. A failed
67
+ * body's teardown is logged beside the body's error rather than replacing it.
68
+ * The handle sits in `live` while the backend runs.
69
+ *
70
+ * @param config - the backend to spawn
71
+ * @param live - where the running handle is held
72
+ * @param body - what to run against it
73
+ * @returns what `body` returned
74
+ */
75
+ export declare const with_live_backend: <T>(config: BackendConfig, live: LiveBackend, body: (handle: BackendHandle) => Promise<T>) => Promise<T>;
76
+ /**
77
+ * Tear down a backend left running — one whose test timed out — logging a
78
+ * failed teardown rather than throwing.
79
+ *
80
+ * @param live - the holder, cleared
81
+ */
82
+ export declare const teardown_live_backend: (live: LiveBackend) => Promise<void>;
83
+ /**
84
+ * A transport on `config`'s backend, holding `cookies` when given. `origin:
85
+ * null` sends no `Origin`, as a bearer or daemon token requires.
86
+ *
87
+ * @param config - the backend
88
+ * @param cookies - `Set-Cookie` lines to start the jar with
89
+ * @param origin - `null` for an Origin-free transport
90
+ * @returns the transport
91
+ */
92
+ export declare const backend_transport: (config: BackendConfig, cookies?: ReadonlyArray<string>, origin?: null) => FetchTransport;
93
+ /**
94
+ * `method` on `config`'s RPC endpoint over `transport`.
95
+ *
96
+ * @param config - the backend
97
+ * @param transport - the transport carrying the credential
98
+ * @param method - the RPC method
99
+ * @param params - its params
100
+ * @param headers - extra request headers
101
+ * @returns the answer
102
+ */
103
+ export declare const backend_rpc: (config: BackendConfig, transport: FetchTransport, method: string, params: unknown, headers?: Record<string, string>) => Promise<RpcResult>;
104
+ /**
105
+ * `method` on a fresh transport holding `cookies`, its output parsed.
106
+ *
107
+ * @param config - the backend
108
+ * @param cookies - the session's `Set-Cookie` lines
109
+ * @param method - the RPC method
110
+ * @param params - its params
111
+ * @param output - the output schema it must answer
112
+ * @returns the parsed output
113
+ */
114
+ export declare const backend_rpc_as: <T>(config: BackendConfig, cookies: ReadonlyArray<string>, method: string, params: unknown, output: Schema<T, any>) => Promise<T>;
115
+ /**
116
+ * A daemon-token backdoor call: Origin-free and cookie-free, as the daemon
117
+ * token requires.
118
+ *
119
+ * @param handle - the backend, whose daemon token authenticates
120
+ * @param method - the backdoor method
121
+ * @returns the answer
122
+ */
123
+ export declare const backend_daemon_rpc: (handle: BackendHandle, method: string) => Promise<RpcResult>;
124
+ /**
125
+ * Await the backend's detached writes (`_testing_drain_effects`), so what it
126
+ * did is all on disk before a snapshot or teardown.
127
+ *
128
+ * @param handle - the backend
129
+ */
130
+ export declare const drain_backend_effects: (handle: BackendHandle) => Promise<void>;
131
+ /**
132
+ * Assert no database invariant is broken, as `handle`'s backend reads them
133
+ * (`_testing_db_invariants`).
134
+ *
135
+ * @param handle - the backend
136
+ */
137
+ export declare const assert_backend_invariants: (handle: BackendHandle) => Promise<void>;
138
+ /** A REST answer: its status, parsed body (`null` when empty) and `Set-Cookie` lines. */
139
+ export interface BackendJsonAnswer {
140
+ readonly status: number;
141
+ readonly body: unknown;
142
+ readonly set_cookies: Array<string>;
143
+ }
144
+ /**
145
+ * A JSON `POST` to a REST route.
146
+ *
147
+ * @param transport - the transport carrying the credential
148
+ * @param path - the route path
149
+ * @param body - the JSON body
150
+ * @returns the answer
151
+ */
152
+ export declare const backend_post_json: (transport: FetchTransport, path: string, body: unknown) => Promise<BackendJsonAnswer>;
153
+ /**
154
+ * Who a credential authenticates as on `config`'s backend (`account_verify`):
155
+ * an account id, or `null` on a 401 `authentication_required`.
156
+ *
157
+ * @param config - the backend
158
+ * @param credential - a session's `Set-Cookie` lines or a bearer token
159
+ * @returns the account id, or `null` when refused
160
+ */
161
+ export declare const verified_account_id: (config: BackendConfig, credential: {
162
+ cookies: ReadonlyArray<string>;
163
+ } | {
164
+ bearer: string;
165
+ }) => Promise<string | null>;
166
+ /**
167
+ * Whether a session passes the admin gate: `invite_list` answered (`true`) or
168
+ * refused 403 `insufficient_permissions` (`false`).
169
+ *
170
+ * @param config - the backend
171
+ * @param cookies - the session's `Set-Cookie` lines
172
+ * @returns whether the gate passes
173
+ */
174
+ export declare const passes_admin_gate: (config: BackendConfig, cookies: ReadonlyArray<string>) => Promise<boolean>;
175
+ //# sourceMappingURL=shared_database_backends.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared_database_backends.d.ts","sourceRoot":"","sources":["../../../src/lib/testing/cross_backend/shared_database_backends.ts"],"names":[],"mappings":"AAAA,OAA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