@sssb/kit 0.5.0 → 0.6.1
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.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/auth-tenancy.ts +157 -0
- package/src/adapters/configured-auth.ts +203 -0
- package/src/adapters/fake/atomic-write.ts +1 -1
- package/src/adapters/fake/auth.ts +35 -1
- package/src/adapters/fake/jobs.ts +5 -4
- package/src/adapters/fake/simulated-auth.ts +30 -0
- package/src/adapters/index.ts +3 -2
- package/src/adapters/real/account-refused-form.tsx +32 -0
- package/src/adapters/real/auth.ts +76 -7
- package/src/adapters/real/index.ts +23 -3
- package/src/adapters/real/rds-data-dialect.ts +118 -1
- package/src/adapters/real/rds-data-emulator.ts +35 -1
- package/src/authz/authorize.ts +4 -1
- package/src/components/auth/account-refused.tsx +53 -0
- package/src/core/abilities.ts +22 -6
- package/src/core/jobs.ts +17 -0
- package/src/core/roles.ts +17 -2
- package/src/cutover/rows.json +4 -0
- package/src/db/family.ts +1 -1
- package/src/db/jobs.ts +17 -5
- package/src/db/migrations/0017_job_requester.ts +20 -0
- package/src/db/migrations/index.ts +2 -0
- package/src/db/org-lookup.ts +18 -0
- package/src/db/schema.ts +2 -0
- package/src/demo-static/contracts.ts +9 -0
- package/src/demo-static/rows.ts +2 -0
- package/src/demo-static/world.ts +22 -4
- package/src/guide.md +26 -0
- package/src/i18n/messages/en.json +5 -1
- package/src/i18n/messages/es.json +5 -1
- package/src/ports/auth.ts +26 -1
- package/src/server-lib/notify.ts +51 -9
- package/src/testing/conformance/auth-provider.ts +1 -0
- package/src/testing/conformance/demo-presets.ts +4 -4
|
@@ -13,13 +13,19 @@ import type {
|
|
|
13
13
|
ProfileUpdate,
|
|
14
14
|
} from '../../ports/auth'
|
|
15
15
|
import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
|
|
16
|
+
import { authSettings } from '../auth-tenancy'
|
|
17
|
+
import type { ProviderIdentitySource } from '../configured-auth'
|
|
16
18
|
|
|
17
19
|
/**
|
|
18
20
|
* Clerk headless adapter (ADR-0003). Clerk organizations ARE our orgs
|
|
19
21
|
* (product copy: "teams"); our org slug === Clerk org slug (no mapping layer). The tenant (site) is
|
|
20
|
-
* ambient and lives in user publicMetadata
|
|
22
|
+
* ambient and lives in the user's publicMetadata, under the deployment's key (`tenantSlug` unless
|
|
23
|
+
* AUTH_TENANT_METADATA_KEY says otherwise) — one Clerk instance per tenant in prod, so
|
|
21
24
|
* every org a user sees belongs to their tenant. The ACTIVE org rides in unsafeMetadata.currentOrgSlug,
|
|
22
25
|
* and the request-time role comes from that org membership's publicMetadata.role (role is per-org).
|
|
26
|
+
* These are the default auth settings (multi tenancy, the provider's organizations); a single tenancy or a fixed
|
|
27
|
+
* org source (../auth-tenancy.ts) wraps this adapter with ../configured-auth.ts, which reads Clerk's accounts
|
|
28
|
+
* through `clerkIdentitySource` below.
|
|
23
29
|
*
|
|
24
30
|
* AUTHORED — CUTOVER (`auth-dev`): typechecked against @clerk/nextjs, never run against a real
|
|
25
31
|
* Clerk instance. Verify the full port contract suite against the dev instance at cutover.
|
|
@@ -31,7 +37,27 @@ interface AppPublicMetadata {
|
|
|
31
37
|
role?: string
|
|
32
38
|
locale?: string
|
|
33
39
|
restricted?: boolean
|
|
34
|
-
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The tenant a user's public metadata claims, under the deployment's key (`AUTH_TENANT_METADATA_KEY`, default
|
|
44
|
+
* `tenantSlug`: ../auth-tenancy.ts): the string it holds; `undefined` when it holds none (absent, null or empty); or
|
|
45
|
+
* `null` when it holds something else, which a single tenancy refuses and a multi tenancy reads as no tenant.
|
|
46
|
+
*/
|
|
47
|
+
function tenantClaim(metadata: unknown): string | null | undefined {
|
|
48
|
+
const key = authSettings().tenantMetadataKey
|
|
49
|
+
// Its own property only: a key such as `toString` names something every object inherits.
|
|
50
|
+
const value =
|
|
51
|
+
metadata !== null && typeof metadata === 'object' && Object.hasOwn(metadata, key)
|
|
52
|
+
? (metadata as Record<string, unknown>)[key]
|
|
53
|
+
: undefined
|
|
54
|
+
if (value === undefined || value === null || value === '') return undefined
|
|
55
|
+
return typeof value === 'string' ? value : null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function localeFrom(metadata: unknown): Locale {
|
|
59
|
+
const locale = (metadata as AppPublicMetadata | null | undefined)?.locale
|
|
60
|
+
return LOCALES.includes(locale as Locale) ? (locale as Locale) : DEFAULT_LOCALE
|
|
35
61
|
}
|
|
36
62
|
|
|
37
63
|
/**
|
|
@@ -92,7 +118,7 @@ export const realAuth: AuthPort = {
|
|
|
92
118
|
const user = await currentUser()
|
|
93
119
|
if (!user) return null
|
|
94
120
|
const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
|
|
95
|
-
const locale =
|
|
121
|
+
const locale = localeFrom(metadata)
|
|
96
122
|
|
|
97
123
|
// Resolve the active org membership: the remembered currentOrgSlug if still a membership,
|
|
98
124
|
// else the first one. Role comes from that membership (per-org), not the user object.
|
|
@@ -110,7 +136,7 @@ export const realAuth: AuthPort = {
|
|
|
110
136
|
role,
|
|
111
137
|
locale,
|
|
112
138
|
// Ambient site claim — never the active org's business.
|
|
113
|
-
tenantSlug:
|
|
139
|
+
tenantSlug: tenantClaim(user.publicMetadata) ?? '',
|
|
114
140
|
orgSlug: active ? (active.organization.slug ?? active.organization.id) : '',
|
|
115
141
|
restricted: isRestricted(metadata.restricted, role),
|
|
116
142
|
}
|
|
@@ -133,7 +159,8 @@ export const realAuth: AuthPort = {
|
|
|
133
159
|
},
|
|
134
160
|
|
|
135
161
|
async signOut(): Promise<void> {
|
|
136
|
-
// Server-side revocation
|
|
162
|
+
// Server-side revocation only: the browser keeps its short-lived session token until it lapses, so a page that must
|
|
163
|
+
// show the person signed out at once also signs out through Clerk's client (./account-refused-form.tsx does).
|
|
137
164
|
const { sessionId } = await auth()
|
|
138
165
|
if (!sessionId) return
|
|
139
166
|
const client = await clerkClient()
|
|
@@ -186,7 +213,12 @@ export const realAuth: AuthPort = {
|
|
|
186
213
|
if (user.banned) return null
|
|
187
214
|
const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
|
|
188
215
|
const role = roleFrom(membership.publicMetadata)
|
|
189
|
-
return {
|
|
216
|
+
return {
|
|
217
|
+
role,
|
|
218
|
+
restricted: isRestricted(metadata.restricted, role),
|
|
219
|
+
name: user.fullName ?? null,
|
|
220
|
+
email: user.primaryEmailAddress?.emailAddress ?? '',
|
|
221
|
+
}
|
|
190
222
|
},
|
|
191
223
|
|
|
192
224
|
async listMembers(orgSlug: string): Promise<Membership[]> {
|
|
@@ -230,7 +262,7 @@ export const realAuth: AuthPort = {
|
|
|
230
262
|
*
|
|
231
263
|
* The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
|
|
232
264
|
* absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
|
|
233
|
-
* (`localhost`), not the app's (
|
|
265
|
+
* (`localhost`), not the app's (safeinsights/sssb#131).
|
|
234
266
|
*/
|
|
235
267
|
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
236
268
|
const { userId } = await auth()
|
|
@@ -276,3 +308,40 @@ export const realAuth: AuthPort = {
|
|
|
276
308
|
await client.users.updateUserMetadata(userId, { unsafeMetadata: { currentOrgSlug: orgSlug } })
|
|
277
309
|
},
|
|
278
310
|
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Clerk's accounts as the auth settings see them (../configured-auth.ts): who is signed in and whether an account may
|
|
314
|
+
* still act, with no organization or role in it, so a fixed org source makes no membership call per request. A banned
|
|
315
|
+
* account may not act, as `getMember` says above; a locked one may, for the reason given there.
|
|
316
|
+
*/
|
|
317
|
+
export const clerkIdentitySource: ProviderIdentitySource = {
|
|
318
|
+
async current() {
|
|
319
|
+
const { userId } = await auth()
|
|
320
|
+
if (!userId) return null
|
|
321
|
+
const user = await currentUser()
|
|
322
|
+
if (!user) return null
|
|
323
|
+
return {
|
|
324
|
+
id: userId,
|
|
325
|
+
name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
|
|
326
|
+
email: user.primaryEmailAddress?.emailAddress ?? '',
|
|
327
|
+
locale: localeFrom(user.publicMetadata),
|
|
328
|
+
tenantClaim: tenantClaim(user.publicMetadata),
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
async account(userId) {
|
|
332
|
+
const client = await clerkClient()
|
|
333
|
+
let user
|
|
334
|
+
try {
|
|
335
|
+
user = await client.users.getUser(userId)
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (isClerkAPIResponseError(error) && error.status === 404) return null
|
|
338
|
+
throw error
|
|
339
|
+
}
|
|
340
|
+
if (user.banned) return null
|
|
341
|
+
return {
|
|
342
|
+
tenantClaim: tenantClaim(user.publicMetadata),
|
|
343
|
+
name: user.fullName ?? null,
|
|
344
|
+
email: user.primaryEmailAddress?.emailAddress ?? '',
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { staffOrgSlug } from '@sssb/app-config/abilities'
|
|
1
2
|
import type { AnalyticsPort } from '../../ports/analytics'
|
|
2
3
|
import type { AuthPort } from '../../ports/auth'
|
|
3
4
|
import type { DbPort } from '../../ports/db'
|
|
@@ -7,7 +8,10 @@ import type { JobsPort } from '../../ports/jobs'
|
|
|
7
8
|
import type { LlmPort } from '../../ports/llm'
|
|
8
9
|
import type { StoragePort } from '../../ports/storage'
|
|
9
10
|
import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
|
|
10
|
-
import {
|
|
11
|
+
import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
|
|
12
|
+
import { configuredAuth } from '../configured-auth'
|
|
13
|
+
import { orgNameForSlugs } from '../../db/org-lookup'
|
|
14
|
+
import { clerkIdentitySource, realAuth } from './auth'
|
|
11
15
|
import { DATABASE_ENV, databaseTransport } from './database-transport'
|
|
12
16
|
import { noAnalytics } from './no-analytics'
|
|
13
17
|
import { optionalPortsEnv, portChoice } from './optional-ports'
|
|
@@ -49,6 +53,7 @@ export function assertRealEnv(): void {
|
|
|
49
53
|
...DATABASE_ENV[transport],
|
|
50
54
|
...(transport === 'data-api' ? DATA_API_REGION_ENV : {}),
|
|
51
55
|
...optionalPortsEnv(),
|
|
56
|
+
...authRequiredEnv(),
|
|
52
57
|
}
|
|
53
58
|
const missing = Object.keys(required).filter((name) => !process.env[name])
|
|
54
59
|
if (missing.length > 0) {
|
|
@@ -69,6 +74,15 @@ export function assertRealEnv(): void {
|
|
|
69
74
|
throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
|
|
70
75
|
}
|
|
71
76
|
}
|
|
77
|
+
// The auth settings: an unknown choice, a malformed slug, key or role, a setting its choice does not use, or a fixed
|
|
78
|
+
// org source that would hand everyone the staff org's manage-all.
|
|
79
|
+
let problem: string | null
|
|
80
|
+
try {
|
|
81
|
+
problem = fixedOrgProblem(authSettings().orgSource, staffOrgSlug)
|
|
82
|
+
} catch (error) {
|
|
83
|
+
problem = (error as Error).message
|
|
84
|
+
}
|
|
85
|
+
if (problem) throw new CutoverPendingError(['auth-tenancy'], problem)
|
|
72
86
|
}
|
|
73
87
|
|
|
74
88
|
/**
|
|
@@ -114,6 +128,12 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
114
128
|
region: need('AWS_REGION'),
|
|
115
129
|
})
|
|
116
130
|
: (await import('./db')).createRealDb(need('DATABASE_URL'))
|
|
131
|
+
// Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
|
|
132
|
+
// reaches the people (the in-process runner's job context included) is handed this one. A fixed org source names
|
|
133
|
+
// its home org from the database's org row.
|
|
134
|
+
const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug, (tenant, org) =>
|
|
135
|
+
orgNameForSlugs(db, tenant, org),
|
|
136
|
+
)
|
|
117
137
|
const storageChoice = portChoice('storage')
|
|
118
138
|
const storage =
|
|
119
139
|
storageChoice === 's3'
|
|
@@ -144,7 +164,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
144
164
|
runner === 'codebuild'
|
|
145
165
|
? (await import('./jobs')).createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION'))
|
|
146
166
|
: runner === 'in-process'
|
|
147
|
-
? await inProcessJobs(hooks, { db, storage, email, llm, auth
|
|
167
|
+
? await inProcessJobs(hooks, { db, storage, email, llm, auth })
|
|
148
168
|
: absentJobs
|
|
149
169
|
// PostHog only where a key is configured (staging/prod per ADR-0010); a no-op otherwise (./no-analytics.ts), never
|
|
150
170
|
// the simulated world's fake, which writes under `.data/`.
|
|
@@ -152,7 +172,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
152
172
|
? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
|
|
153
173
|
: noAnalytics
|
|
154
174
|
return {
|
|
155
|
-
auth
|
|
175
|
+
auth,
|
|
156
176
|
db,
|
|
157
177
|
storage,
|
|
158
178
|
llm,
|
|
@@ -16,12 +16,18 @@ import {
|
|
|
16
16
|
PostgresIntrospector,
|
|
17
17
|
PostgresQueryCompiler,
|
|
18
18
|
type DatabaseConnection,
|
|
19
|
+
type ColumnMetadata,
|
|
20
|
+
type DatabaseIntrospector,
|
|
21
|
+
type DatabaseMetadataOptions,
|
|
19
22
|
type Dialect,
|
|
20
23
|
type Driver,
|
|
21
24
|
type Kysely,
|
|
22
25
|
type QueryResult,
|
|
26
|
+
type SchemaMetadata,
|
|
27
|
+
type TableMetadata,
|
|
23
28
|
type TransactionSettings,
|
|
24
29
|
} from 'kysely'
|
|
30
|
+
import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE } from 'kysely/migration'
|
|
25
31
|
import {
|
|
26
32
|
castPlaceholder,
|
|
27
33
|
commitOutcome,
|
|
@@ -91,10 +97,121 @@ export class RdsDataDialect implements Dialect {
|
|
|
91
97
|
}
|
|
92
98
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
93
99
|
createIntrospector(db: Kysely<any>) {
|
|
94
|
-
return new
|
|
100
|
+
return new RdsDataIntrospector(db)
|
|
95
101
|
}
|
|
96
102
|
}
|
|
97
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Kysely's Postgres introspector, with the one column the Data API cannot return cast to text. Kysely's `getTables`
|
|
106
|
+
* selects `pg_class.relkind`, a one-byte `"char"`, which the Data API refuses whole ("The result contains the
|
|
107
|
+
* unsupported data type "CHAR"", ./rds-data-emulator.ts's `REFUSED_RESULT_TYPES`), and its Migrator calls it before
|
|
108
|
+
* anything else, to see whether its own tables exist. So this is Kysely 0.29's query and its reading of the rows, with
|
|
109
|
+
* `relkind::text` for `relkind`; `getSchemas` reads only `nspname`, a `name`, and is Kysely's own. The contract suite
|
|
110
|
+
* (./rds-data.contract.test.ts) holds it to Kysely's introspector on the same database, so an upgrade of Kysely that
|
|
111
|
+
* changes what `getTables` returns fails there.
|
|
112
|
+
*/
|
|
113
|
+
export class RdsDataIntrospector implements DatabaseIntrospector {
|
|
114
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
115
|
+
readonly #db: Kysely<any>
|
|
116
|
+
readonly #postgres: PostgresIntrospector
|
|
117
|
+
|
|
118
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
119
|
+
constructor(db: Kysely<any>) {
|
|
120
|
+
this.#db = db
|
|
121
|
+
this.#postgres = new PostgresIntrospector(db)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
getSchemas(): Promise<SchemaMetadata[]> {
|
|
125
|
+
return this.#postgres.getSchemas()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async getTables(options: DatabaseMetadataOptions = { withInternalKyselyTables: false }): Promise<TableMetadata[]> {
|
|
129
|
+
let query = this.#db
|
|
130
|
+
.selectFrom('pg_catalog.pg_attribute as a')
|
|
131
|
+
.innerJoin('pg_catalog.pg_class as c', 'a.attrelid', 'c.oid')
|
|
132
|
+
.innerJoin('pg_catalog.pg_namespace as ns', 'c.relnamespace', 'ns.oid')
|
|
133
|
+
.innerJoin('pg_catalog.pg_type as typ', 'a.atttypid', 'typ.oid')
|
|
134
|
+
.innerJoin('pg_catalog.pg_namespace as dtns', 'typ.typnamespace', 'dtns.oid')
|
|
135
|
+
.select([
|
|
136
|
+
'a.attname as column',
|
|
137
|
+
'a.attnotnull as not_null',
|
|
138
|
+
'a.atthasdef as has_default',
|
|
139
|
+
'c.relname as table',
|
|
140
|
+
sql<string>`c.relkind::text`.as('table_type'),
|
|
141
|
+
'ns.nspname as schema',
|
|
142
|
+
'typ.typname as type',
|
|
143
|
+
'dtns.nspname as type_schema',
|
|
144
|
+
sql<string | null>`col_description(a.attrelid, a.attnum)`.as('column_description'),
|
|
145
|
+
sql<
|
|
146
|
+
string | null
|
|
147
|
+
>`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(
|
|
148
|
+
'auto_incrementing',
|
|
149
|
+
),
|
|
150
|
+
])
|
|
151
|
+
.where('c.relkind', 'in', ['r', 'v', 'p', 'f'])
|
|
152
|
+
.where('ns.nspname', '!~', '^pg_')
|
|
153
|
+
.where('ns.nspname', '!=', 'information_schema')
|
|
154
|
+
.where('ns.nspname', '!=', 'crdb_internal')
|
|
155
|
+
.where(sql<boolean>`has_schema_privilege(ns.nspname, 'USAGE')`)
|
|
156
|
+
.where('a.attnum', '>=', 0)
|
|
157
|
+
.where('a.attisdropped', '!=', true)
|
|
158
|
+
.orderBy('ns.nspname')
|
|
159
|
+
.orderBy('c.relname')
|
|
160
|
+
.orderBy('a.attnum')
|
|
161
|
+
.$castTo<IntrospectedColumn>()
|
|
162
|
+
if (!options.withInternalKyselyTables) {
|
|
163
|
+
query = query
|
|
164
|
+
.where('c.relname', '!=', DEFAULT_MIGRATION_TABLE)
|
|
165
|
+
.where('c.relname', '!=', DEFAULT_MIGRATION_LOCK_TABLE)
|
|
166
|
+
}
|
|
167
|
+
const tables: TableMetadata[] = []
|
|
168
|
+
const bySchema = new Map<string, Map<string, TableMetadata>>()
|
|
169
|
+
for (const column of await query.execute()) {
|
|
170
|
+
let schema = bySchema.get(column.schema)
|
|
171
|
+
if (!schema) bySchema.set(column.schema, (schema = new Map()))
|
|
172
|
+
let table = schema.get(column.table)
|
|
173
|
+
if (!table) {
|
|
174
|
+
table = Object.freeze({
|
|
175
|
+
columns: [],
|
|
176
|
+
isForeign: column.table_type === 'f',
|
|
177
|
+
isView: column.table_type === 'v',
|
|
178
|
+
name: column.table,
|
|
179
|
+
schema: column.schema,
|
|
180
|
+
})
|
|
181
|
+
schema.set(column.table, table)
|
|
182
|
+
tables.push(table)
|
|
183
|
+
}
|
|
184
|
+
table.columns.push(
|
|
185
|
+
// `comment` present and undefined on an uncommented column, as Kysely's is: the cast is
|
|
186
|
+
// exactOptionalPropertyTypes', which Kysely's own type does not satisfy either.
|
|
187
|
+
Object.freeze({
|
|
188
|
+
comment: column.column_description ?? undefined,
|
|
189
|
+
dataType: column.type,
|
|
190
|
+
dataTypeSchema: column.type_schema,
|
|
191
|
+
hasDefaultValue: column.has_default,
|
|
192
|
+
isAutoIncrementing: column.auto_incrementing !== null,
|
|
193
|
+
isNullable: !column.not_null,
|
|
194
|
+
name: column.column,
|
|
195
|
+
} as ColumnMetadata),
|
|
196
|
+
)
|
|
197
|
+
}
|
|
198
|
+
return tables
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
interface IntrospectedColumn {
|
|
203
|
+
column: string
|
|
204
|
+
not_null: boolean
|
|
205
|
+
has_default: boolean
|
|
206
|
+
table: string
|
|
207
|
+
table_type: string
|
|
208
|
+
schema: string
|
|
209
|
+
type: string
|
|
210
|
+
type_schema: string
|
|
211
|
+
column_description: string | null
|
|
212
|
+
auto_incrementing: string | null
|
|
213
|
+
}
|
|
214
|
+
|
|
98
215
|
/** Kysely's own Postgres migration-lock id, so a `pg` migrator and a Data API one exclude each other. */
|
|
99
216
|
const MIGRATION_LOCK_ID = '3853314791062309107'
|
|
100
217
|
|
|
@@ -30,7 +30,10 @@ import type { RdsDataClientLike, RdsDataCommand } from './rds-data-dialect'
|
|
|
30
30
|
* - a statement inside a transaction runs on that transaction's one connection, until Commit/Rollback;
|
|
31
31
|
* - a response over 1 MiB is refused, and an unknown transaction id is TransactionNotFoundException;
|
|
32
32
|
* - database errors come back as a message only, WITHOUT a SQLSTATE — the least the Data API is
|
|
33
|
-
* reported to give, so what is proven is that SSSB's error handling survives the worst case
|
|
33
|
+
* reported to give, so what is proven is that SSSB's error handling survives the worst case;
|
|
34
|
+
* - a result with a column of a type the Data API refuses is refused whole, rows or none, with its
|
|
35
|
+
* `UnsupportedResultException`, after the statement has run (REFUSED_RESULT_TYPES says which types, and on what
|
|
36
|
+
* evidence, some of it inferred).
|
|
34
37
|
*
|
|
35
38
|
* What it cannot know is AWS's exact wire format (column `typeName`s, timestamp strings, error wording).
|
|
36
39
|
* It follows PgJDBC's conventions, which the Data API is built on; the `data-api` cutover row is the live
|
|
@@ -44,6 +47,30 @@ export interface EmulatedCall {
|
|
|
44
47
|
|
|
45
48
|
const RESPONSE_LIMIT_BYTES = 1024 * 1024
|
|
46
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Result column types the Data API refuses, seen or inferred, by `pg_type.typname`, with the name its error gives them. AWS lists none:
|
|
52
|
+
* "The Data API doesn't support all data types", and the fix it gives is a cast to TEXT (the Aurora User Guide's
|
|
53
|
+
* "Troubleshooting Amazon RDS Data API", "Unsupported result exception"). What is here is evidence:
|
|
54
|
+
*
|
|
55
|
+
* - `char`, Postgres's one-byte "char" (`pg_class.relkind`): refused live on Aurora PostgreSQL with
|
|
56
|
+
* `UnsupportedResultException: The result contains the unsupported data type "CHAR"`, for a result of no rows (Kysely's
|
|
57
|
+
* introspector, on a database with no tables yet), so the refusal reads the columns, not the values;
|
|
58
|
+
* - `bpchar`, `char(n)`: the same JDBC type, `CHAR`, in PgJDBC's type map, on which the Data API is built, so the same
|
|
59
|
+
* error, if the error's "CHAR" is that JDBC type and not the type's own name upper-cased; inferred, not observed;
|
|
60
|
+
* - `_char` and `_bpchar`, arrays of the two, whose elements the Data API would have to return as the same type;
|
|
61
|
+
* inferred, not observed.
|
|
62
|
+
*
|
|
63
|
+
* Strict where unobserved, so a query passes here only if it passes on the evidence's worst reading; a cast to text
|
|
64
|
+
* costs nothing. The `data-api` cutover row's smoke run (`docs/runbooks/data-api.md`, step 3) records what AWS does
|
|
65
|
+
* with each, and a type it answers leaves this map, as one it refuses joins it.
|
|
66
|
+
*/
|
|
67
|
+
const REFUSED_RESULT_TYPES: ReadonlyMap<string, string> = new Map([
|
|
68
|
+
['char', 'CHAR'],
|
|
69
|
+
['bpchar', 'CHAR'],
|
|
70
|
+
['_char', 'CHAR'],
|
|
71
|
+
['_bpchar', 'CHAR'],
|
|
72
|
+
])
|
|
73
|
+
|
|
47
74
|
export class RdsDataEmulator implements RdsDataClientLike {
|
|
48
75
|
/** Every call, in order — the contract suite asserts on the transaction sequence. */
|
|
49
76
|
readonly calls: EmulatedCall[] = []
|
|
@@ -161,6 +188,13 @@ export class RdsDataEmulator implements RdsDataClientLike {
|
|
|
161
188
|
client,
|
|
162
189
|
result.fields.map((field) => field.dataTypeID),
|
|
163
190
|
)
|
|
191
|
+
const refused = result.fields.find((field) =>
|
|
192
|
+
REFUSED_RESULT_TYPES.has(typeNames.get(field.dataTypeID) ?? ''),
|
|
193
|
+
)
|
|
194
|
+
if (refused) {
|
|
195
|
+
const name = REFUSED_RESULT_TYPES.get(typeNames.get(refused.dataTypeID)!)
|
|
196
|
+
throw awsError('UnsupportedResultException', `The result contains the unsupported data type "${name}"`)
|
|
197
|
+
}
|
|
164
198
|
const longAsString = input.resultSetOptions?.longReturnType === 'STRING'
|
|
165
199
|
const columns: ColumnMetadata[] = result.fields.map((field) => ({
|
|
166
200
|
name: field.name,
|
package/src/authz/authorize.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
type SubjectType,
|
|
11
11
|
defineAbilitiesFor,
|
|
12
12
|
} from '../core/abilities'
|
|
13
|
+
import { hasStanding } from '../core/roles'
|
|
13
14
|
import type { OrgIdentity } from '../db/org-lookup'
|
|
14
15
|
import type { AuthPort, AuthUser } from '../ports/auth'
|
|
15
16
|
import { ForbiddenError } from '../ports/errors'
|
|
@@ -48,7 +49,9 @@ export function abilityActorFromUser(user: AuthUser, activeOrgId: string): Abili
|
|
|
48
49
|
role: user.role,
|
|
49
50
|
restricted: user.restricted,
|
|
50
51
|
activeOrgId,
|
|
51
|
-
|
|
52
|
+
// Not for a person without standing (role `none`): a fixed org source places every user of the identity
|
|
53
|
+
// provider in the home org, which may be the staff org. The ability layer refuses it again (defineAbilitiesFor).
|
|
54
|
+
manageAll: user.orgSlug === staffOrgSlug && hasStanding(user.role),
|
|
52
55
|
}
|
|
53
56
|
}
|
|
54
57
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { Alert, Button, Stack, Text } from '@mantine/core'
|
|
4
|
+
import { useTranslations } from 'next-intl'
|
|
5
|
+
import { useState } from 'react'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The sign-in card's body for a person the identity provider has signed in but this app refuses
|
|
9
|
+
* (`AuthPort.refusal`): their account names another tenant, or holds something that is not a tenant at all, so it is
|
|
10
|
+
* taken to belong to another site. It says so, and offers one
|
|
11
|
+
* explicit sign-out. Never automatic: on a provider instance shared with another product, signing out ends the
|
|
12
|
+
* person's session there too, which the copy says before they choose.
|
|
13
|
+
*
|
|
14
|
+
* `onSignOut` answers whether the sign-out went through: `false` (or a rejection) shows the error and lets them try
|
|
15
|
+
* again; anything else keeps the spinner while the page navigates (a reload, or the provider's own redirect).
|
|
16
|
+
*/
|
|
17
|
+
export function AccountRefused({ onSignOut }: { onSignOut: () => void | Promise<boolean | void> }) {
|
|
18
|
+
const t = useTranslations('auth')
|
|
19
|
+
const [busy, setBusy] = useState(false)
|
|
20
|
+
const [failed, setFailed] = useState(false)
|
|
21
|
+
|
|
22
|
+
async function signOut() {
|
|
23
|
+
setBusy(true)
|
|
24
|
+
setFailed(false)
|
|
25
|
+
try {
|
|
26
|
+
if ((await onSignOut()) === false) {
|
|
27
|
+
setBusy(false)
|
|
28
|
+
setFailed(true)
|
|
29
|
+
}
|
|
30
|
+
} catch {
|
|
31
|
+
setBusy(false)
|
|
32
|
+
setFailed(true)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return (
|
|
37
|
+
<Stack gap="sm" data-testid="account-refused">
|
|
38
|
+
<Text fw={600}>{t('refusedTitle')}</Text>
|
|
39
|
+
<Text size="sm">{t('refusedBody')}</Text>
|
|
40
|
+
<Text size="sm" c="gray.7">
|
|
41
|
+
{t('refusedSignOutNote')}
|
|
42
|
+
</Text>
|
|
43
|
+
{failed ? (
|
|
44
|
+
<Alert color="red" role="alert">
|
|
45
|
+
{t('refusedSignOutError')}
|
|
46
|
+
</Alert>
|
|
47
|
+
) : null}
|
|
48
|
+
<Button onClick={() => void signOut()} loading={busy} data-testid="account-refused-signout">
|
|
49
|
+
{t('signOut')}
|
|
50
|
+
</Button>
|
|
51
|
+
</Stack>
|
|
52
|
+
)
|
|
53
|
+
}
|
package/src/core/abilities.ts
CHANGED
|
@@ -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
|
-
|
|
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(
|
|
422
|
+
return appAbilityRules(ruleActor, action, subject, { sameOrg: personSameOrg })
|
|
407
423
|
}
|
|
408
424
|
}
|
|
409
425
|
|
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
|
-
|
|
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
|
}
|
package/src/cutover/rows.json
CHANGED
|
@@ -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/family.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { runWithTenant } from './with-tenant'
|
|
|
8
8
|
/**
|
|
9
9
|
* The database family (ADR-0015, second addendum, point 3): what is specific to one database engine, gathered behind
|
|
10
10
|
* one object so the framework's logic stays generic over the engine. SSSB has one family today, Postgres, with three
|
|
11
|
-
* transports (pglite, node-postgres, the RDS Data API); a second family (libsql,
|
|
11
|
+
* transports (pglite, node-postgres, the RDS Data API); a second family (libsql, safeinsights/sssb#174)
|
|
12
12
|
* is a second object of this shape, not a fork of the data layer.
|
|
13
13
|
*
|
|
14
14
|
* A family owns:
|