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
35 changes: 35 additions & 0 deletions docs/SUPPORT_COMPOSITION.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,45 @@ with no default and styles the two modes differently. Mail / outbound
notification is still deferred (Task 10) — staff reply omits `notification`
like customer create/reply.

### Role administration (`/api/admin/…`)

Gated on the stored `Admin` role (`@pegma/authorization-admin`); the host
checks permissions before calling the service, which never re-checks its own
callers.

| Method | Path | Notes |
| --- | --- | --- |
| `GET` | `/api/admin/state` | `bootstrapArmed` + CSRF token |
| `POST` | `/api/admin/lookup` | One search box: body `{ query }`, resolves an email **or** a principal id |
| `GET` | `/api/admin/principals/:id` | Principal + active roles with `managedBy` |
| `GET` | `/api/admin/principals/:id/history` | Audited lifecycle timeline |
| `POST` | `/api/admin/principals/:id/roles` | Assign `Support` or `Admin` |
| `DELETE` | `/api/admin/assignments/:id` | Revoke; last-administrator guard |

**One search box, decided server-side.** `classifyLookup` treats a `@`
anywhere in the query as an email and everything else as a principal id:
Identity's one normalization function requires exactly one `@` in every
address, and principal ids never contain one. Email lookups call the
published `Identity.findUserByEmail`; the host passes the trimmed value
through **without normalizing it**, because exactly one normalization
function exists and it lives in Identity (test-pinned).

**Why the lookup is a POST.** The query can be a real person's email
address, so it stays out of URLs, referrers, and access logs; the same
choice puts CSRF and same-origin in front of the one endpoint that can
confirm an address exists. Identity's public enumeration resistance is
untouched — this path is reachable only by an authenticated `Admin` holder,
and it is rate-limited so a stolen admin session cannot harvest the
directory.

Durable rate-limit policies (separate from Identity):

- `pegma.support.ticket.create`
- `pegma.support.ticket.reply` (customer replies and staff message/note posts)
- `pegma.admin.role.mutate` (assign / revoke, 30/h per operator)
- `pegma.admin.principal.lookup` (directory lookups, 120/h per operator)

All four are swept by the same scheduled maintenance run.

## Site pages

Expand Down
95 changes: 73 additions & 22 deletions public/staff-roles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ const forbidden = document.querySelector('#roles-forbidden');
const panel = document.querySelector('#roles-panel');
const bootstrapWarning = document.querySelector('#bootstrap-warning');
const lookupForm = document.querySelector('#lookup-form');
const principalInput = document.querySelector('#lookup-principal');
const lookupInput = document.querySelector('#lookup-query');
const principalCard = document.querySelector('#principal-card');
const principalEmail = document.querySelector('#principal-email');
const principalMeta = document.querySelector('#principal-meta');
const principalMatched = document.querySelector('#principal-matched');
const roleList = document.querySelector('#role-list');
const assignForm = document.querySelector('#assign-form');
const assignRole = document.querySelector('#assign-role');
Expand Down Expand Up @@ -107,10 +108,11 @@ function renderRoles(roles) {
? 'Revoked — the guard restored the principal to keep an administrator.'
: 'Revoked.',
);
await loadPrincipal(currentPrincipal);
await refreshPrincipal();
} catch (error) {
showStatus(
MUTATION_ERRORS[error.message] ?? `Revoke failed (${error.message}).`,
MUTATION_ERRORS[error.message] ??
`Revoke failed (${error.message}).`,
true,
);
}
Expand Down Expand Up @@ -139,37 +141,84 @@ function renderHistory(events) {
}
}

async function loadPrincipal(principalId) {
const [detail, history] = await Promise.all([
api(`/api/admin/principals/${encodeURIComponent(principalId)}`),
api(`/api/admin/principals/${encodeURIComponent(principalId)}/history`),
]);
currentPrincipal = principalId;
function renderPrincipal(detail, matchedBy) {
currentPrincipal = detail.principal.principalId;
principalEmail.textContent = detail.principal.email;
principalMeta.textContent = `${detail.principal.principalId} · ${detail.principal.status} · created ${detail.principal.createdAt}`;
if (matchedBy === undefined) {
principalMatched.hidden = true;
} else {
principalMatched.textContent =
matchedBy === 'email'
? 'Matched by email address.'
: 'Matched by principal id.';
principalMatched.hidden = false;
}
renderRoles(detail.roles);
renderHistory(history.events);
principalCard.hidden = false;
}

/**
* Every load takes a ticket. A second lookup (or a refresh after a
* mutation) invalidates any in-flight one, so a slow response can never
* paint its principal's history under a newer principal's details.
*/
let loadTicket = 0;

/**
* Fetch details and history, then render BOTH or NEITHER: the card only
* becomes interactive once the pair belongs to the same principal.
*/
async function loadPrincipal(fetchDetail) {
const ticket = (loadTicket += 1);
const detail = await fetchDetail();
const id = encodeURIComponent(detail.principal.principalId);
const history = await api(`/api/admin/principals/${id}/history`);
if (ticket !== loadTicket) {
return;
}
renderPrincipal(detail, detail.matchedBy);
renderHistory(history.events);
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
}

/** One box: the worker decides email vs principal id. */
async function resolvePrincipal(query) {
await loadPrincipal(() =>
api('/api/admin/lookup', {
method: 'POST',
body: JSON.stringify({ query }),
}),
);
}

/** Re-read the already-resolved principal after a mutation. */
async function refreshPrincipal() {
const id = encodeURIComponent(currentPrincipal);
await loadPrincipal(() => api(`/api/admin/principals/${id}`));
}

lookupForm.addEventListener('submit', async (event) => {
event.preventDefault();
const principalId = principalInput.value.trim();
if (principalId === '') {
const query = lookupInput.value.trim();
if (query === '') {
return;
}
showStatus('Loading principal…');
showStatus('Looking up…');
try {
await loadPrincipal(principalId);
await resolvePrincipal(query);
showStatus('Ready.');
} catch (error) {
principalCard.hidden = true;
showStatus(
error.status === 404
? 'No account with that principal id.'
: `Lookup failed (${error.message}).`,
true,
);
if (error.status === 404) {
showStatus('No account matches that email or principal id.', true);
} else if (error.status === 400) {
showStatus(
'That does not look like an email address or a principal id.',
true,
);
} else {
showStatus(`Lookup failed (${error.message}).`, true);
}
}
});

Expand All @@ -181,7 +230,9 @@ assignForm.addEventListener('submit', async (event) => {
const role = assignRole.value;
if (
role === 'Admin' &&
!window.confirm('Grant the Admin role? Admins can change all role assignments.')
!window.confirm(
'Grant the Admin role? Admins can change all role assignments.',
)
) {
return;
}
Expand All @@ -191,7 +242,7 @@ assignForm.addEventListener('submit', async (event) => {
{ method: 'POST', body: JSON.stringify({ role }) },
);
showStatus(`Assigned ${role}.`);
await loadPrincipal(currentPrincipal);
await refreshPrincipal();
} catch (error) {
showStatus(
MUTATION_ERRORS[error.message] ?? `Assign failed (${error.message}).`,
Expand Down
12 changes: 6 additions & 6 deletions src/pages/staff/roles.astro
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,27 @@ import Base from '../../layouts/Base.astro';
</div>

<form id="lookup-form" class="account-form">
<label for="lookup-principal">Principal id</label>
<label for="lookup-query">Email or principal id</label>
<input
id="lookup-principal"
name="principal"
id="lookup-query"
name="query"
type="text"
required
autocomplete="off"
placeholder="a41f406e-…"
placeholder="person@example.com or a41f406e-…"
/>
<div class="account-inline">
<button type="submit">Look up</button>
</div>
<p class="form-note">
Exact Identity principal id. Principal search by email stays outside
this surface.
Exact match either way — the surface works out which you typed.
</p>
</form>

<section id="principal-card" hidden>
<h3 id="principal-email"></h3>
<p id="principal-meta" class="form-note"></p>
<p id="principal-matched" class="form-note" hidden></p>

<h4>Active roles</h4>
<ul id="role-list" class="ticket-list"></ul>
Expand Down
132 changes: 130 additions & 2 deletions worker/src/admin-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createMemoryStore } from '@pegma/storage-core';
import { createSessionStore } from '@pegma/sessions';
import { fixedClock, type Logger, type PrincipalId } from '@pegma/spine';
import { describe, expect, it, vi } from 'vitest';
import { createAdminApi } from './admin-api';
import { classifyLookup, createAdminApi } from './admin-api';
import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api';
import type {
IdentityPort,
Expand All @@ -13,6 +13,7 @@ import type {
import { createRoleHolderIndex } from './role-holder-index';
import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access';
import {
createAdminLookupLimiter,
createAdminMutationLimiter,
createSupportRuntime,
} from './support-desk';
Expand Down Expand Up @@ -49,6 +50,12 @@ function identityFor(
emailVerified: true,
} satisfies VerifiedIdentityClaims;
}),
findUserByEmail: vi.fn(async (email: string) => {
for (const user of users.values()) {
if (user.email === email.trim().toLowerCase()) return user;
}
return null;
}),
getUser: vi.fn(
async (principalId: PrincipalId) => users.get(principalId) ?? null,
),
Expand Down Expand Up @@ -132,9 +139,10 @@ function fixture(options: { bootstrapPrincipals?: readonly PrincipalId[] } = {})
roleStore: runtime.roleStore,
holderIndex: createRoleHolderIndex(store),
mutationLimiter: createAdminMutationLimiter(store, clock),
lookupLimiter: createAdminLookupLimiter(store, clock),
bootstrapPrincipals: new Set(options.bootstrapPrincipals ?? []),
});
return { api, sessions, roleStore: runtime.roleStore };
return { api, sessions, identity, roleStore: runtime.roleStore };
}

/** Seed the first administrator the way the bootstrap touch would. */
Expand All @@ -153,6 +161,126 @@ async function bootstrappedAdmin(
return { ...world, auth };
}

describe('classifyLookup', () => {
it('routes anything containing @ to email and everything else to id', () => {
expect(classifyLookup('person@example.test')).toBe('email');
expect(classifyLookup('a41f406e-6e58-4090-b5b9-62bf7a8ab65d')).toBe(
'principalId',
);
// Identity's normalization rejects malformed addresses; the classifier
// only decides which endpoint answers, never whether input is valid.
expect(classifyLookup('@')).toBe('email');
expect(classifyLookup('not-an-email')).toBe('principalId');
});
});

describe('one search box', () => {
it('resolves a principal id', async () => {
const { api, auth } = await bootstrappedAdmin();
const response = await api(
mutate('POST', '/api/admin/lookup', auth, { query: admin }),
);
expect(response.status).toBe(200);
const body = (await response.json()) as {
matchedBy: string;
principal: { principalId: string; email: string };
roles: readonly { role: string }[];
};
expect(body.matchedBy).toBe('principalId');
expect(body.principal.principalId).toBe(admin);
expect(body.roles.map((role) => role.role)).toEqual([ADMIN_ROLE]);
});

it('resolves an email and hands Identity the value verbatim', async () => {
const { api, auth, identity } = await bootstrappedAdmin();
const response = await api(
mutate('POST', '/api/admin/lookup', auth, {
query: ' Member@Example.TEST ',
}),
);
expect(response.status).toBe(200);
const body = (await response.json()) as {
matchedBy: string;
principal: { principalId: string };
};
expect(body.matchedBy).toBe('email');
expect(body.principal.principalId).toBe(member);
// Exactly one email normalization function exists and it lives in
// Identity: the host trims the text-box value and passes it through
// untouched — no host-side lowercasing.
expect(identity.findUserByEmail).toHaveBeenCalledWith('Member@Example.TEST');
});

it('answers 404 for an unknown principal and 400 for unusable input', async () => {
const { api, auth } = await bootstrappedAdmin();
expect(
(
await api(
mutate('POST', '/api/admin/lookup', auth, {
query: 'nobody@example.test',
}),
)
).status,
).toBe(404);
expect(
(await api(mutate('POST', '/api/admin/lookup', auth, { query: ' ' })))
.status,
).toBe(400);
expect(
(
await api(
mutate('POST', '/api/admin/lookup', auth, {
query: `${'x'.repeat(320)}@example.test`,
}),
)
).status,
).toBe(400);
});

it('maps an Identity input rejection to 400, not 500', async () => {
const world = await bootstrappedAdmin();
world.identity.findUserByEmail = vi.fn(async () => {
throw Object.assign(new Error('bad'), { code: 'invalid_input' });
});
const response = await world.api(
mutate('POST', '/api/admin/lookup', world.auth, { query: 'a@b@c' }),
);
expect(response.status).toBe(400);
expect(await response.json()).toEqual({ error: 'invalid_query' });
});

it('is gated on the Admin role and CSRF like every other admin route', async () => {
const { api, sessions } = fixture();
const nobody = await sessionCookie(sessions, member, 'q'.repeat(43));
expect(
(
await api(
mutate(
'POST',
'/api/admin/lookup',
{ cookie: nobody.cookie, csrfToken: nobody.csrfToken },
{ query: member },
),
)
).status,
).toBe(403);

// A separate world: its session store owns the admin cookie below.
const bootstrapped = await bootstrappedAdmin();
const noCsrf = new Request('https://pegma.dev/api/admin/lookup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Origin: IDENTITY_ISSUER,
'Sec-Fetch-Site': 'same-origin',
Cookie: bootstrapped.auth.cookie,
},
body: JSON.stringify({ query: admin }),
});
expect((await bootstrapped.api(noCsrf)).status).toBe(403);
});
});

describe('admin API access', () => {
it('requires authentication and the Admin role, fail-closed order', async () => {
const { api, sessions } = fixture();
Expand Down
Loading