Skip to content

Commit 518f1d6

Browse files
committed
fix(auth): standing grants count as claims in the one-step door's closing rule
The allow-list also requires that the user holds no sys_api_key row and no sys_oauth_consent row, revoked or not. A missing table holds no rows; a failed read answers sign_in as grant_unreadable. Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 0e8a0d3 commit 518f1d6

4 files changed

Lines changed: 133 additions & 14 deletions

File tree

‎.changeset/34257-one-step-invitation-acceptance.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ Metadata-protocol: none
1414

1515
- **The invitation mail carries a mailbox proof.** The accept link in the mail carries a single-use proof bound to the invitation, its address and its expiry; a resend retires it. The proof is never at rest in clear, the stored mail row never holds the proof, and the console's copy-link action answers the link without it. The invitation mail is sent inline, never through the durable mail queue, because the queue delivers from the stored row.
1616
- **One door redeems it.** `POST /api/v1/auth/organization/accept-invitation-one-step` takes the invitation id, the proof, a name and a password. In one request it creates the account (or sets the password of an account whose address is not verified, ending every session that account had with the reason a password reset records), verifies the address, accepts the invitation and signs in. The password-age stamp and the forced-change clear that every password change writes are written too. On an account whose password it replaces, the password history is consulted before the proof is spent and extended after, as the reset door does. The proof is spent only by a request that passed every gate; one server process serializes concurrent redemptions of a proof, and across server processes single use is as strong as the store's consume. A bad proof gets one `INVALID_TOKEN` refusal that does not say which check failed, and the real proof stays usable. The door is rate-limited per client network address and per invitation, and runs the sign-up gates before anything is written: email sign-up switched off, SSO-only mode, password length, complexity and breach checks, a name for a new account, and who may sign up. A refused request leaves the proof usable.
17-
- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor and no verified phone number, its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent.
17+
- **An address with an account signs in as today.** The door sets a password on an existing account only when it reads that the mailbox is the account's one claim: the address is not verified, the account's only sign-in account is its email and password one or it has none, it has no second factor, no verified phone number, no API key and no OAuth client consent, its identity source is local, and the server allows a local password here (not SSO-only, email and password on). Every other account, including one in a state no rule names, answers `sign_in`, and the proof stays unspent.
1818
- **A cloud-managed environment refuses it.** With `OS_CLOUD_MANAGED=1` the door sets no local password: a request carrying a proof answers `409 RESOURCE_CONFLICT`, the cloud-managed refusal, before the proof is read. `CLOUD_MANAGED_REFUSAL_MESSAGES` gains the door's message. A process without the variable is unaffected.
1919
- **Without the proof, a session must hold the verified invited address.** Called with a session and no proof, the door accepts only when the session's address is the invited one and verified, and otherwise answers `verify_email`. A copied link still owes the verification mail.
2020
- **`SendTemplateInput.deliverOnlyData`** (`@objectstack/spec`): render values delivered with the message and never written to the stored mail row, which gives no sign they were overlaid. Required template variables are checked against `data` alone. A send carrying them is delivered inline, never through the durable queue, so its sender gives up queued delivery where a queue is mounted. Only the server-side template send declares the key; `POST /email/send` and a script's `ctx.email.send` take a `SendEmailInput`, which has none.

‎docs/adr/0138-guest-model-anonymous-principal-doors-grants-and-organization.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -313,11 +313,11 @@ passed every gate, and one server process serializes concurrent redemptions of i
313313
as strong as the store's consume. Every proof that does not admit gets one refusal that does not say which check
314314
failed. The door sets a password on an existing account only when it reads that the mailbox is the account's one
315315
claim: the address is not verified, the account's only sign-in account is its email and password one or it has none,
316-
it has no second factor and no verified phone number, its identity source is local, and the server allows a local
317-
password here (not SSO-only, email and password on). Every other account, including one in a state no rule names,
318-
answers `sign_in`, and the proof stays unspent. A cloud-managed environment sets no local password, so there the door
319-
refuses every request that carries a proof. It carries a rate limit per client network address and per invitation,
320-
as ADR-0121 D6 requires. Enforced by
316+
it has no second factor, no verified phone number, no API key and no OAuth client consent, its identity source is
317+
local, and the server allows a local password here (not SSO-only, email and password on). Every other account,
318+
including one in a state no rule names, answers `sign_in`, and the proof stays unspent. A cloud-managed environment
319+
sets no local password, so there the door refuses every request that carries a proof. It carries a rate limit per
320+
client network address and per invitation, as ADR-0121 D6 requires. Enforced by
321321
`packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts#buildInvitationProofDoorPlugin`, ledgered in
322322
`packages/plugins/plugin-auth/src/auth-route-ledger.ts`. It is a better-auth endpoint, so it rides the `/auth`
323323
catch-all, which no route table lists door by door: the anonymous sweep's classification names it under class 2 as a

‎packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts‎

Lines changed: 64 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,23 @@
6060
* The door sets a password on an existing account only when it reads that the
6161
* mailbox is the account's one claim: the address is not verified, the
6262
* account's only sign-in account is its email and password one or it has
63-
* none, it has no second factor and no verified phone number, its identity
64-
* source is local, and the server allows a local password here (not SSO-only,
65-
* email and password on). Every other account, including one in a state no
66-
* rule names, answers `sign_in`, and the proof stays unspent.
63+
* none, it has no second factor, no verified phone number, no API key and no
64+
* OAuth client consent, its identity source is local, and the server allows a
65+
* local password here (not SSO-only, email and password on). Every other
66+
* account, including one in a state no rule names, answers `sign_in`, and the
67+
* proof stays unspent.
6768
*
6869
* The judge, {@link oneStepSignInState}, is an allow-list: it lets the
6970
* password be set only when every value it reads is positively the one that
7071
* carries no other claim, and a value no rule names answers `sign_in` as
7172
* `unrecognised`. Its reasons are {@link ONE_STEP_SIGN_IN_STATES}; the card's
7273
* test pins one case per reason.
7374
*
75+
* Standing grants count as claims ({@link readStandingGrant}): any
76+
* `sys_api_key` or `sys_oauth_consent` row of the user, revoked or not,
77+
* answers `sign_in`. A table that does not exist holds no rows; a read that
78+
* fails answers `sign_in` as `grant_unreadable`.
79+
*
7480
* An account that passes gets the typed password in place of its own, and
7581
* every one of its sessions is revoked with the reason a password reset
7682
* records (`session-tombstone.ts`). The password history is consulted before
@@ -91,11 +97,12 @@
9197
*/
9298

9399
import { isCloudManaged } from '@objectstack/core';
100+
import { isMissingTableError } from '@objectstack/types';
94101
import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js';
95102
import { incrementFixedWindow, InProcessCounterStore, type CounterStore } from './rate-limit-storage.js';
96103
import { readRequestClientAddress } from './request-client-address.js';
97104
import { isPendingSsoSource } from './pending-sso-marker.js';
98-
import { isIdpProvisionedSource, readUserSource } from './sso-only-local-password.js';
105+
import { isIdpProvisionedSource, readUserSource, type UserSourceReader } from './sso-only-local-password.js';
99106

100107
/** The door's path, under the auth mount. */
101108
export const ACCEPT_INVITATION_ONE_STEP_PATH = '/organization/accept-invitation-one-step';
@@ -236,6 +243,12 @@ export const ONE_STEP_SIGN_IN_STATES = [
236243
'second_factor',
237244
/** The account has a verified phone number. */
238245
'verified_phone',
246+
/** The account holds an API key, revoked or not. */
247+
'api_key',
248+
/** The account holds an OAuth client consent, revoked or not. */
249+
'oauth_consent',
250+
/** The account's standing grants cannot be read. */
251+
'grant_unreadable',
239252
/** The account is provisioned by an identity provider. */
240253
'idp_provisioned',
241254
/** The account is waiting for its first single sign-on. */
@@ -260,6 +273,35 @@ function isOff(value: unknown): boolean {
260273
return value === false || value === null || value === undefined;
261274
}
262275

276+
/** The objects whose rows are a user's standing grants, each read by `user_id`. */
277+
export const STANDING_GRANT_OBJECTS = ['sys_api_key', 'sys_oauth_consent'] as const;
278+
279+
/** Whether a user holds any row of one standing-grant object; `ok: false` when it cannot be read. */
280+
export type StandingGrantReading = { ok: true; held: boolean } | { ok: false };
281+
282+
const SYSTEM_READ = { context: { isSystem: true, positions: [], permissions: [] } } as const;
283+
284+
/**
285+
* Does `userId` hold any row of `object`, revoked or not? One indexed read by
286+
* `user_id`, `id` only, as the system. A table that does not exist holds no
287+
* rows; any other failure, or no read surface, is `ok: false`.
288+
*/
289+
export async function readStandingGrant(
290+
engine: UserSourceReader | undefined,
291+
object: (typeof STANDING_GRANT_OBJECTS)[number],
292+
userId: string,
293+
): Promise<StandingGrantReading> {
294+
if (!engine?.find) return { ok: false };
295+
try {
296+
const rows = await engine.find(object, { where: { user_id: userId }, fields: ['id'], limit: 1 }, SYSTEM_READ);
297+
if (!Array.isArray(rows)) return { ok: false };
298+
return { ok: true, held: rows.length > 0 };
299+
} catch (e) {
300+
if (isMissingTableError(e, object)) return { ok: true, held: false };
301+
return { ok: false };
302+
}
303+
}
304+
263305
/** What the judge reads of an existing account and the server. */
264306
export interface OneStepAccountReading {
265307
/** `user.emailVerified`, as stored. */
@@ -270,6 +312,10 @@ export interface OneStepAccountReading {
270312
twoFactorEnabled: unknown;
271313
/** `user.phoneNumberVerified`, as stored (absent without the plugin). */
272314
phoneNumberVerified: unknown;
315+
/** Any `sys_api_key` row of the user ({@link readStandingGrant}). */
316+
apiKeys: StandingGrantReading;
317+
/** Any `sys_oauth_consent` row of the user ({@link readStandingGrant}). */
318+
oauthConsents: StandingGrantReading;
273319
/** `sys_user.source`, or `ok: false` when it cannot be read. */
274320
source: { ok: true; value: string | null } | { ok: false };
275321
/** SSO-only mode. */
@@ -289,6 +335,9 @@ export function oneStepSignInState(account: OneStepAccountReading): OneStepSignI
289335
if (!account.accountProviders.every((providerId) => providerId === 'credential')) return 'linked_provider';
290336
if (!isOff(account.twoFactorEnabled)) return account.twoFactorEnabled === true ? 'second_factor' : 'unrecognised';
291337
if (!isOff(account.phoneNumberVerified)) return account.phoneNumberVerified === true ? 'verified_phone' : 'unrecognised';
338+
if (!account.apiKeys.ok || !account.oauthConsents.ok) return 'grant_unreadable';
339+
if (account.apiKeys.held !== false) return 'api_key';
340+
if (account.oauthConsents.held !== false) return 'oauth_consent';
292341
if (!account.source.ok) return 'source_unreadable';
293342
const source = account.source.value;
294343
if (!LOCAL_SOURCES.has(source)) {
@@ -406,12 +455,21 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo
406455
const found = await internal.findUserByEmail(email, { includeAccounts: true });
407456
const existing = found?.user;
408457
if (existing) {
458+
const engine = host.getDataEngine() as UserSourceReader | undefined;
459+
const userId = String(existing.id);
460+
const [apiKeys, oauthConsents, source] = await Promise.all([
461+
readStandingGrant(engine, 'sys_api_key', userId),
462+
readStandingGrant(engine, 'sys_oauth_consent', userId),
463+
readUserSource(engine, userId),
464+
]);
409465
const state = oneStepSignInState({
410466
emailVerified: existing.emailVerified,
411467
accountProviders: (found.accounts ?? []).map((a: any) => a?.providerId),
412468
twoFactorEnabled: existing.twoFactorEnabled,
413469
phoneNumberVerified: existing.phoneNumberVerified,
414-
source: await readUserSource(host.getDataEngine() as never, String(existing.id)),
470+
apiKeys,
471+
oauthConsents,
472+
source,
415473
ssoOnly: host.isSsoOnlyMode(),
416474
emailPasswordEnabled: ctx.context.options.emailAndPassword?.enabled,
417475
});

‎packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -458,8 +458,18 @@ describe('#34257 — a signed-in return accepts only a verified address', () =>
458458

459459

460460
// The tables a redemption writes: the account, its credential, its sessions,
461-
// the membership, the invitation and the proof row.
462-
const WRITTEN_TABLES = ['sys_user', 'sys_account', 'sys_session', 'sys_member', 'sys_invitation', 'sys_verification'];
461+
// the membership, the invitation and the proof row; and the standing grants
462+
// the judge reads, which nothing here writes.
463+
const WRITTEN_TABLES = [
464+
'sys_user',
465+
'sys_account',
466+
'sys_session',
467+
'sys_member',
468+
'sys_invitation',
469+
'sys_verification',
470+
'sys_api_key',
471+
'sys_oauth_consent',
472+
];
463473
const writtenState = (engine: MemoryEngine) =>
464474
JSON.stringify(WRITTEN_TABLES.map((table) => [table, engine.tables.get(table) ?? []]));
465475

@@ -661,6 +671,16 @@ describe('#34257 — the door sets a password only where the mailbox is the acco
661671
/** Put the account into the state, and answer how to take it out again. */
662672
enter(booted: Booted, email: string): Promise<() => Promise<void> | void>;
663673
}
674+
const findThrowsFor = (engine: MemoryEngine, object: string, error: Error) => {
675+
const find = engine.find.bind(engine);
676+
engine.find = async (name: string, q: any = {}) => {
677+
if (name === object) throw error;
678+
return find(name, q);
679+
};
680+
return () => {
681+
engine.find = find;
682+
};
683+
};
664684
const findThrowsForSource = (engine: MemoryEngine) => {
665685
const find = engine.find.bind(engine);
666686
engine.find = async (name: string, q: any = {}) => {
@@ -710,6 +730,26 @@ describe('#34257 — the door sets a password only where the mailbox is the acco
710730
};
711731
},
712732
},
733+
// A standing grant counts as a claim, a revoked one included.
734+
api_key: {
735+
enter: async ({ engine }, email) => {
736+
await engine.insert('sys_api_key', { id: `key_${email}`, user_id: userRow(engine, email)!.id, revoked: true });
737+
return () => {
738+
engine.tables.set('sys_api_key', (engine.tables.get('sys_api_key') ?? []).filter((k) => k.id !== `key_${email}`));
739+
};
740+
},
741+
},
742+
oauth_consent: {
743+
enter: async ({ engine }, email) => {
744+
await engine.insert('sys_oauth_consent', { id: `consent_${email}`, user_id: userRow(engine, email)!.id, client_id: 'client_34257', scopes: '["openid"]' });
745+
return () => {
746+
engine.tables.set('sys_oauth_consent', (engine.tables.get('sys_oauth_consent') ?? []).filter((c) => c.id !== `consent_${email}`));
747+
};
748+
},
749+
},
750+
grant_unreadable: {
751+
enter: async ({ engine }) => findThrowsFor(engine, 'sys_oauth_consent', new Error('store unavailable')),
752+
},
713753
idp_provisioned: {
714754
enter: async ({ engine }, email) => {
715755
userRow(engine, email)!.source = 'idp_provisioned';
@@ -759,6 +799,8 @@ describe('#34257 — the door sets a password only where the mailbox is the acco
759799
accountProviders: ['credential'],
760800
twoFactorEnabled: false,
761801
phoneNumberVerified: undefined,
802+
apiKeys: { ok: true, held: false },
803+
oauthConsents: { ok: true, held: false },
762804
source: { ok: true, value: 'env_native' },
763805
ssoOnly: false,
764806
emailPasswordEnabled: true,
@@ -778,6 +820,10 @@ describe('#34257 — the door sets a password only where the mailbox is the acco
778820
['a second-factor flag stored in no form the judge reads', { twoFactorEnabled: 'true' }, 'unrecognised'],
779821
['a verified phone number', { phoneNumberVerified: true }, 'verified_phone'],
780822
['a phone flag stored in no form the judge reads', { phoneNumberVerified: 1 }, 'unrecognised'],
823+
['an API key', { apiKeys: { ok: true, held: true } }, 'api_key'],
824+
['an OAuth client consent', { oauthConsents: { ok: true, held: true } }, 'oauth_consent'],
825+
['API keys that cannot be read', { apiKeys: { ok: false } }, 'grant_unreadable'],
826+
['OAuth client consents that cannot be read', { oauthConsents: { ok: false } }, 'grant_unreadable'],
781827
['an identity-provider source', { source: { ok: true, value: 'idp_provisioned' } }, 'idp_provisioned'],
782828
['a pending single sign-on', { source: { ok: true, value: 'idp_pending' } }, 'pending_sso'],
783829
['an unreadable source', { source: { ok: false } }, 'source_unreadable'],
@@ -789,6 +835,21 @@ describe('#34257 — the door sets a password only where the mailbox is the acco
789835
expect(oneStepSignInState({ ...ALLOWED, ...change })).toBe(reason);
790836
});
791837

838+
it('a grant table that does not exist holds no grant: the account is accepted', async () => {
839+
const booted = await boot();
840+
const { engine, manager, invite } = booted;
841+
const email = 'grants-absent@example.com';
842+
const { invitation, proof } = await invite(email);
843+
await signUp(manager, engine, email);
844+
const leaveKeys = findThrowsFor(engine, 'sys_api_key', new Error('SQLITE_ERROR: no such table: sys_api_key'));
845+
findThrowsFor(engine, 'sys_oauth_consent', new Error('SQLITE_ERROR: no such table: sys_oauth_consent'));
846+
try {
847+
await expectAccepted(await door(manager, { invitationId: invitation.id, proof, name: 'G', password: NEW_PASSWORD }));
848+
} finally {
849+
leaveKeys();
850+
}
851+
});
852+
792853
it('every state the closing rule names has a case, and no case names another state', () => {
793854
expect(Object.keys(CASES).sort()).toEqual([...ONE_STEP_SIGN_IN_STATES].sort());
794855
});

0 commit comments

Comments
 (0)