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
9 changes: 8 additions & 1 deletion services/platform/backend/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,9 @@ export function createAuth(config: AuthConfig) {
// afterDeleteTeam hook retires the scopes and audits the deletion.
disabledPaths: [
...OIDC_DISABLED_PATHS,
// Writes a session's additional fields from a request body; the app
// never calls it, and those fields are the server's (below).
'/update-session',
'/organization/leave',
'/organization/add-team-member',
'/organization/remove-team-member',
Expand Down Expand Up @@ -843,14 +846,18 @@ export function createAuth(config: AuthConfig) {
additionalFields: {
// The role a trusted-headers proxy asserted at sign-in, and the ONE
// organization it holds for; the org middleware applies the override
// to that organization only (`backend/auth/org.ts`).
// to that organization only (`backend/auth/org.ts`). Only the
// trusted-headers door writes them (`domains/sso/trusted-headers.ts`,
// in SQL), never a request body.
trustedRole: {
type: 'string' as const,
required: false,
input: false,
},
trustedOrganizationId: {
type: 'string' as const,
required: false,
input: false,
},
},
},
Expand Down
75 changes: 75 additions & 0 deletions services/platform/backend/auth/org.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Hono } from 'hono';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { trustedRoleHolds } from '../domains/trusted_headers/service.ts';
import { evaluateTwoFactorEnforcement } from '../domains/two_factor/service.ts';
import {
MembershipError,
requireOrganizationMembership,
Expand All @@ -11,6 +13,12 @@ vi.mock('./membership.ts', async (original) => ({
...(await original<typeof import('./membership.ts')>()),
requireOrganizationMembership: vi.fn(),
}));
vi.mock('../domains/trusted_headers/service.ts', () => ({
trustedRoleHolds: vi.fn(),
}));
vi.mock('../domains/two_factor/service.ts', () => ({
evaluateTwoFactorEnforcement: vi.fn(),
}));
afterEach(() => {
vi.clearAllMocks();
});
Expand Down Expand Up @@ -48,3 +56,70 @@ describe('organization membership error envelope', () => {
},
);
});

describe('a trusted-headers role on the session [THDR-R10]', () => {
/** The role the gate settles on for a member whose seat is `seat` and
* whose session carries `session`. */
async function roleFor(
seat: string,
session: Record<string, unknown>,
): Promise<string> {
vi.mocked(requireOrganizationMembership).mockResolvedValue({
member: {
id: 'member-a',
organizationId: 'org-a',
userId: 'user-a',
role: seat,
},
organizationIds: ['org-a'],
});
vi.mocked(evaluateTwoFactorEnforcement).mockResolvedValue({
decision: 'allowed',
} as never);
const app = new Hono<OrgEnv>();
app.use(async (c, next) => {
c.set('sessionBundle', {
user: { id: 'user-a', email: 'a@example.invalid', name: 'A' },
session: { id: 'session-a', ...session },
});
await next();
});
app.use(requireOrgMember({} as never));
app.get('/me', (c) => c.json({ role: c.get('orgMember').role }));
const response = await app.request('/me?orgId=org-a');
const body = (await response.json()) as { role: string };
return body.role;
}

it('applies the proxy role while the organization still allows it', async () => {
vi.mocked(trustedRoleHolds).mockResolvedValue(true);
await expect(
roleFor('member', {
trustedRole: 'Editor',
trustedOrganizationId: 'org-a',
}),
).resolves.toBe('editor');
expect(trustedRoleHolds).toHaveBeenCalledWith({}, 'org-a', 'editor');
});

it("falls back to the member's own seat when the role could not have been asserted", async () => {
vi.mocked(trustedRoleHolds).mockResolvedValue(false);
await expect(
roleFor('member', {
trustedRole: 'owner',
trustedOrganizationId: 'org-a',
}),
).resolves.toBe('member');
});

it('asks nothing for a session without a trusted role, or one bound to another organization', async () => {
await expect(roleFor('member', {})).resolves.toBe('member');
await expect(
roleFor('member', {
trustedRole: 'admin',
trustedOrganizationId: 'org-b',
}),
).resolves.toBe('member');
expect(trustedRoleHolds).not.toHaveBeenCalled();
});
});
14 changes: 9 additions & 5 deletions services/platform/backend/auth/org.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type AppAction,
type AppSubject,
} from '../../lib/permissions/ability.ts';
import { trustedRoleHolds } from '../domains/trusted_headers/service.ts';
import { evaluateTwoFactorEnforcement } from '../domains/two_factor/service.ts';
import {
MembershipError,
Expand Down Expand Up @@ -73,14 +74,17 @@ export function requireOrgMember<E extends OrgEnv>(
trustedOrg === orgId
? trustedRaw.toLowerCase().trim()
: undefined;
// ...and only while the organization still lets a proxy assert that
// role: a role no proxy could have stamped is no override.
const overridden =
trustedRole !== undefined &&
trustedRole !== '' &&
member.role !== 'owner' &&
(await trustedRoleHolds(sql, orgId, trustedRole));
c.set('orgId', orgId);
c.set(
'orgMember',
trustedRole !== undefined &&
trustedRole !== '' &&
member.role !== 'owner'
? { ...member, role: trustedRole }
: member,
overridden ? { ...member, role: trustedRole } : member,
);
// Server-side org 2FA enforcement: a 'blocked' decision (policy enforced,
// user not enrolled, past grace) must actually WITHHOLD authority here —
Expand Down
78 changes: 78 additions & 0 deletions services/platform/backend/auth/session-trust-fields.integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Real-Postgres proof that the session's trusted-headers fields are the
* server's alone. `trustedRole` and `trustedOrganizationId` carry the role
* an authenticating proxy asserted at sign-in, and the org gate applies that
* role in that one organization (`auth/org.ts`). No request body writes
* them, and the gate honours a trusted role only while the organization
* lets a proxy assert it.
*/
import type { Sql } from 'postgres';

export async function checkSessionTrustFieldsAreServerOnly(
sql: Sql,
base: string,
ctx: { orgId: string },
// A plain member of the organization, signed in with a password.
member: { cookie: string; userId: string },
record: (name: string, ok: boolean, detail: string) => void,
): Promise<void> {
const attempt = await fetch(`${base}/api/auth/update-session`, {
method: 'POST',
headers: {
'content-type': 'application/json',
origin: base,
cookie: member.cookie,
},
body: JSON.stringify({
trustedRole: 'owner',
trustedOrganizationId: ctx.orgId,
}),
});
const stored = await sql<
{ trustedRole: string | null; trustedOrganizationId: string | null }[]
>`
SELECT "trustedRole", "trustedOrganizationId" FROM "session"
WHERE "userId" = ${member.userId}
`;
// An admin-only read: the member must still be refused.
const adminRead = await fetch(
`${base}/api/app/audit-logs?orgId=${encodeURIComponent(ctx.orgId)}`,
{ headers: { cookie: member.cookie } },
);
// A row carrying a role no proxy could assert counts for nothing: the gate
// applies a trusted role only while the organization lets a proxy assert
// it, and nobody may assert owner.
await sql`
UPDATE "session" SET "trustedRole" = 'owner',
"trustedOrganizationId" = ${ctx.orgId}
WHERE "userId" = ${member.userId}
`;
const forgedRead = await fetch(
`${base}/api/app/audit-logs?orgId=${encodeURIComponent(ctx.orgId)}`,
{ headers: { cookie: member.cookie } },
);
await sql`
UPDATE "session" SET "trustedRole" = NULL, "trustedOrganizationId" = NULL
WHERE "userId" = ${member.userId}
`;
// Boot signed out, once, every session that carried a trusted role.
const repaired = await sql<{ name: string }[]>`
SELECT name FROM app.boot_repairs
WHERE name = 'revoke-client-written-trust-fields'
`;
record(
'auth: a trusted role no proxy could assert grants nothing, and boot reset such sessions once',
forgedRead.status === 403 && repaired.length === 1,
`owner in the session row → admin-only read ${forgedRead.status} (want 403), boot repair recorded=${repaired.length} (want 1)`,
);
record(
"auth: a member cannot write the session's trusted role or organization",
attempt.status >= 400 &&
stored.length > 0 &&
stored.every(
(row) => row.trustedRole === null && row.trustedOrganizationId === null,
) &&
adminRead.status === 403,
`update-session → ${attempt.status} (want 4xx), stored=${JSON.stringify(stored)}, admin-only read → ${adminRead.status} (want 403)`,
);
}
37 changes: 37 additions & 0 deletions services/platform/backend/db/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,42 @@ async function verifyProvisionedAccounts(
}
}

/** The `app.boot_repairs` name of {@link revokeClientWrittenTrustFields}. */
const REVOKE_CLIENT_TRUST_FIELDS = 'revoke-client-written-trust-fields';

/**
* Sign out, once, every session that carries trusted-headers fields, so each
* is minted again by the trusted-headers door — the only writer of those
* fields from now on (`backend/auth/auth.ts`). A proxy's users get a fresh
* session through the proxy's sign-in hand-off on their next visit; anyone
* else signs in again.
*
* Recorded in `app.boot_repairs` (0193) so it runs once per database: the
* sessions are Better Auth's, and exist only after its migrator ran.
*/
async function revokeClientWrittenTrustFields(
sql: postgres.Sql,
log: (message: string) => void,
): Promise<void> {
await sql.begin(async (tx) => {
const recorded = await tx`
INSERT INTO app.boot_repairs (name) VALUES (${REVOKE_CLIENT_TRUST_FIELDS})
ON CONFLICT (name) DO NOTHING
RETURNING name
`;
if (recorded.length === 0) return;
const revoked = await tx`
DELETE FROM "session"
WHERE "trustedRole" IS NOT NULL OR "trustedOrganizationId" IS NOT NULL
`;
if (revoked.count > 0) {
log(
`[backend] reset ${revoked.count} session(s) carrying a trusted role`,
);
}
});
}

/**
* A numbered `.ts` migration: a DATA migration whose decision is a rule the
* application already owns — a backfill keyed on which files an extractor
Expand Down Expand Up @@ -361,6 +397,7 @@ async function migrateOnce(
}
await defaultTeamMemberCount(sql);
await verifyProvisionedAccounts(sql, log);
await revokeClientWrittenTrustFields(sql, log);
}
// The e-mail index builds concurrently, which must not happen under
// this lock (see `indexUserEmailLower`).
Expand Down
11 changes: 11 additions & 0 deletions services/platform/backend/db/migrations/0193_boot_repairs.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- 0.5 app migration 0193: the ledger of one-time boot repairs.
--
-- A repair of Better Auth's own rows cannot be a numbered migration: these
-- files run before Better Auth creates its tables on a fresh database, and
-- the tables are not the app's to reshape. Boot runs such a repair after
-- Better Auth's migrator, under the same migration lock (`db/migrate.ts`),
-- and records its name here so it runs once per database.
CREATE TABLE IF NOT EXISTS app.boot_repairs (
name text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
);
53 changes: 53 additions & 0 deletions services/platform/backend/domains/trusted_headers/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
setTrustedHeaderSettings,
TRUSTED_HEADER_KEY_MARKER,
TrustedHeadersError,
trustedRoleHolds,
} from './service.ts';

/**
Expand Down Expand Up @@ -368,3 +369,55 @@ describe('TrustedHeadersError', () => {
expect(error.status).toBe(404);
});
});

describe('trustedRoleHolds — a session keeps a proxy role only while it could be asserted [THDR-R10]', () => {
const settings = (row: object | undefined) =>
fakeSql((text) =>
text.includes('FROM app.trusted_header_settings')
? row === undefined
? []
: [row]
: undefined,
);

it('never honours owner, and asks nothing for it', async () => {
const fake = settings({
enabled: true,
maxAssertedRole: 'admin',
hasKey: true,
});
await expect(trustedRoleHolds(fake.sql, 'org-1', 'owner')).resolves.toBe(
false,
);
expect(fake.queries).toHaveLength(0);
});

it('honours a role up to the ceiling while the switch is on and a key lives', async () => {
const fake = settings({
enabled: true,
maxAssertedRole: 'developer',
hasKey: true,
});
await expect(
trustedRoleHolds(fake.sql, 'org-1', 'developer'),
).resolves.toBe(true);
await expect(trustedRoleHolds(fake.sql, 'org-1', 'editor')).resolves.toBe(
true,
);
await expect(trustedRoleHolds(fake.sql, 'org-1', 'admin')).resolves.toBe(
false,
);
});

it('honours nothing while paused, without a live key, or never set up', async () => {
for (const row of [
{ enabled: false, maxAssertedRole: 'admin', hasKey: true },
{ enabled: true, maxAssertedRole: 'admin', hasKey: false },
undefined,
]) {
await expect(
trustedRoleHolds(settings(row).sql, 'org-1', 'member'),
).resolves.toBe(false);
}
});
});
Loading