From a7294364b96a0a5c0e875156164e7c5c381ed4af Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:23:35 +0000 Subject: [PATCH 1/4] feat(ui): name every audited action and say what location work was asked for --- ui/src/lib/api/http-audit.test.ts | 11 +++++++++++ ui/src/lib/api/http-audit.ts | 20 +++++++++++++++++++- ui/src/lib/platform/permission-catalog.ts | 10 ++++++++++ ui/src/routes/admin/audit/+page.svelte | 5 +++-- 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/ui/src/lib/api/http-audit.test.ts b/ui/src/lib/api/http-audit.test.ts index 7ebccefbf4..9c2b905039 100644 --- a/ui/src/lib/api/http-audit.test.ts +++ b/ui/src/lib/api/http-audit.test.ts @@ -51,7 +51,18 @@ describe('toAuditEntry', () => { after: '{"token_id":"t-1"}', scope: { locationId: null, subject: 'run_id=run-4' } }); + expect(entry.summary).toBe(''); expect(auditMatches(entry, { outcome: 'denied' })).toBe(false); expect(auditMatches(entry, { actor: 'scheduler/s-1', action: 'token.issued' })).toBe(true); }); + + it('says what work a location was asked for, and which run a read was of', () => { + const allowed = (action: string, after_json: Record) => + toAuditEntry({ ...base, actor: 'principal:p-1', actor_name: 'ana', action, granting_role: 'admin', scope_json: { location_id: 'loc-1', target: 'prod' }, after_json }).summary; + const work = (work: Record) => allowed('location.work_requested', { request_id: 'q-1', reason: 'plan', work }); + expect(work({ kind: 'plan', command: ['build', '--select', 'orders'], selection: ['model:orders'], settings: {} })).toBe('Plan sqb build --select orders'); + expect(work({ kind: 'sync_warehouse' })).toBe('Sync the warehouse copy'); + expect(allowed('error.read', { run_id: 'd36ac8b2-314c-46aa', found: true })).toBe('Run d36ac8b2'); + expect(allowed('output.read', { run_id: 'd36ac8b2-314c-46aa', found: false })).toBe('Run d36ac8b2, not found'); + }); }); diff --git a/ui/src/lib/api/http-audit.ts b/ui/src/lib/api/http-audit.ts index 0000c6d0d3..a5226cef09 100644 --- a/ui/src/lib/api/http-audit.ts +++ b/ui/src/lib/api/http-audit.ts @@ -32,6 +32,24 @@ function scopeOf(scope: Record): AuditEntry['scope'] { }; } +const WORK: Record = { + check_connection: 'Test the warehouse connection', + sync_warehouse: 'Sync the warehouse copy', + evaluate_sensor: 'Evaluate a sensor' +}; + +/** What an allowed action did, from the fields the server records with it; empty when nothing reads better than the raw change. */ +function allowedSummary(action: string, after: Record): string { + if (action === 'location.work_requested') { + const work = fieldsOf(after.work); + const kind = textOf(work.kind) ?? ''; + if (kind === 'plan' && Array.isArray(work.command)) return `Plan sqb ${work.command.join(' ')}`; + return WORK[kind] ?? kind; + } + const run = textOf(after.run_id); + return run ? `Run ${run.slice(0, 8)}${after.found === false ? ', not found' : ''}` : ''; +} + /** A denial is listed under the action it refused, with its decision ID and reason. */ export function toAuditEntry(wire: Wire['SecurityAuditEvent']): AuditEntry { const denied = wire.action === DENIED; @@ -48,7 +66,7 @@ export function toAuditEntry(wire: Wire['SecurityAuditEvent']): AuditEntry { grantingRole: denied ? null : wire.granting_role, decisionId: denied ? textOf(after.decision_id) : null, evidenceRead: wire.action === 'evidence.read', - summary: denied ? (textOf(after.reason) ?? '') : '', + summary: denied ? (textOf(after.reason) ?? '') : allowedSummary(wire.action, after), before: jsonText(wire.before_json), after: denied ? null : jsonText(wire.after_json), ip: wire.ip_address ?? '', diff --git a/ui/src/lib/platform/permission-catalog.ts b/ui/src/lib/platform/permission-catalog.ts index 749cafa393..ca8d299a86 100644 --- a/ui/src/lib/platform/permission-catalog.ts +++ b/ui/src/lib/platform/permission-catalog.ts @@ -77,20 +77,29 @@ export function requiresText(action: Capability): string { const AUDIT_ONLY: Record = { 'session.login': 'Signed in', 'admin.granted': 'Changed administrators', + 'admin.initialized': 'Set up the first administrator', 'authorization.denied': 'Denied', 'cli.login.started': 'Started CLI sign-in', 'cli.login.decided': 'Decided CLI sign-in', 'cli.login.exchanged': 'Completed CLI sign-in', + 'error.read': 'Read a node’s error', 'evidence.read': 'Read sample rows', 'job.run_requested': 'Requested a job run', 'location.created': 'Created location', + 'location.work_requested': 'Asked a location to work', 'oidc.flow.created': 'Started SSO sign-in', + 'oidc.flow.consumed': 'Finished SSO sign-in', 'oidc.authenticated': 'Signed in with SSO', + 'output.read': 'Read run output', 'password.changed': 'Changed password', 'principal.created': 'Added person', + 'principal.disabled': 'Disabled person', + 'principal.enabled': 'Enabled person', 'role.assigned': 'Changed role', + 'role.revoked': 'Removed role', 'run.acknowledged': 'Acknowledged run', 'run.acknowledgement_withdrawn': 'Withdrew acknowledgement', + 'run.adhoc_requested': 'Requested an ad-hoc run', 'run.cancel_requested': 'Requested cancel', 'run.rerun_requested': 'Requested rerun', 'session.created': 'Signed in', @@ -98,6 +107,7 @@ const AUDIT_ONLY: Record = { 'sql.read': 'Read SQL', 'token.issued': 'Issued token', 'token.revoked': 'Revoked token', + 'token.rotated': 'Rotated token', 'trigger.changed': 'Changed trigger' }; diff --git a/ui/src/routes/admin/audit/+page.svelte b/ui/src/routes/admin/audit/+page.svelte index 93f431ebce..66b045e347 100644 --- a/ui/src/routes/admin/audit/+page.svelte +++ b/ui/src/routes/admin/audit/+page.svelte @@ -91,6 +91,7 @@ {#each rows as e (e.id)} + {@const change = e.before !== null || e.after !== null ? `${e.before ?? '∅'} → ${e.after ?? '∅'}` : null} @@ -118,8 +119,8 @@ {e.grantingRole ?? '—'} {e.summary} -
- {#if e.before !== null || e.after !== null}{e.before ?? '∅'} → {e.after ?? '∅'} ·{/if} +
+ {#if change && !e.summary}{change} ·{/if} {e.requestId}
From 420967f59e0388322be079d98150b36e4d046559 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:27:34 +0000 Subject: [PATCH 2/4] feat(ui): count a large deploy's node changes by kind instead of listing them --- ui/src/lib/build-area/changes.test.ts | 32 ++++++++++++++++ ui/src/lib/build-area/changes.ts | 54 ++++++++++++++++++++++++++- ui/src/routes/+page.svelte | 6 +-- ui/src/routes/changes/+page.svelte | 26 +++++++++++-- 4 files changed, 110 insertions(+), 8 deletions(-) create mode 100644 ui/src/lib/build-area/changes.test.ts diff --git a/ui/src/lib/build-area/changes.test.ts b/ui/src/lib/build-area/changes.test.ts new file mode 100644 index 0000000000..e0fcdafd73 --- /dev/null +++ b/ui/src/lib/build-area/changes.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import type { ChangeOp, NodeChange } from '$lib/api'; +import { nodeChangeGroups, nodeChangeLine } from './changes'; + +const change = (key: string, op: ChangeOp = 'added'): NodeChange => ({ key, kind: null, op, formerKey: null, compiledOnly: false, detail: '', columns: [] }); +const many = (n: number, prefix: string, op: ChangeOp = 'added') => Array.from({ length: n }, (_, i) => change(`${prefix}:n${i}`, op)); + +describe('node change summaries', () => { + it('counts a first deploy by change and kind, largest first, in plain nouns', () => { + const nodes = [...many(3, 'model'), ...many(1200, 'audit'), change('udf:margin'), ...many(2, 'model', 'removed'), change('widget:x')]; + expect(nodeChangeGroups(nodes)).toEqual([ + { op: 'added', prefix: 'audit', count: 1200, noun: 'checks' }, + { op: 'added', prefix: 'model', count: 3, noun: 'models' }, + { op: 'removed', prefix: 'model', count: 2, noun: 'models' }, + { op: 'added', prefix: 'udf', count: 1, noun: 'function' }, + { op: 'added', prefix: 'widget', count: 1, noun: 'widget' } + ]); + expect(nodeChangeLine(nodes)).toBe('added 1,200 checks · added 3 models · removed 2 models · 2 more kinds'); + }); + + it('keeps SQL and Python hooks apart, so each kind is its own group', () => { + expect(nodeChangeGroups([change('sql_hook:a'), change('hook:b')]).map((g) => [g.prefix, g.noun])).toEqual([ + ['hook', 'Python hook'], + ['sql_hook', 'SQL hook'] + ]); + }); + + it('names the nodes when there are only a few', () => { + expect(nodeChangeLine([change('model:orders', 'changed'), change('seed:carriers')])).toBe('changed model:orders · added seed:carriers'); + expect(nodeChangeLine([])).toBe('No node changes'); + }); +}); diff --git a/ui/src/lib/build-area/changes.ts b/ui/src/lib/build-area/changes.ts index dba0fbe9de..f7da3d04ca 100644 --- a/ui/src/lib/build-area/changes.ts +++ b/ui/src/lib/build-area/changes.ts @@ -1,16 +1,66 @@ // Summaries of change-feed entries. Pure; no side effects. -import type { SnapshotChange } from '$lib/api'; +import type { ChangeOp, NodeChange, SnapshotChange } from '$lib/api'; const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; /** e.g. "3 nodes · 1 trigger · 1 role · dependencies". */ export function summarizeChange(change: SnapshotChange): string { const parts: string[] = []; - if (change.nodes.length) parts.push(count(change.nodes.length, 'node')); + if (change.nodes.length) parts.push(`${change.nodes.length.toLocaleString('en')} ${change.nodes.length === 1 ? 'node' : 'nodes'}`); const orchestration = change.orchestration.length; if (orchestration) parts.push(count(orchestration, 'job or trigger', 'jobs and triggers')); if (change.roles.length) parts.push(count(change.roles.length, 'role')); if (change.environment) parts.push('environment'); return parts.length ? parts.join(' · ') : 'No definition changes'; } + +/** A deploy lists its node changes one by one up to this many; more are counted by kind. */ +export const NODE_LIST_LIMIT = 20; + +/** Readable names for the node key prefixes a snapshot uses; an unknown prefix is shown as it is. */ +const NOUN: Record = { + model: ['model', 'models'], + audit: ['check', 'checks'], + sql_test: ['SQL test', 'SQL tests'], + sql_scenario: ['scenario', 'scenarios'], + source: ['source', 'sources'], + loader: ['loader', 'loaders'], + macro: ['macro', 'macros'], + seed: ['seed', 'seeds'], + snapshot: ['snapshot', 'snapshots'], + udf: ['function', 'functions'], + table_fn: ['table function', 'table functions'], + sql_hook: ['SQL hook', 'SQL hooks'], + hook: ['Python hook', 'Python hooks'], + materialization: ['materialization', 'materializations'] +}; + +export type NodeChangeGroup = { op: ChangeOp; prefix: string; count: number; noun: string }; + +/** A deploy's node changes counted by change and kind, largest first, e.g. 252 added models. */ +export function nodeChangeGroups(nodes: readonly NodeChange[]): NodeChangeGroup[] { + const groups = new Map(); + for (const n of nodes) { + const prefix = n.key.includes(':') ? n.key.slice(0, n.key.indexOf(':')) : 'model'; + const id = `${n.op}\u0000${prefix}`; + const group = groups.get(id) ?? { op: n.op, prefix, count: 0 }; + group.count += 1; + groups.set(id, group); + } + return [...groups.values()] + .sort((a, b) => b.count - a.count || a.prefix.localeCompare(b.prefix)) + .map(({ op, prefix, count }) => { + const [one, many] = NOUN[prefix] ?? [prefix, prefix]; + return { op, prefix, count, noun: count === 1 ? one : many }; + }); +} + +/** One line on a deploy's node changes: the first few keys, or the largest groups when there are many. */ +export function nodeChangeLine(nodes: readonly NodeChange[]): string { + if (!nodes.length) return 'No node changes'; + if (nodes.length <= 3) return nodes.map((n) => `${n.op} ${n.key}`).join(' · '); + const groups = nodeChangeGroups(nodes); + const shown = groups.slice(0, 3).map((g) => `${g.op} ${g.count.toLocaleString('en')} ${g.noun}`); + return groups.length > 3 ? `${shown.join(' · ')} · ${groups.length - 3} more kinds` : shown.join(' · '); +} diff --git a/ui/src/routes/+page.svelte b/ui/src/routes/+page.svelte index 6b42cad532..3b22c1aacf 100644 --- a/ui/src/routes/+page.svelte +++ b/ui/src/routes/+page.svelte @@ -20,8 +20,8 @@ import { runStatusLabel } from '$lib/status'; import { attentionRank, attentionView, type AttentionTone } from '$lib/build-area/attention'; import type { AttentionItem } from '$lib/api'; - import { changeOpLabel, formatCredits } from '$lib/build-area/labels'; - import { summarizeChange } from '$lib/build-area/changes'; + import { formatCredits } from '$lib/build-area/labels'; + import { nodeChangeLine, summarizeChange } from '$lib/build-area/changes'; import { pagesBeyondTarget } from '$lib/nav'; const overview = createResource((client, scope) => client.overview(scope), ['runs', 'checks', 'node_status', 'snapshot', 'platform_events', 'triggers']); @@ -258,7 +258,7 @@ {c.gitRevision?.slice(0, 7) ?? '—'}version {c.generation} {summarizeChange(c)} - {c.nodes.slice(0, 3).map((n) => `${changeOpLabel[n.op].toLowerCase()} ${n.key}`).join(' · ') || 'No node changes'} + {nodeChangeLine(c.nodes)} {c.gitAuthor ? `${c.gitAuthor} · ` : ''}{formatAgo(c.publishedAt, app.now)} diff --git a/ui/src/routes/changes/+page.svelte b/ui/src/routes/changes/+page.svelte index 3fdecb51fa..6a7bb8a43f 100644 --- a/ui/src/routes/changes/+page.svelte +++ b/ui/src/routes/changes/+page.svelte @@ -13,7 +13,7 @@ import { formatAgo, formatStamp } from '$lib/format/time'; import { runStatusLabel, runStatusTone } from '$lib/status'; import { changeOpLabel, changeOpTone, formatCredits } from '$lib/build-area/labels'; - import { summarizeChange } from '$lib/build-area/changes'; + import { NODE_LIST_LIMIT, nodeChangeGroups, summarizeChange } from '$lib/build-area/changes'; import { nodeHref, orchestrationHref, percentChange } from './utils'; type Area = 'all' | 'nodes' | 'orchestration' | 'roles' | 'environment'; @@ -37,6 +37,8 @@ return [c.gitRevision ?? '', c.gitAuthor ?? '', String(c.generation), ...c.nodes.map((n) => n.key), ...c.nodes.map((n) => n.formerKey ?? ''), ...c.orchestration.map((o) => o.key), ...c.roles.map((r) => r.role)].some((s) => s.toLowerCase().includes(q)); }) ); + /** Deploys, by snapshot, whose long node list is shown in full. */ + let listed = $state>({}); const areaOptions: { value: Area; label: string }[] = [ { value: 'all', label: 'All' }, { value: 'nodes', label: 'Nodes' }, @@ -75,9 +77,19 @@
{#if c.nodes.length} + {@const grouped = c.nodes.length > NODE_LIST_LIMIT && !listed[c.snapshotId] && !query.trim()}
-

Nodes {c.nodes.length}

- {#each c.nodes as n (n.key + n.op)} +

Nodes {c.nodes.length.toLocaleString('en')}

+ {#if grouped} + {#each nodeChangeGroups(c.nodes) as g (g.op + g.prefix)} +
+ {changeOpLabel[g.op]} + {g.count.toLocaleString('en')} {g.noun} +
+ {/each} + + {/if} + {#each grouped ? [] : c.nodes as n (n.key + n.op)} {@const href = nodeHref(n, app.client.supports('getCatalogNode'))}
{changeOpLabel[n.op]} @@ -247,6 +259,14 @@ padding: 4px 0; font-size: 12.5px; } + .more { + margin-top: 4px; + color: var(--primary); + font-size: 12.5px; + } + .more:hover { + text-decoration: underline; + } .row.sub { padding-left: 22px; } From 2740c2ab40791245830f127d817b1e4a21ed1d37 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:29:21 +0000 Subject: [PATCH 3/4] feat(ui): warn when a calendar trigger is running out of dates --- ui/src/lib/api/http-jobs.test.ts | 10 ++++++++-- ui/src/lib/api/http-jobs.ts | 14 ++++++++++---- ui/src/routes/triggers/[id]/trigger-view.svelte | 2 +- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/ui/src/lib/api/http-jobs.test.ts b/ui/src/lib/api/http-jobs.test.ts index 987a7ec3dc..2056dcf665 100644 --- a/ui/src/lib/api/http-jobs.test.ts +++ b/ui/src/lib/api/http-jobs.test.ts @@ -188,8 +188,14 @@ describe('schedule due times', () => { const calendar = trigger('t-cal', 'business_days', 'orders', { description: 'Business days', job_key: 'orders', schedule: { kind: 'calendar', times, refresh_at: '2026-11-08T00:00:00Z' } }); const detailOf = (wire: W['PersonTriggerRecord']) => triggerDetailOf(toTrigger(wire, [], null), wire, [], []); - it('reports the last stored calendar time and the next refresh', () => { - expect(detailOf(calendar).calendar).toMatchObject({ storedUntil: '2026-11-10T09:00:00.000Z', nextRefreshAt: '2026-11-08T00:00:00Z', horizon: null, low: false }); + it('reports the last stored calendar time, the next refresh, and whether it is running out of dates', () => { + const at = (now: string) => triggerDetailOf(toTrigger(calendar, [], null), calendar, [], [], null, Date.parse(now)).calendar; + expect(at('2026-11-08T12:00:00Z')).toMatchObject({ storedUntil: '2026-11-10T09:00:00.000Z', nextRefreshAt: '2026-11-08T00:00:00Z', horizon: null, low: false }); + // The last date is 23 hours away: under the server's one-day warning. + expect(at('2026-11-09T10:00:00Z')).toMatchObject({ low: true, lowHorizonWarningBelow: '1 day of dates' }); + // The server warns only about running calendars. + const paused = { ...calendar, status: 'paused' as const }; + expect(triggerDetailOf(toTrigger(paused, [], null), paused, [], [], null, Date.parse('2026-11-09T10:00:00Z')).calendar?.low).toBe(false); expect(detailOf(daily).calendar).toBeNull(); }); diff --git a/ui/src/lib/api/http-jobs.ts b/ui/src/lib/api/http-jobs.ts index 518072be7f..5bc6963257 100644 --- a/ui/src/lib/api/http-jobs.ts +++ b/ui/src/lib/api/http-jobs.ts @@ -129,18 +129,23 @@ function cursorMovedAt(state: Wire['PersonSensorState'], history: TriggerStateEv return times.length ? times.reduce((a, b) => (Date.parse(a) >= Date.parse(b) ? a : b)) : null; } +/** A calendar is running out of dates once its last one is this close, as the server judges it. */ +const CALENDAR_LOW_MS = 24 * 60 * 60 * 1000; + export function triggerDetailOf( trigger: Trigger, wire: Wire['PersonTriggerRecord'], ticks: Tick[], history: TriggerStateEvent[], - state: Wire['PersonSensorState'] | null = null + state: Wire['PersonSensorState'] | null = null, + now = Date.now() ): TriggerDetail { const d = wire.definition_json; const evaluations = state?.evaluations.map(toEvaluation) ?? null; const lastEvaluatedFingerprint = state?.evaluations[0]?.definition_fingerprint ?? null; const calendar = isSchedule(d) && d.schedule.kind === 'calendar' ? d.schedule : null; const stored = calendar ? calendar.times.map(Date.parse) : []; + const last = stored.length ? Math.max(...stored) : null; return { ...trigger, definitionChanged: !!state && lastEvaluatedFingerprint !== null && lastEvaluatedFingerprint !== state.definition_fingerprint, @@ -151,11 +156,12 @@ export function triggerDetailOf( upcoming: isSchedule(d) ? wire.upcoming : null, calendar: calendar && { horizon: null, - storedUntil: stored.length ? new Date(Math.max(...stored)).toISOString() : null, + storedUntil: last === null ? null : new Date(last).toISOString(), lastRefreshedAt: null, nextRefreshAt: calendar.refresh_at, - lowHorizonWarningBelow: null, - low: false + // The server warns when a running calendar's last date is a day away or less. + lowHorizonWarningBelow: '1 day of dates', + low: wire.status === 'running' && (last === null || last <= now + CALENDAR_LOW_MS) }, sensor: isSchedule(d) ? null diff --git a/ui/src/routes/triggers/[id]/trigger-view.svelte b/ui/src/routes/triggers/[id]/trigger-view.svelte index 222ae327dd..9cc717da5b 100644 --- a/ui/src/routes/triggers/[id]/trigger-view.svelte +++ b/ui/src/routes/triggers/[id]/trigger-view.svelte @@ -124,7 +124,7 @@

Calendar

{#if t.calendar.horizon}
Worked out ahead
{t.calendar.horizon}
{/if} -
Known until
{t.calendar.storedUntil ? formatStamp(t.calendar.storedUntil) : 'no times stored'}
+
Known until
{#if t.calendar.storedUntil}{formatStamp(t.calendar.storedUntil)} {Date.parse(t.calendar.storedUntil) > app.now ? formatIn(t.calendar.storedUntil, app.now) : formatAgo(t.calendar.storedUntil, app.now)}{:else}no times stored{/if}
{#if t.calendar.lastRefreshedAt}
Last updated
{formatAgo(t.calendar.lastRefreshedAt, app.now)}
{/if} {#if t.calendar.nextRefreshAt}
Next update
{Date.parse(t.calendar.nextRefreshAt) > app.now ? formatIn(t.calendar.nextRefreshAt, app.now) : `due ${formatAgo(t.calendar.nextRefreshAt, app.now)}`}
{/if} {#if t.calendar.lowHorizonWarningBelow}
Warns when under
{t.calendar.lowHorizonWarningBelow}
{/if} From b8b0e263306a9aee90274d52bcc40a317672558d Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:10:40 +0000 Subject: [PATCH 4/4] feat(server): sqb dev signs the local UI in as a development administrator sqb dev now keeps one local person, an installation administrator, and mounts the person API for loopback requests as that person. The bootstrap read reports the new disabled login mode, and the UI hides Sign out there. --- clients/typescript/src/schema.d.ts | 2 +- .../src/native_commands/main/_run_dev.rs | 2 ++ .../api/_helpers/authentication/configure.rs | 14 ++++++-- .../_helpers/authentication/development.rs | 31 ++++++++++++++++ .../src/api/_helpers/authentication/mod.rs | 1 + .../sqlbuild-orchestration/src/api/models.rs | 4 +++ .../main/identities/development_person.rs | 36 +++++++++++++++++++ .../src/credentials/main/identities/mod.rs | 1 + .../tests/api/test_development.rs | 27 ++++++++++++++ ui/src/lib/components/app-sidebar.svelte | 2 +- 10 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs create mode 100644 crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index 987403741d..b3537b4597 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -1913,7 +1913,7 @@ export interface components { * @description How people sign in to this server. * @enum {string} */ - LoginMode: "password" | "trusted_proxy" | "oidc"; + LoginMode: "password" | "trusted_proxy" | "oidc" | "disabled"; /** @description A running calendar schedule whose last date is at most a day away, or which has none left. */ LowCalendar: { /** diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs index 6206482586..8570106c85 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs @@ -3,6 +3,7 @@ use std::path::Path; use sqlbuild_orchestration::api::models::DevelopmentScope; +use sqlbuild_orchestration::credentials::main::identities::development_person::development_person; use sqlbuild_orchestration::credentials::main::locations::development_location::development_location; use sqlbuild_orchestration::credentials::models::AuditContext; use sqlbuild_orchestration::declarations::main::pause_development_triggers::pause_development_triggers; @@ -76,6 +77,7 @@ async fn development_store( location_id, target: target.into(), triggers: flag(namespace, "development_triggers"), + principal_id: development_person(&store, &context).await?, }; if !scope.triggers { pause_development_triggers(&store, (location_id, target)).await?; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs index 81403e1762..abbc7b8872 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs @@ -2,9 +2,9 @@ use std::net::SocketAddr; -use axum::{Extension, Router}; +use axum::{Extension, Router, middleware}; -use crate::api::_helpers::authentication::{oidc, password_sessions, trusted_proxy}; +use crate::api::_helpers::authentication::{development, oidc, password_sessions, trusted_proxy}; use crate::api::models::{ApiAuthentication, DevelopmentScope, GroupRole, HumanLogin, LoginMode}; use crate::store::errors::ControlError; use crate::store::models::ControlStore; @@ -31,6 +31,7 @@ pub(crate) async fn configure( let login_mode = match &login { HumanLogin::Oidc(_) => LoginMode::Oidc, HumanLogin::TrustedProxy(_) => LoginMode::TrustedProxy, + HumanLogin::Development(_) => LoginMode::Disabled, _ => LoginMode::Password, }; let (development, routes) = match login { @@ -41,7 +42,14 @@ pub(crate) async fn configure( "disabled authentication requires a loopback listener".into(), )); } - (Some(scope), Router::new()) + let person = scope.principal_id; + ( + Some(scope), + password_sessions::person_routes().route_layer(middleware::from_fn_with_state( + person, + development::authenticate, + )), + ) } HumanLogin::Password(origin) => (None, password_sessions::router(store, origin)?), HumanLogin::TrustedProxy(settings) => (None, trusted_proxy::router(store, settings)?), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs new file mode 100644 index 0000000000..03f024d94c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs @@ -0,0 +1,31 @@ +//! Development person requests: `local_request` already confined them to a loopback host and origin. + +use std::net::SocketAddr; + +use axum::extract::{ConnectInfo, Request, State}; +use axum::middleware::Next; +use axum::response::Response; +use uuid::Uuid; + +use crate::credentials::models::{AuditContext, AuthenticatedPerson}; + +pub(crate) async fn authenticate( + State(principal_id): State, + mut request: Request, + next: Next, +) -> Response { + let peer = request + .extensions() + .get::>() + .map(|info| info.0.ip().to_canonical()); + request.extensions_mut().insert(AuditContext { + actor: format!("principal:{principal_id}"), + granting_role: "development".into(), + request_id: Uuid::now_v7(), + ip_address: peer, + }); + request + .extensions_mut() + .insert(AuthenticatedPerson(principal_id, None)); + next.run(request).await +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs index 95a52ea8b5..a83a2a8dee 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs @@ -1,6 +1,7 @@ pub(crate) mod bearer; pub(crate) mod cli_login; pub(crate) mod configure; +pub(crate) mod development; pub(crate) mod oidc; pub(crate) mod oidc_provider; pub(crate) mod password_sessions; diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index 77bba7b6f7..e892515a8a 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -211,6 +211,8 @@ pub enum LoginMode { Password, TrustedProxy, Oidc, + /// `sqb dev` on loopback: no sign-in, every request acts as the local development person. + Disabled, } /// What the UI needs first: how people sign in, and what this person may see and do. @@ -232,6 +234,8 @@ pub struct DevelopmentScope { pub location_id: uuid::Uuid, pub target: String, pub triggers: bool, + /// The local person every loopback request acts as. + pub principal_id: uuid::Uuid, } /// The one way people sign in to this server, if any. diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs new file mode 100644 index 0000000000..587416b462 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs @@ -0,0 +1,36 @@ +//! `sqb dev` acts as one local administrator, recreated or restored on startup when missing. + +use uuid::Uuid; + +use crate::authorization::main::grant_admin::grant_admin; +use crate::credentials::main::identities::create_principal::create_principal; +use crate::credentials::models::AuditContext; +use crate::store::errors::ControlError; +use crate::store::main::read_records::read_records; +use crate::store::models::{ControlStore, Parameter}; + +pub async fn development_person( + store: &ControlStore, + context: &AuditContext, +) -> Result { + let rows: Vec = read_records( + store, + "SELECT p.principal_id, p.disabled_at, a.assignment_id FROM sqb_principals p \ + LEFT JOIN sqb_role_assignments a ON a.principal_id=p.principal_id AND a.role_key='admin' \ + AND a.location_id IS NULL AND a.target IS NULL WHERE p.name=$1", + vec![Parameter::Text("local-development".into())], + ) + .await?; + let id = match rows.first() { + Some(row) => serde_json::from_value(row["principal_id"].clone()) + .map_err(|_| ControlError::Schema("invalid development person identity".into()))?, + None => create_principal(store, context, "local-development").await?, + }; + let administrator = rows + .first() + .is_some_and(|row| row["disabled_at"].is_null() && !row["assignment_id"].is_null()); + if !administrator { + grant_admin(store, context, id).await?; + } + Ok(id) +} diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs index 59b28fe23a..126f3c51d3 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs @@ -1,3 +1,4 @@ pub mod create_principal; +pub mod development_person; pub(crate) mod insert_principal; pub mod list_people; diff --git a/crates/sqlbuild-orchestration/tests/api/test_development.rs b/crates/sqlbuild-orchestration/tests/api/test_development.rs index 490d8861c7..b41baed731 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_development.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_development.rs @@ -3,6 +3,7 @@ use uuid::Uuid; use crate::api::models::{ApiAuthentication, DevelopmentScope, HumanLogin}; +use crate::credentials::main::identities::development_person::development_person; use crate::credentials::main::locations::development_location::development_location; use crate::credentials::models::AuditContext; use crate::declarations::main::{ @@ -82,6 +83,15 @@ fn given_development_when_defaults_publish_then_identity_audit_and_trigger_pause .await .expect("target-specific identity"); assert_ne!(location, other); + let person = development_person(store, &context) + .await + .expect("development person"); + assert_eq!( + development_person(store, &context) + .await + .expect("retained development person"), + person + ); let api = start_api_with_authentication( store, ApiAuthentication { @@ -89,12 +99,29 @@ fn given_development_when_defaults_publish_then_identity_audit_and_trigger_pause location_id: location, target: "development".into(), triggers: false, + principal_id: person, }), ..ApiAuthentication::default() }, ) .await; let client = reqwest::Client::new(); + let bootstrap: serde_json::Value = client + .get(format!("{}/api/control/bootstrap", api.url)) + .send() + .await + .expect("bootstrap") + .error_for_status() + .expect("loopback person needs no sign-in") + .json() + .await + .expect("bootstrap body"); + assert_eq!(bootstrap["login_mode"], "disabled", "{bootstrap}"); + assert_eq!( + bootstrap["access"]["principal_id"], + person.to_string(), + "{bootstrap}" + ); let url = format!( "{}/api/locations/{location}/targets/development/snapshots", api.url diff --git a/ui/src/lib/components/app-sidebar.svelte b/ui/src/lib/components/app-sidebar.svelte index 69342ddffb..eab51d4eba 100644 --- a/ui/src/lib/components/app-sidebar.svelte +++ b/ui/src/lib/components/app-sidebar.svelte @@ -86,7 +86,7 @@
{initials} {app.user.displayName}{#if app.user.role} · {app.user.role}{/if} - {#if app.signOut} + {#if app.signOut && app.bootstrap?.authMode !== 'disabled'} {/if}