@fabrika/platform-node 0.9.0-dev.20 → 0.9.0-dev.22
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/platform-node",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.22",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
"test": "bun test"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
41
|
+
"@fabrika/platform": "0.9.0-dev.22"
|
|
42
42
|
}
|
|
43
43
|
}
|
package/src/index.ts
CHANGED
|
@@ -70,7 +70,6 @@ export {
|
|
|
70
70
|
readPostgresMigrationBundle,
|
|
71
71
|
type ReadPostgresMigrationBundleOptions,
|
|
72
72
|
} from './postgres-migrations'
|
|
73
|
-
export { createTestProvisioner, type TestProvisioner } from './postgres-test-provisioner'
|
|
74
73
|
export {
|
|
75
74
|
definePostgresServiceMigrations,
|
|
76
75
|
postgresMigrationResultMessage,
|
package/types/src/index.d.ts
CHANGED
|
@@ -9,7 +9,6 @@ export { decodeJob, type Job, PostgresJobConsumer, type PostgresJobConsumerOptio
|
|
|
9
9
|
export type { DatabaseObject, DatabaseObjectKind } from './migration-classify';
|
|
10
10
|
export { rewritePlaceholders, type RewrittenSql } from './placeholders';
|
|
11
11
|
export { applyPostgresMigrations, definePostgresMigrationPlan, migrationChecksum, platformNodePostgresMigrationBundle, type PostgresApplicationMigrationSettings, type PostgresMigration, type PostgresMigrationBundle, PostgresMigrationError, postgresMigrationFilenames, postgresMigrationIdentity, type PostgresMigrationPlan, readPostgresMigrationBundle, type ReadPostgresMigrationBundleOptions, } from './postgres-migrations';
|
|
12
|
-
export { createTestProvisioner, type TestProvisioner } from './postgres-test-provisioner';
|
|
13
12
|
export { definePostgresServiceMigrations, postgresMigrationResultMessage, type PostgresServiceMigrations, type PostgresServiceMigrationsConfig, } from './service-postgres-migrations';
|
|
14
13
|
export { PostgresDatabase, PostgresStatement, type SqlBindValue } from './sql-postgres';
|
|
15
14
|
export { type BackgroundTasks, type BackgroundTasksOptions, createBackgroundTasks } from './wait-until';
|
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
import type { SqlDatabase } from '@fabrika/platform'
|
|
2
|
-
import { createHash, randomBytes } from 'node:crypto'
|
|
3
|
-
import { provisioningCredential, quotedIdentifier, scramVerifier } from './application-postgres-roles'
|
|
4
|
-
import { PostgresMigrationError } from './postgres-migration-error'
|
|
5
|
-
import { PostgresDatabase } from './sql-postgres'
|
|
6
|
-
|
|
7
|
-
/** A provisioning credential that exists for one test run only, and what it created. */
|
|
8
|
-
export interface TestProvisioner {
|
|
9
|
-
/**
|
|
10
|
-
* Connects as `fabrika_tests_<hex>`: CREATEROLE and CREATE on the database, nothing of any application, and a login
|
|
11
|
-
* for `TEST_PROVISIONER_LIFETIME_MINUTES` only.
|
|
12
|
-
*/
|
|
13
|
-
readonly url: string
|
|
14
|
-
/** The provisioners of earlier runs that creating this one dropped. Role names, never a credential. */
|
|
15
|
-
readonly swept: readonly string[]
|
|
16
|
-
/** Drops every role the provisioner created, with everything those roles own, then the provisioner itself. */
|
|
17
|
-
drop(): Promise<void>
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Every grant or revoke on a database changes its one `pg_database` row, and two concurrent changes of that row fail with
|
|
22
|
-
* `tuple concurrently updated`, so each change waits for this transaction-level lock first.
|
|
23
|
-
*/
|
|
24
|
-
export const DATABASE_GRANT_LOCK_KEY: number = createHash('sha256').update('fabrika-db:database-grants', 'utf8').digest().readUIntBE(0, 6) + 1
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Grants (or revokes) CREATE on `database` to `role`, serialized with every other run that does so on the same server.
|
|
28
|
-
* Verified afterwards: a grantor that neither owns the database, is a superuser nor holds CREATE WITH GRANT OPTION only
|
|
29
|
-
* gets a WARNING, and the statement changes nothing.
|
|
30
|
-
*/
|
|
31
|
-
export async function changeCreateOnDatabase(admin: SqlDatabase, change: 'grant' | 'revoke', role: string, database: string): Promise<void> {
|
|
32
|
-
const statement = change === 'grant'
|
|
33
|
-
? `GRANT CREATE ON DATABASE ${quotedIdentifier(database)} TO ${quotedIdentifier(role)}`
|
|
34
|
-
: `REVOKE CREATE ON DATABASE ${quotedIdentifier(database)} FROM ${quotedIdentifier(role)}`
|
|
35
|
-
await admin.batch([admin.prepare(`SELECT pg_catalog.pg_advisory_xact_lock(${DATABASE_GRANT_LOCK_KEY})`), admin.prepare(statement)])
|
|
36
|
-
const held = await admin.prepare("SELECT pg_catalog.has_database_privilege(?, ?, 'CREATE') AS creates").bind(role, database).first<{
|
|
37
|
-
creates: boolean
|
|
38
|
-
}>()
|
|
39
|
-
if ((held?.creates ?? false) !== (change === 'grant')) {
|
|
40
|
-
throw new PostgresMigrationError(
|
|
41
|
-
`the provisioning credential could not ${change} CREATE on the database ${database} ${
|
|
42
|
-
change === 'grant' ? 'to' : 'from'
|
|
43
|
-
} ${role}: it must own the database, be a superuser, or hold CREATE on it WITH GRANT OPTION`,
|
|
44
|
-
)
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** Before Postgres 16, CREATEROLE may grant membership in any role that is not a superuser, `pg_execute_server_program` included. */
|
|
49
|
-
const MINIMUM_SERVER_VERSION = 160000
|
|
50
|
-
|
|
51
|
-
/** A provisioner's name. The sweep selects by it, so a role of another kind never matches. */
|
|
52
|
-
const TEST_PROVISIONER_NAME = /^fabrika_tests_[0-9a-f]{16}$/
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* How long a provisioner can log in (`VALID UNTIL`). A run that a kill stopped before `drop()` leaves its provisioner
|
|
56
|
-
* behind, and nobody knows its password; after this time it also cannot log in, and the next run's sweep drops it. A
|
|
57
|
-
* run makes new connections until it ends, so this is far beyond the longest run.
|
|
58
|
-
*/
|
|
59
|
-
export const TEST_PROVISIONER_LIFETIME_MINUTES = 15
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* The session-level lock one sweep holds. A run that does not get it skips its sweep: the run that holds it is sweeping
|
|
63
|
-
* the same leftovers, and any role may take any advisory lock, so a run never waits for it.
|
|
64
|
-
*/
|
|
65
|
-
const SWEEP_LOCK_KEY: number = createHash('sha256').update('fabrika-db:test-provisioner-sweep', 'utf8').digest().readUIntBE(0, 6) + 1
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Creates a throwaway provisioning credential for code the platform runs but did not write, such as an application's
|
|
69
|
-
* generated tests: it can create the test kit's role families and schemas, and reaches no application's data, because
|
|
70
|
-
* a CREATEROLE role administers only the roles it created. The provisioning credential itself never leaves this process.
|
|
71
|
-
* First it drops the provisioners earlier runs left behind (`sweepTestProvisioners`).
|
|
72
|
-
*/
|
|
73
|
-
export async function createTestProvisioner(provisioningUrl: string): Promise<TestProvisioner> {
|
|
74
|
-
const { url } = provisioningCredential(provisioningUrl)
|
|
75
|
-
const name = `fabrika_tests_${randomBytes(8).toString('hex')}`
|
|
76
|
-
const password = randomBytes(32).toString('base64url')
|
|
77
|
-
const admin = PostgresDatabase.connect(provisioningUrl, { max: 1 })
|
|
78
|
-
try {
|
|
79
|
-
const self = await admin.prepare(`SELECT rolsuper, rolcreaterole, pg_catalog.current_setting('server_version_num')::int AS version,
|
|
80
|
-
pg_catalog.current_database() AS database,
|
|
81
|
-
pg_catalog.quote_literal((pg_catalog.now() + interval '${TEST_PROVISIONER_LIFETIME_MINUTES} minutes')::text) AS valid_until
|
|
82
|
-
FROM pg_catalog.pg_roles WHERE rolname = current_user`).first<{
|
|
83
|
-
rolsuper: boolean
|
|
84
|
-
rolcreaterole: boolean
|
|
85
|
-
version: number
|
|
86
|
-
database: string
|
|
87
|
-
valid_until: string
|
|
88
|
-
}>()
|
|
89
|
-
if (self === null || (!self.rolsuper && !self.rolcreaterole)) {
|
|
90
|
-
throw new PostgresMigrationError(
|
|
91
|
-
'the provisioning credential is neither a superuser nor holds CREATEROLE, so it cannot create the test run its own',
|
|
92
|
-
)
|
|
93
|
-
}
|
|
94
|
-
if (self.version < MINIMUM_SERVER_VERSION) {
|
|
95
|
-
throw new PostgresMigrationError(
|
|
96
|
-
'the test run needs Postgres 16 or later: before 16, a CREATEROLE role may grant itself any role that is not a superuser',
|
|
97
|
-
)
|
|
98
|
-
}
|
|
99
|
-
const swept = await sweepTestProvisioners(admin, self.database)
|
|
100
|
-
await admin.prepare(`CREATE ROLE ${name} LOGIN CREATEROLE NOINHERIT PASSWORD '${scramVerifier(password)}' VALID UNTIL ${self.valid_until}`).run()
|
|
101
|
-
try {
|
|
102
|
-
await changeCreateOnDatabase(admin, 'grant', name, self.database)
|
|
103
|
-
} catch (error) {
|
|
104
|
-
await admin.prepare(`DROP ROLE ${name}`).run()
|
|
105
|
-
throw error
|
|
106
|
-
}
|
|
107
|
-
const database = self.database
|
|
108
|
-
url.username = name
|
|
109
|
-
url.password = password
|
|
110
|
-
return { url: url.toString(), swept, drop: () => dropTestProvisioner(provisioningUrl, name, database) }
|
|
111
|
-
} finally {
|
|
112
|
-
await admin.close()
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async function dropTestProvisioner(provisioningUrl: string, name: string, database: string): Promise<void> {
|
|
117
|
-
const admin = PostgresDatabase.connect(provisioningUrl, { max: 1 })
|
|
118
|
-
try {
|
|
119
|
-
await dropProvisioner(admin, name, database)
|
|
120
|
-
} finally {
|
|
121
|
-
await admin.close()
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* As the provisioning credential: drops every provisioner an earlier run left behind (a run killed before `drop()`),
|
|
127
|
-
* with everything it administers. A leftover is one past its `VALID UNTIL`, or without one (a release before it), that
|
|
128
|
-
* the credential administers, that holds CREATE on no other database, and that has no session, neither as itself nor as
|
|
129
|
-
* a role it created. A concurrent run's provisioner is still valid; a session keeps one that outlived its validity.
|
|
130
|
-
*/
|
|
131
|
-
async function sweepTestProvisioners(admin: SqlDatabase, database: string): Promise<readonly string[]> {
|
|
132
|
-
const lock = await admin.prepare(`SELECT pg_catalog.pg_try_advisory_lock(${SWEEP_LOCK_KEY}) AS locked`).first<{ locked: boolean }>()
|
|
133
|
-
if (lock?.locked !== true) return []
|
|
134
|
-
try {
|
|
135
|
-
const { results } = await admin.prepare(`SELECT r.rolname AS name FROM pg_catalog.pg_roles r
|
|
136
|
-
WHERE r.rolname ~ ?
|
|
137
|
-
AND (r.rolvaliduntil IS NULL OR r.rolvaliduntil < pg_catalog.now())
|
|
138
|
-
AND pg_catalog.pg_has_role(r.oid, 'MEMBER WITH ADMIN OPTION')
|
|
139
|
-
AND NOT EXISTS (SELECT FROM pg_catalog.pg_database d
|
|
140
|
-
WHERE d.datname <> pg_catalog.current_database() AND pg_catalog.has_database_privilege(r.oid, d.oid, 'CREATE'))
|
|
141
|
-
AND NOT EXISTS (SELECT FROM pg_catalog.pg_stat_activity a
|
|
142
|
-
WHERE a.usesysid = r.oid
|
|
143
|
-
OR a.usesysid IN (SELECT m.roleid FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid AND m.admin_option))
|
|
144
|
-
ORDER BY 1`).bind(TEST_PROVISIONER_NAME.source).all<{ name: string }>()
|
|
145
|
-
const swept: string[] = []
|
|
146
|
-
for (const { name } of results) {
|
|
147
|
-
if (!TEST_PROVISIONER_NAME.test(name)) continue
|
|
148
|
-
await dropProvisioner(admin, name, database)
|
|
149
|
-
swept.push(name)
|
|
150
|
-
}
|
|
151
|
-
return swept
|
|
152
|
-
} finally {
|
|
153
|
-
await admin.prepare(`SELECT pg_catalog.pg_advisory_unlock(${SWEEP_LOCK_KEY})`).run()
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/** As the provisioning credential: the provisioner's roles with what they own, its CREATE on `database`, then itself. */
|
|
158
|
-
async function dropProvisioner(admin: SqlDatabase, name: string, database: string): Promise<void> {
|
|
159
|
-
await admin.prepare(`GRANT ${name} TO CURRENT_USER`).run()
|
|
160
|
-
await dropCreatedRoles(admin, name)
|
|
161
|
-
await changeCreateOnDatabase(admin, 'revoke', name, database)
|
|
162
|
-
await admin.prepare(`DROP ROLE ${name}`).run()
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** As the provisioner: each role it administers, made its own for a moment so that its objects can be dropped, then dropped. */
|
|
166
|
-
async function dropCreatedRoles(admin: SqlDatabase, name: string): Promise<void> {
|
|
167
|
-
const { results } = await admin.prepare(`SELECT pg_catalog.pg_get_userbyid(m.roleid) AS role FROM pg_catalog.pg_auth_members m
|
|
168
|
-
WHERE m.member = pg_catalog.to_regrole(?) AND m.admin_option ORDER BY 1`).bind(name).all<{ role: string }>()
|
|
169
|
-
for (const { role } of results) {
|
|
170
|
-
const quoted = quotedIdentifier(role)
|
|
171
|
-
await admin.batch([
|
|
172
|
-
admin.prepare(`SET LOCAL ROLE ${name}`),
|
|
173
|
-
admin.prepare(`GRANT ${quoted} TO ${name}`),
|
|
174
|
-
])
|
|
175
|
-
await admin.batch([admin.prepare(`SET LOCAL ROLE ${quoted}`), admin.prepare(`DROP OWNED BY ${quoted} CASCADE`)])
|
|
176
|
-
await admin.batch([admin.prepare(`SET LOCAL ROLE ${name}`), admin.prepare(`DROP ROLE ${quoted}`)])
|
|
177
|
-
}
|
|
178
|
-
}
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import type { SqlDatabase } from '@fabrika/platform';
|
|
2
|
-
/** A provisioning credential that exists for one test run only, and what it created. */
|
|
3
|
-
export interface TestProvisioner {
|
|
4
|
-
/**
|
|
5
|
-
* Connects as `fabrika_tests_<hex>`: CREATEROLE and CREATE on the database, nothing of any application, and a login
|
|
6
|
-
* for `TEST_PROVISIONER_LIFETIME_MINUTES` only.
|
|
7
|
-
*/
|
|
8
|
-
readonly url: string;
|
|
9
|
-
/** The provisioners of earlier runs that creating this one dropped. Role names, never a credential. */
|
|
10
|
-
readonly swept: readonly string[];
|
|
11
|
-
/** Drops every role the provisioner created, with everything those roles own, then the provisioner itself. */
|
|
12
|
-
drop(): Promise<void>;
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Every grant or revoke on a database changes its one `pg_database` row, and two concurrent changes of that row fail with
|
|
16
|
-
* `tuple concurrently updated`, so each change waits for this transaction-level lock first.
|
|
17
|
-
*/
|
|
18
|
-
export declare const DATABASE_GRANT_LOCK_KEY: number;
|
|
19
|
-
/**
|
|
20
|
-
* Grants (or revokes) CREATE on `database` to `role`, serialized with every other run that does so on the same server.
|
|
21
|
-
* Verified afterwards: a grantor that neither owns the database, is a superuser nor holds CREATE WITH GRANT OPTION only
|
|
22
|
-
* gets a WARNING, and the statement changes nothing.
|
|
23
|
-
*/
|
|
24
|
-
export declare function changeCreateOnDatabase(admin: SqlDatabase, change: 'grant' | 'revoke', role: string, database: string): Promise<void>;
|
|
25
|
-
/**
|
|
26
|
-
* How long a provisioner can log in (`VALID UNTIL`). A run that a kill stopped before `drop()` leaves its provisioner
|
|
27
|
-
* behind, and nobody knows its password; after this time it also cannot log in, and the next run's sweep drops it. A
|
|
28
|
-
* run makes new connections until it ends, so this is far beyond the longest run.
|
|
29
|
-
*/
|
|
30
|
-
export declare const TEST_PROVISIONER_LIFETIME_MINUTES = 15;
|
|
31
|
-
/**
|
|
32
|
-
* Creates a throwaway provisioning credential for code the platform runs but did not write, such as an application's
|
|
33
|
-
* generated tests: it can create the test kit's role families and schemas, and reaches no application's data, because
|
|
34
|
-
* a CREATEROLE role administers only the roles it created. The provisioning credential itself never leaves this process.
|
|
35
|
-
* First it drops the provisioners earlier runs left behind (`sweepTestProvisioners`).
|
|
36
|
-
*/
|
|
37
|
-
export declare function createTestProvisioner(provisioningUrl: string): Promise<TestProvisioner>;
|