@sssb/kit 0.4.0 → 0.6.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 (64) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/auth-tenancy.ts +157 -0
  4. package/src/adapters/configured-auth.ts +183 -0
  5. package/src/adapters/email-message.ts +30 -0
  6. package/src/adapters/fake/analytics.ts +1 -1
  7. package/src/adapters/fake/auth.ts +53 -3
  8. package/src/adapters/fake/data-dir.ts +32 -2
  9. package/src/adapters/fake/email.ts +2 -0
  10. package/src/adapters/fake/jobs.ts +5 -4
  11. package/src/adapters/fake/simulated-auth.ts +24 -0
  12. package/src/adapters/index.ts +3 -2
  13. package/src/adapters/real/accept-invite-form.tsx +32 -14
  14. package/src/adapters/real/analytics.ts +29 -2
  15. package/src/adapters/real/auth.ts +127 -23
  16. package/src/adapters/real/contract-postgres.ts +15 -11
  17. package/src/adapters/real/email.ts +2 -0
  18. package/src/adapters/real/index.ts +19 -3
  19. package/src/adapters/real/jobs-in-process.ts +32 -14
  20. package/src/adapters/real/jobs.ts +6 -3
  21. package/src/adapters/real/migrate-handler.ts +3 -1
  22. package/src/adapters/real/rds-data-codec.ts +88 -4
  23. package/src/adapters/real/rds-data-emulator.ts +12 -4
  24. package/src/adapters/real/sign-in-form.tsx +29 -13
  25. package/src/authz/app-exemptions.ts +79 -9
  26. package/src/authz/authorize.ts +4 -1
  27. package/src/authz/route-scan.ts +626 -55
  28. package/src/components/auth/accept-invite-screen.tsx +5 -1
  29. package/src/components/auth/people-picker.tsx +20 -2
  30. package/src/components/profile-screen.tsx +27 -2
  31. package/src/core/abilities.ts +22 -6
  32. package/src/core/inbound-email.ts +41 -6
  33. package/src/core/jobs.ts +17 -0
  34. package/src/core/roles.ts +17 -2
  35. package/src/cutover/rows.json +4 -0
  36. package/src/db/jobs.ts +32 -11
  37. package/src/db/keyset.ts +8 -6
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/migrations/0017_job_requester.ts +20 -0
  40. package/src/db/migrations/index.ts +2 -0
  41. package/src/db/rls-coverage.ts +51 -17
  42. package/src/db/schedules.ts +9 -3
  43. package/src/db/schema.ts +2 -0
  44. package/src/demo-static/actor-drivers.ts +8 -2
  45. package/src/demo-static/contracts.ts +9 -0
  46. package/src/demo-static/email-html.ts +9 -0
  47. package/src/demo-static/rows.ts +2 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +98 -41
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +37 -6
  52. package/src/i18n/messages/en.json +3 -0
  53. package/src/i18n/messages/es.json +3 -0
  54. package/src/i18n/messages.ts +3 -2
  55. package/src/ports/auth.ts +10 -1
  56. package/src/server-lib/notify.ts +51 -9
  57. package/src/server-lib/scheduled-tick.ts +5 -1
  58. package/src/server-lib/webhook-dispatch.ts +3 -0
  59. package/src/service-auth/mailgun.ts +19 -4
  60. package/src/testing/conformance/auth-provider.ts +17 -5
  61. package/src/testing/conformance/authz.ts +6 -2
  62. package/src/testing/conformance/demo-presets.ts +4 -4
  63. package/src/testing/conformance/i18n.ts +99 -5
  64. package/src/testing/conformance/suite.ts +63 -3
@@ -117,7 +117,11 @@ export function AcceptInviteScreen({
117
117
  <Text size="xs" c="gray.7" data-testid="accept-agreements-notice">
118
118
  {t('agreementsNotice')}
119
119
  </Text>
120
- {error ? <Text c="red.8">{error}</Text> : null}
120
+ {error ? (
121
+ <Text c="red.8" role="alert">
122
+ {error}
123
+ </Text>
124
+ ) : null}
121
125
  </Stack>
122
126
  </form>
123
127
  }
@@ -14,8 +14,18 @@ export interface PickerPerson {
14
14
  /**
15
15
  * Simulated-mode sign-in: the same card layout the real credential form uses, listing seeded
16
16
  * people. One auth UI in every mode (ADR-0003).
17
+ *
18
+ * `onPick` may answer a promise: one that resolves `false` or rejects (the sign-in was refused, the dev server is
19
+ * down) clears the spinner so the person can pick again; anything else (`true`, or nothing, as an `async` handler
20
+ * that returns no value resolves) keeps it while the page navigates.
17
21
  */
18
- export function PeoplePicker({ people, onPick }: { people: PickerPerson[]; onPick: (id: string) => void }) {
22
+ export function PeoplePicker({
23
+ people,
24
+ onPick,
25
+ }: {
26
+ people: PickerPerson[]
27
+ onPick: (id: string) => void | Promise<boolean | void>
28
+ }) {
19
29
  const t = useTranslations('auth')
20
30
  const [busy, setBusy] = useState<string | null>(null)
21
31
 
@@ -39,7 +49,15 @@ export function PeoplePicker({ people, onPick }: { people: PickerPerson[]; onPic
39
49
  }
40
50
  onClick={() => {
41
51
  setBusy(person.id)
42
- onPick(person.id)
52
+ const result = onPick(person.id)
53
+ if (result) {
54
+ result.then(
55
+ (outcome) => {
56
+ if (outcome === false) setBusy(null)
57
+ },
58
+ () => setBusy(null),
59
+ )
60
+ }
43
61
  }}
44
62
  >
45
63
  {person.name}
@@ -10,6 +10,9 @@ export interface ProfileValues {
10
10
  locale: string
11
11
  }
12
12
 
13
+ /** The longest display name SSSB's auth adapters accept; a blank one is refused too. */
14
+ const PROFILE_NAME_MAX_LENGTH = 256
15
+
13
16
  /**
14
17
  * Lean take on Clerk's UserProfile (ADR-0003): a sectioned account page. The Profile section is live;
15
18
  * the Security section is a named seam so MFA / password / connected accounts have a home when those
@@ -27,13 +30,25 @@ export function ProfileScreen({
27
30
  initial: ProfileValues
28
31
  email: string
29
32
  locales: string[]
33
+ /** Rejects when the profile was not saved: the screen then keeps the form and says so. */
30
34
  onSave: (values: ProfileValues) => Promise<void>
31
35
  extraSection?: ReactNode
32
36
  }) {
33
37
  const t = useTranslations('profile')
34
38
  const [saved, setSaved] = useState(false)
35
39
  const [busy, setBusy] = useState(false)
36
- const form = useForm({ initialValues: initial })
40
+ const [saveFailed, setSaveFailed] = useState(false)
41
+ const form = useForm({
42
+ initialValues: initial,
43
+ validate: {
44
+ name: (value) =>
45
+ !value.trim()
46
+ ? t('nameRequired')
47
+ : value.length > PROFILE_NAME_MAX_LENGTH
48
+ ? t('nameTooLong', { max: PROFILE_NAME_MAX_LENGTH })
49
+ : null,
50
+ },
51
+ })
37
52
 
38
53
  return (
39
54
  <Container component="main" size="sm" py="xl">
@@ -48,8 +63,12 @@ export function ProfileScreen({
48
63
  onSubmit={form.onSubmit((values) => {
49
64
  setBusy(true)
50
65
  setSaved(false)
66
+ setSaveFailed(false)
51
67
  onSave(values)
52
- .then(() => setSaved(true))
68
+ .then(
69
+ () => setSaved(true),
70
+ () => setSaveFailed(true),
71
+ )
53
72
  .finally(() => setBusy(false))
54
73
  })}
55
74
  >
@@ -58,6 +77,7 @@ export function ProfileScreen({
58
77
  <TextInput
59
78
  label={t('nameLabel')}
60
79
  data-testid="profile-name"
80
+ withAsterisk
61
81
  {...form.getInputProps('name')}
62
82
  />
63
83
  <Select
@@ -75,6 +95,11 @@ export function ProfileScreen({
75
95
  >
76
96
  {t('saveButton')}
77
97
  </Button>
98
+ {saveFailed ? (
99
+ <Text c="red.8" size="sm" role="alert" data-testid="profile-save-error">
100
+ {t('saveError')}
101
+ </Text>
102
+ ) : null}
78
103
  {saved ? (
79
104
  <Text c="green.8" size="sm" data-testid="profile-saved">
80
105
  {t('saved')}
@@ -7,7 +7,7 @@ import {
7
7
  type AppSubjectFields,
8
8
  type AppSubjectType,
9
9
  } from '@sssb/app-config/abilities'
10
- import { canManageOrg, isRole, type Role } from './roles'
10
+ import { canManageOrg, hasStanding, isRole, type Role } from './roles'
11
11
 
12
12
  /**
13
13
  * The authorization model. PURE TypeScript — imports only ./roles and the app-config seam
@@ -273,6 +273,12 @@ export interface Ability {
273
273
  cannot(action: AbilityAction, subject: AbilitySubject): boolean
274
274
  }
275
275
 
276
+ /**
277
+ * An active-org id no org has: what the app's rules are shown for a person without standing (`hasStanding`). Org ids
278
+ * are database uuids, so no subject's org field can hold it.
279
+ */
280
+ const NO_STANDING_ORG = '\u0000no-standing'
281
+
276
282
  /**
277
283
  * Compile the rule table for one actor. The framework rules (deny by default):
278
284
  * - manageAll → allow everything (held by a member acting AS the app's operator org; see above).
@@ -324,16 +330,26 @@ export function defineAbilitiesFor(actor: Actor): Ability {
324
330
  // The staff superpower belongs to a SESSION acting as the operator org. Enforced here rather than
325
331
  // trusted to whoever built the actor: a person who came through any other credential (an email, a
326
332
  // token), or who states none, never wields it, even acting in the staff org. The app's rules are
327
- // handed the same effective value.
333
+ // handed the same effective value. A person without standing (role `none`, ./roles.ts `hasStanding`) never wields
334
+ // it either: a fixed org source places every user of the identity provider in the home org, which may be the staff
335
+ // org.
328
336
  const session = copy.credential?.kind === 'session'
337
+ const standing = hasStanding(copy.role)
329
338
  // Read at call time, like the app's machine rules (see the machine branch above).
330
339
  const widening: NonSessionAdministration = nonSessionAdministration
331
340
  const person: AbilityActor =
332
- copy.manageAll && session
341
+ copy.manageAll && session && standing
333
342
  ? { ...copy, manageAll: true, credential: { kind: 'session', id: copy.credential?.id ?? null } }
334
343
  : { ...copy, manageAll: false }
335
- // sameOrg for the person reads the COPY's org, like every other person rule.
336
- const personSameOrg: SameOrg = (subject) => subject.orgId != null && subject.orgId === person.activeOrgId
344
+ // sameOrg for the person reads the COPY's org, like every other person rule. A person without standing is in no
345
+ // org for any rule, the framework's or the app's (which are handed this same predicate): being placed in an org is
346
+ // not membership of it.
347
+ const personSameOrg: SameOrg = (subject) =>
348
+ standing && subject.orgId != null && subject.orgId === person.activeOrgId
349
+ // The app's rules see a person without standing as active in no org at all: its `activeOrgId` is a value no org id
350
+ // equals, so a rule that compares org ids itself rather than calling `sameOrg` (a two-sided subject's requester and
351
+ // responder sides, say) cannot grant it either.
352
+ const ruleActor: AbilityActor = standing ? person : { ...person, activeOrgId: NO_STANDING_ORG }
337
353
 
338
354
  function can(action: AbilityAction, subject: AbilitySubject): boolean {
339
355
  // The staff-org superpower. manageAll precedes
@@ -403,7 +419,7 @@ export function defineAbilitiesFor(actor: Actor): Ability {
403
419
  default:
404
420
  // App subjects register through the seam (src/app-config/abilities.ts). Deny by default:
405
421
  // appAbilityRules returns false for anything it does not explicitly allow.
406
- return appAbilityRules(person, action, subject, { sameOrg: personSameOrg })
422
+ return appAbilityRules(ruleActor, action, subject, { sameOrg: personSameOrg })
407
423
  }
408
424
  }
409
425
 
@@ -42,14 +42,49 @@ export interface InboundRecipient {
42
42
  const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
43
43
 
44
44
  /**
45
- * Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`,
46
- * a bare `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local
47
- * parts are case-insensitive in every practical mail system — we normalize so a sender/member match is
48
- * not defeated by case). Returns '' for anything without an addr-spec.
45
+ * `raw` with each double-quoted string taken out, a backslash escaping the character after it. A quote that never
46
+ * closes is left where it is, with everything after it. One pass by hand: the regular expression for this
47
+ * (`"(?:[^"\\]|\\.)*"`) rescans from every opening quote, which is quadratic on a header an attacker writes.
48
+ */
49
+ function withoutQuotedStrings(raw: string): string {
50
+ let out = ''
51
+ let at = 0
52
+ while (at < raw.length) {
53
+ if (raw[at] !== '"') {
54
+ out += raw[at]
55
+ at += 1
56
+ continue
57
+ }
58
+ let end = at + 1
59
+ while (end < raw.length && raw[end] !== '"') end += raw[end] === '\\' ? 2 : 1
60
+ if (end >= raw.length) return out + raw.slice(at)
61
+ at = end + 1
62
+ }
63
+ return out
64
+ }
65
+
66
+ /**
67
+ * Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`, a bare
68
+ * `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local parts are
69
+ * case-insensitive in every practical mail system — we normalize so a sender/member match is not defeated by case).
70
+ *
71
+ * It fails closed: anything it cannot read one way only returns '' ("no address"), never a guess. Double-quoted
72
+ * strings (a display name) are dropped first, so `"<victim@org.test>" <attacker@evil.test>` is the attacker's own
73
+ * address. Then a value with angle brackets must hold exactly one `<...>` with nothing but whitespace after its `>`:
74
+ * a comment after the address (`<a@x> (<b@y>)`), a second address (`<a@x>, <b@y>`) or text after the brackets
75
+ * (`x<b@y>a@x`) each name another address, so they return ''. Returns '' for anything without an addr-spec too.
49
76
  */
50
77
  export function normalizeEmailAddress(raw: string): string {
51
- const angle = raw.match(/<([^>]+)>/)
52
- const candidate = (angle ? angle[1]! : raw).trim().toLowerCase()
78
+ const unquoted = withoutQuotedStrings(raw)
79
+ let candidate: string
80
+ if (/[<>]/.test(unquoted)) {
81
+ const only = /^[^<>]*<([^<>]*)>\s*$/.exec(unquoted)
82
+ if (!only) return ''
83
+ candidate = only[1]!
84
+ } else {
85
+ candidate = unquoted
86
+ }
87
+ candidate = candidate.trim().toLowerCase()
53
88
  // A single '@' with non-empty both sides, else not a usable address.
54
89
  const at = candidate.indexOf('@')
55
90
  if (at <= 0 || at !== candidate.lastIndexOf('@') || at === candidate.length - 1) return ''
package/src/core/jobs.ts CHANGED
@@ -35,6 +35,23 @@ export function isJobKind(value: string): value is JobKind {
35
35
  )
36
36
  }
37
37
 
38
+ /**
39
+ * When a job kind's terminal state notifies the team's admins: `always` (a completion and a failure, what every app
40
+ * kind did before the setting existed, so the default), `failure` (only a failure) or `never`. An app says it per
41
+ * kind in the seam's optional `jobNotify` export (`@sssb/app-config/jobs`); the framework's own kinds never notify.
42
+ */
43
+ export const JOB_NOTIFY_MODES = ['always', 'failure', 'never'] as const
44
+ export type JobNotify = (typeof JOB_NOTIFY_MODES)[number]
45
+
46
+ export function isJobNotify(value: unknown): value is JobNotify {
47
+ return (JOB_NOTIFY_MODES as readonly unknown[]).includes(value)
48
+ }
49
+
50
+ /** Whether a job that reached `status` is notified under `mode`. */
51
+ export function notifiesOn(mode: JobNotify, status: 'completed' | 'failed'): boolean {
52
+ return mode === 'always' || (mode === 'failure' && status === 'failed')
53
+ }
54
+
38
55
  export function isJobStatus(value: string): value is JobStatus {
39
56
  return (JOB_STATUSES as readonly string[]).includes(value)
40
57
  }
package/src/core/roles.ts CHANGED
@@ -1,6 +1,21 @@
1
- export const ROLES = ['admin', 'staff', 'member', 'guest', 'restricted'] as const
1
+ /**
2
+ * `none` is the lowest: a signed-in person with no standing in the org they are placed in. A fixed org source
3
+ * (`AUTH_ORG_SOURCE=fixed`, the app's `params.auth`) gives it to every user of the deployment's identity provider by
4
+ * default (its other choice is `restricted`). It grants nothing a membership would: no org-scoped access in the
5
+ * framework's rules or the app's, and never manage-all (`hasStanding`). It is not grantable by invite.
6
+ */
7
+ export const ROLES = ['admin', 'staff', 'member', 'guest', 'restricted', 'none'] as const
2
8
  export type Role = (typeof ROLES)[number]
3
9
 
10
+ /**
11
+ * Whether a role carries standing in the org its holder is placed in: every role but `none`. The ability layer
12
+ * treats a holder without standing as outside every org (`sameOrg` is false, framework rules and app rules alike) and
13
+ * never lets it wield the staff org's manage-all.
14
+ */
15
+ export function hasStanding(role: Role): boolean {
16
+ return role !== 'none'
17
+ }
18
+
4
19
  // The designated staff/operator org slug is an app/deployment choice, so it lives on the
5
20
  // seam as `staffOrgSlug` (src/app-config/abilities.ts) — NOT here. DISAMBIGUATION: the operator ORG is
6
21
  // NOT the rank-ladder role `'staff'` below; the role is an org-manager RANK, the org is the operator
@@ -43,5 +58,5 @@ export function canManageOrg(role: Role): boolean {
43
58
  * adapters derive `AuthUser.restricted` and `getMember`'s standing through this one function.
44
59
  */
45
60
  export function isRestricted(flag: boolean | undefined, role: Role): boolean {
46
- return flag === true || role === 'restricted'
61
+ return flag === true || role === 'restricted' || role === 'none'
47
62
  }
@@ -4,6 +4,10 @@
4
4
  "id": "auth-dev",
5
5
  "what": "Managed-auth **development** instance + keys"
6
6
  },
7
+ {
8
+ "id": "auth-tenancy",
9
+ "what": "Auth settings: the tenancy (multi, or single with its tenant) and the org source (the provider's, or one fixed home org and role)"
10
+ },
7
11
  {
8
12
  "id": "auth-prod",
9
13
  "what": "Managed-auth **production** instance (typically one per tenant site)"
package/src/db/jobs.ts CHANGED
@@ -33,16 +33,24 @@ export function toIso(value: unknown): string {
33
33
  * Submits a job: one tenant-scoped transaction persists the `jobs` row and its opening 'queued'
34
34
  * timeline entry together, THEN — only once that has committed — hands off to the execution seam
35
35
  * so the handler (fake: in-process; real: CodeBuild) can never observe a job that isn't durable yet.
36
+ * `requestedBy` is the user id of the person submitting it, when a person is: their job's end reaches them when
37
+ * the org has no admin to tell (../server-lib/notify.ts `notifyJobTerminal`).
36
38
  */
37
39
  export async function submitJob(
38
40
  db: DbPort,
39
41
  jobs: JobsPort,
40
- input: { tenantId: string; orgId: string | null; kind: string; payload: unknown },
42
+ input: { tenantId: string; orgId: string | null; kind: string; payload: unknown; requestedBy?: string | null },
41
43
  ): Promise<{ id: string }> {
42
44
  const { id } = await db.withTenant(input.tenantId, async (trx) => {
43
45
  const job = await trx
44
46
  .insertInto('jobs')
45
- .values({ tenant_id: input.tenantId, org_id: input.orgId, kind: input.kind, payload: input.payload })
47
+ .values({
48
+ tenant_id: input.tenantId,
49
+ org_id: input.orgId,
50
+ kind: input.kind,
51
+ payload: input.payload,
52
+ requested_by: input.requestedBy ?? null,
53
+ })
46
54
  .returning('id')
47
55
  .executeTakeFirstOrThrow()
48
56
  await trx
@@ -98,13 +106,22 @@ export async function recordJobStatus(
98
106
  // Outbound webhooks: a job status change is an emitted event. Enqueue only — cheap; the
99
107
  // drain delivers async. Deliberately AFTER the status transaction commits (the audit precedent),
100
108
  // and skipped when the job has no org (RLS-proof / legacy rows can't have subscribed endpoints).
109
+ // The status is durable by now, so a failed enqueue must not fail the caller: a runner that saw
110
+ // `running` throw would never run the handler, and one that saw `completed` throw would answer an
111
+ // error for a job that finished. The event is lost and logged (console.warn reaches CloudWatch in
112
+ // Lambda; SSSB has no logger port, as ../adapters/real/db.ts says).
101
113
  if (job.orgId) {
102
- await enqueueWebhookEvent(db, {
103
- tenantId,
104
- orgId: job.orgId,
105
- kind: 'job.status_changed',
106
- payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
107
- })
114
+ try {
115
+ await enqueueWebhookEvent(db, {
116
+ tenantId,
117
+ orgId: job.orgId,
118
+ kind: 'job.status_changed',
119
+ payload: { jobId, jobKind: job.kind, status: next, orgId: job.orgId },
120
+ })
121
+ } catch (error) {
122
+ const message = error instanceof Error ? error.message : String(error)
123
+ console.warn(`SSSB jobs: job ${jobId} is ${next}, but enqueueing its webhook event failed: ${message}`)
124
+ }
108
125
  }
109
126
  }
110
127
 
@@ -270,10 +287,14 @@ export async function jobKindAndOrg(
270
287
  db: DbPort,
271
288
  tenantId: string,
272
289
  jobId: string,
273
- ): Promise<{ kind: string; orgId: string | null } | null> {
290
+ ): Promise<{ kind: string; orgId: string | null; requestedBy: string | null } | null> {
274
291
  return db.withTenant(tenantId, async (trx) => {
275
- const row = await trx.selectFrom('jobs').select(['kind', 'org_id']).where('id', '=', jobId).executeTakeFirst()
276
- return row ? { kind: row.kind, orgId: row.org_id } : null
292
+ const row = await trx
293
+ .selectFrom('jobs')
294
+ .select(['kind', 'org_id', 'requested_by'])
295
+ .where('id', '=', jobId)
296
+ .executeTakeFirst()
297
+ return row ? { kind: row.kind, orgId: row.org_id, requestedBy: row.requested_by } : null
277
298
  })
278
299
  }
279
300
 
package/src/db/keyset.ts CHANGED
@@ -101,15 +101,17 @@ export interface KeysetPage<TRow> {
101
101
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
102
102
 
103
103
  /**
104
- * `parseKeysetCursor` plus the one constraint only this layer knows about: the id half is bound to a
105
- * `uuid`, so an id that is not one can never be a real row here and is rejected at the boundary
106
- * rather than becoming a cast error (a 500, and a probe signal) inside the query. Routes over SQL
107
- * tables should use THIS, not the core parser; an in-memory twin uses the core one, whose row handles
108
- * are not uuids.
104
+ * `parseKeysetCursor` plus the constraints only this layer knows about, each a cast error (a 500, and a
105
+ * probe signal) inside the query if it were let through: the id half is bound to a `uuid`, so an id
106
+ * that is not one can never be a real row here; and the `at` half is bound to a `timestamptz`, which
107
+ * has no year 0000 (JavaScript's calendar does, so the core parser accepts it). Both are rejected at
108
+ * the boundary. Routes over SQL tables should use THIS, not the core parser; an in-memory twin uses
109
+ * the core one, whose row handles are not uuids.
109
110
  */
110
111
  export function parseDbKeysetCursor(raw: string | null | undefined): KeysetCursorParse {
111
112
  const parsed = parseKeysetCursor(raw)
112
- if (parsed.kind === 'after' && !UUID_PATTERN.test(parsed.position.id)) return { kind: 'invalid' }
113
+ if (parsed.kind !== 'after') return parsed
114
+ if (!UUID_PATTERN.test(parsed.position.id) || parsed.position.at.startsWith('0000-')) return { kind: 'invalid' }
113
115
  return parsed
114
116
  }
115
117
 
@@ -55,7 +55,7 @@ export async function up(db: Kysely<any>): Promise<void> {
55
55
  END IF;
56
56
  EXCEPTION WHEN insufficient_privilege THEN
57
57
  -- The statement is printed with the role QUOTED, so copying it runs as-is for any role name.
58
- RAISE EXCEPTION 'keel: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
58
+ RAISE EXCEPTION 'SSSB: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
59
59
  END $$
60
60
  `.execute(db)
61
61
  }
@@ -0,0 +1,20 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * WHO started a job: the user id of the person who submitted it, so the end of their job can reach them when the org
5
+ * has no admin to tell (a fixed org source places everyone in one org with one role, so it has none).
6
+ *
7
+ * - NULLABLE, no default. NULL means "no person started it": a scheduled run, a job submitted by a service, and every
8
+ * row written before this migration.
9
+ * - Plain text, no foreign key: user ids are the identity provider's, not a table here (as `audit_events`' actor).
10
+ * - The grant is unchanged: table-level grants cover columns added later (as in 0014 and 0016).
11
+ *
12
+ * It names the one table it touches (the order-independence rule in ./index.ts).
13
+ */
14
+ export async function up(db: Kysely<any>): Promise<void> {
15
+ await sql`ALTER TABLE jobs ADD COLUMN requested_by text`.execute(db)
16
+ }
17
+
18
+ export async function down(db: Kysely<any>): Promise<void> {
19
+ await sql`ALTER TABLE jobs DROP COLUMN requested_by`.execute(db)
20
+ }
@@ -13,6 +13,7 @@ import * as m0013 from './0013_agreements'
13
13
  import * as m0014 from './0014_audit_credential'
14
14
  import * as m0015 from './0015_app_user_grant'
15
15
  import * as m0016 from './0016_audit_detail'
16
+ import * as m0017 from './0017_job_requester'
16
17
 
17
18
  /**
18
19
  * Static migration registry (no filesystem scanning — bundles cleanly into the Lambda migrator and
@@ -44,6 +45,7 @@ export const frameworkMigrations: Record<string, Migration> = {
44
45
  '0014_audit_credential': m0014,
45
46
  '0015_app_user_grant': m0015,
46
47
  '0016_audit_detail': m0016,
48
+ '0017_job_requester': m0017,
47
49
  }
48
50
 
49
51
  export const migrations: Record<string, Migration> = { ...frameworkMigrations, ...appMigrations }
@@ -112,8 +112,15 @@ interface RelationRow {
112
112
  enabled: boolean
113
113
  forced: boolean
114
114
  is_partition: boolean
115
- policies: number
116
- policy_src: string
115
+ }
116
+
117
+ interface PolicyRow {
118
+ schema_name: string
119
+ table_name: string
120
+ policy_name: string
121
+ permissive: boolean
122
+ using_src: string | null
123
+ check_src: string | null
117
124
  }
118
125
 
119
126
  interface PrivilegeRow {
@@ -153,14 +160,7 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
153
160
  c.relkind::text AS kind,
154
161
  c.relrowsecurity AS enabled,
155
162
  c.relforcerowsecurity AS forced,
156
- c.relispartition AS is_partition,
157
- (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid)::int AS policies,
158
- COALESCE((
159
- SELECT string_agg(
160
- COALESCE(pg_get_expr(p.polqual, p.polrelid), '') || ' ' ||
161
- COALESCE(pg_get_expr(p.polwithcheck, p.polrelid), ''), ' ')
162
- FROM pg_policy p WHERE p.polrelid = c.oid
163
- ), '') AS policy_src
163
+ c.relispartition AS is_partition
164
164
  FROM reachable r
165
165
  JOIN pg_class c ON c.oid = r.oid
166
166
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -168,6 +168,26 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
168
168
  ORDER BY n.nspname, c.relname
169
169
  `.execute(db)
170
170
 
171
+ // Policies one row each. They used to be read as one string per table, and since PERMISSIVE policies
172
+ // are OR-ed, one isolating policy hid a `USING (true)` beside it: the table leaked with the gate green.
173
+ const { rows: policyRows } = await sql<PolicyRow>`
174
+ SELECT n.nspname AS schema_name,
175
+ c.relname AS table_name,
176
+ p.polname AS policy_name,
177
+ p.polpermissive AS permissive,
178
+ pg_get_expr(p.polqual, p.polrelid) AS using_src,
179
+ pg_get_expr(p.polwithcheck, p.polrelid) AS check_src
180
+ FROM pg_policy p
181
+ JOIN pg_class c ON c.oid = p.polrelid
182
+ JOIN pg_namespace n ON n.oid = c.relnamespace
183
+ ORDER BY n.nspname, c.relname, p.polname
184
+ `.execute(db)
185
+ const policiesOf = new Map<string, PolicyRow[]>()
186
+ for (const policy of policyRows) {
187
+ const key = `${policy.schema_name}.${policy.table_name}`
188
+ policiesOf.set(key, [...(policiesOf.get(key) ?? []), policy])
189
+ }
190
+
171
191
  const failures: string[] = []
172
192
  const name = (row: RelationRow) => `${row.schema_name}.${row.table_name}`
173
193
  const present = new Set(rows.map(name))
@@ -213,17 +233,31 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
213
233
  continue
214
234
  }
215
235
 
236
+ const policies = policiesOf.get(key) ?? []
216
237
  if (!row.enabled) failures.push(`${key} is reachable by app_user but has no ROW LEVEL SECURITY`)
217
238
  else if (!row.forced) failures.push(`${key} has RLS but not FORCE ROW LEVEL SECURITY`)
218
- else if (row.policies === 0) failures.push(`${key} has RLS enabled but no policy`)
219
- else if (!row.policy_src.includes(TENANT_SETTING)) {
239
+ else if (policies.length === 0) failures.push(`${key} has RLS enabled but no policy`)
240
+ else {
220
241
  // Coverage used to accept any policy at all, so `USING (true)` — a policy that exists and
221
242
  // isolates nothing — passed. Reading the expression is what distinguishes a policy from a
222
- // policy that does something.
223
- failures.push(
224
- `${key} has a policy that never reads ${TENANT_SETTING}, so it does not isolate tenants: ` +
225
- `${row.policy_src.trim()}`,
226
- )
243
+ // policy that does something. Each PERMISSIVE policy is read on its own (they are OR-ed, so
244
+ // one tenant-blind policy opens the table whatever the others say), and each expression it
245
+ // has on its own: a USING that isolates beside a `WITH CHECK (true)` still lets a write land
246
+ // in another tenant. A missing expression is fine (an INSERT policy has no USING; an absent
247
+ // WITH CHECK falls back to USING). RESTRICTIVE policies are AND-ed on top and can only narrow
248
+ // access, so they are not read here (a table with only restrictive policies shows app_user nothing).
249
+ for (const policy of policies) {
250
+ if (!policy.permissive) continue
251
+ const blind = [policy.using_src, policy.check_src].filter(
252
+ (expression): expression is string => expression !== null && !expression.includes(TENANT_SETTING),
253
+ )
254
+ if (blind.length > 0) {
255
+ failures.push(
256
+ `${key} has a permissive policy \`${policy.policy_name}\` that never reads ${TENANT_SETTING}, ` +
257
+ `so it does not isolate tenants (permissive policies are OR-ed): ${blind.join(' / ')}`,
258
+ )
259
+ }
260
+ }
227
261
  }
228
262
  }
229
263
 
@@ -38,9 +38,15 @@ const MAX_COALESCE = 100_000
38
38
  * skipped period. jobs.start() runs only AFTER that transaction commits, exactly as submitJob does, so
39
39
  * a handler never observes a job — or a schedule state — that isn't durable yet.
40
40
  *
41
- * FAULT ISOLATION. One bad row (a malformed spec that parseScheduleSpec rejects, a start() failure)
42
- * must not stall every other schedule: each schedule drains inside its own try/catch, counted in
43
- * `failed` and retried naturally on the next tick because its next_run_at never advanced.
41
+ * FAULT ISOLATION. One bad row must not stall every other schedule: each schedule drains inside its
42
+ * own try/catch, counted in `failed`. What a failure leaves depends on where it happens. A failure
43
+ * INSIDE the transaction (a malformed spec that parseScheduleSpec rejects, a failed insert) rolls it
44
+ * back, so next_run_at never advanced and the next tick tries the row again. A failure AFTER it
45
+ * commits (the audit insert, or jobs.start()) is NOT retried: the job row is already `queued` and the
46
+ * schedule has already moved on to its next slot, so that period's run is not started by this code.
47
+ * Retrying would make the spawn at-least-once for handlers written to run at most once. The job left
48
+ * `queued` is the runner's to deal with: the in-process runner's sweep fails a job left queued too
49
+ * long; under any other runner it stays queued.
44
50
  */
45
51
  export async function runDueSchedules(
46
52
  db: DbPort,
package/src/db/schema.ts CHANGED
@@ -30,6 +30,8 @@ interface JobsTable {
30
30
  status: Generated<string>
31
31
  result_key: string | null
32
32
  error: string | null
33
+ /** The user id of the person who submitted it; null for a scheduled or service job (0017_job_requester). */
34
+ requested_by: Generated<string | null>
33
35
  created_at: Generated<string>
34
36
  updated_at: Generated<string>
35
37
  }
@@ -32,6 +32,10 @@ interface DemoDriverDeps {
32
32
  jobsRef: RefObject<DemoJob[]>
33
33
  setJobs: Dispatch<SetStateAction<DemoJob[]>>
34
34
  log: ActorLog
35
+ /** What the world emits once a job this driver completed is completed, as the server route this driver stands
36
+ * in for does: the service actor's, the job.status_changed webhook; the builder's, the webhook and the admin
37
+ * notification. */
38
+ onCompleted: (job: DemoJob) => void
35
39
  }
36
40
 
37
41
  /** The one team a service actor is scoped to — the twin of its minted token's tenant/org claims. */
@@ -41,7 +45,7 @@ export interface DemoServiceScope {
41
45
  }
42
46
 
43
47
  export function createDemoServiceDriver(
44
- { jobsRef, setJobs, log }: DemoDriverDeps,
48
+ { jobsRef, setJobs, log, onCompleted }: DemoDriverDeps,
45
49
  scope: DemoServiceScope,
46
50
  ): ServiceDriver {
47
51
  return {
@@ -95,13 +99,14 @@ export function createDemoServiceDriver(
95
99
  : j,
96
100
  ),
97
101
  )
102
+ onCompleted(job)
98
103
  return 'applied'
99
104
  },
100
105
  }
101
106
  }
102
107
 
103
108
  export function createDemoBuilderDriver(
104
- { jobsRef, setJobs, log }: DemoDriverDeps,
109
+ { jobsRef, setJobs, log, onCompleted }: DemoDriverDeps,
105
110
  /** Teams already served by a dedicated service actor (@sssb/app-config/jobs' serviceManagedOrgSlugs) —
106
111
  * excluded so the two actors' job pools stay disjoint, exactly like listPendingBuilds. */
107
112
  serviceManagedOrgSlugs: readonly string[],
@@ -155,6 +160,7 @@ export function createDemoBuilderDriver(
155
160
  return { ...j, status: 'completed', timeline }
156
161
  }),
157
162
  )
163
+ onCompleted(job)
158
164
  return 'applied'
159
165
  },
160
166
  }