@axiumine/qpanel-db-setup 0.0.0-stage → 0.9.0-rc.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.
- package/CHANGELOG.md +164 -0
- package/LICENSE +661 -0
- package/README.md +289 -2
- package/dist/migrations/20261127000000-create-enums-and-set-updated-at.mjs +25 -0
- package/dist/migrations/20261127000100-revoke-app-access-to-migration-tables.mjs +39 -0
- package/dist/migrations/20261127000200-create-admin.mjs +24 -0
- package/dist/migrations/20261127000300-create-secret.mjs +37 -0
- package/dist/migrations/20261127000400-create-audit-event.mjs +35 -0
- package/dist/migrations/20261127000500-create-registrar.mjs +27 -0
- package/dist/migrations/20261127000600-create-client.mjs +47 -0
- package/dist/migrations/20261127000700-create-client-note.mjs +22 -0
- package/dist/migrations/20261127000800-create-domain.mjs +37 -0
- package/dist/migrations/20261127000900-create-subdomain.mjs +24 -0
- package/dist/migrations/20261127001000-create-service.mjs +25 -0
- package/dist/migrations/20261127001100-create-datacenter.mjs +22 -0
- package/dist/migrations/20261127001200-create-db-instance.mjs +30 -0
- package/dist/migrations/20261127001300-create-db-instance-node.mjs +30 -0
- package/dist/migrations/20261127001400-create-db-account.mjs +34 -0
- package/dist/migrations/20261127001500-create-app-database.mjs +23 -0
- package/dist/migrations/20261127001600-create-app-database-user.mjs +31 -0
- package/dist/migrations/20261127001700-create-subdomain-app-database.mjs +25 -0
- package/dist/migrations/20261127001800-billing-fields.mjs +52 -0
- package/dist/migrations/20261128000000-secret-value-changed-at.mjs +25 -0
- package/dist/migrations/20261130000000-db-instance-environments.mjs +56 -0
- package/dist/migrations/20261130120000-create-server.mjs +50 -0
- package/dist/migrations/20261130200000-create-server-ssh-access.mjs +147 -0
- package/dist/migrations/20261201000000-ssh-login-per-way.mjs +129 -0
- package/dist/src/arguments.mjs +124 -0
- package/dist/src/bin.mjs +26 -0
- package/dist/src/cli.mjs +139 -0
- package/dist/src/create.mjs +40 -0
- package/dist/src/database.mjs +41 -0
- package/dist/src/env.mjs +49 -0
- package/dist/src/infisical.mjs +37 -0
- package/dist/src/keygrip.mjs +48 -0
- package/dist/src/masterKey.mjs +80 -0
- package/dist/src/masterKeyFile.mjs +66 -0
- package/dist/src/migrator.mjs +64 -0
- package/dist/src/redis.mjs +23 -0
- package/dist/src/secrets.mjs +96 -0
- package/dist/src/target.mjs +22 -0
- package/package.json +83 -4
- package/redis/bootstrap-acl.sh +130 -0
- package/sql/bootstrap.sql +218 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { sql } from 'kysely';
|
|
2
|
+
// The ways to log in of an SSH user become rows of their own (parent ADR-043): each keeps its own password, one-time code
|
|
3
|
+
// secret and notes, which a user had once for all of them.
|
|
4
|
+
//
|
|
5
|
+
// `ssh_login` is a way of a user, in the order of `position`, `0` first, so eight at most. `methods` is its methods in order
|
|
6
|
+
// joined with commas, as sshd's `AuthenticationMethods` writes them. A position is unique for its user, checked at the end
|
|
7
|
+
// of the transaction, so that two ways can change places. That a user has a way at least, and no way twice, is the service's
|
|
8
|
+
// to check: no constraint of a row sees the others. A deleted way takes its secrets with it, also when the delete cascades
|
|
9
|
+
// from the user or from the server.
|
|
10
|
+
//
|
|
11
|
+
// Going up, a user's ways come from `logins`, with the user's dates. The password goes to the first way that asks a password
|
|
12
|
+
// and the one-time code secret to the first way with `keyboard-interactive`, each to the first way when none does; the notes
|
|
13
|
+
// go to the first way. The `secret` rows are not touched: a ciphertext is bound to its row and its purpose, and both stay.
|
|
14
|
+
//
|
|
15
|
+
// Going down, a user has one password, one one-time code secret and one text of notes again: the notes of the ways, one after
|
|
16
|
+
// the other. A user whose ways keep two passwords, or two one-time code secrets, has no place for the second, so the revert
|
|
17
|
+
// refuses: no secret is lost to it.
|
|
18
|
+
export async function up(db) {
|
|
19
|
+
await sql `
|
|
20
|
+
CREATE TABLE qpanel.ssh_login (
|
|
21
|
+
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
|
22
|
+
id_ssh_user uuid NOT NULL,
|
|
23
|
+
position integer NOT NULL,
|
|
24
|
+
methods text NOT NULL,
|
|
25
|
+
id_password_secret uuid,
|
|
26
|
+
id_otp_secret uuid,
|
|
27
|
+
notes text,
|
|
28
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
29
|
+
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
30
|
+
CONSTRAINT ssh_login_id_ssh_user_position_unique UNIQUE (id_ssh_user, position) DEFERRABLE INITIALLY DEFERRED,
|
|
31
|
+
CONSTRAINT ssh_login_id_password_secret_unique UNIQUE (id_password_secret),
|
|
32
|
+
CONSTRAINT ssh_login_id_otp_secret_unique UNIQUE (id_otp_secret),
|
|
33
|
+
CONSTRAINT ssh_login_position_range CHECK (position BETWEEN 0 AND 7),
|
|
34
|
+
CONSTRAINT ssh_login_methods
|
|
35
|
+
CHECK (methods ~ '^(publickey|password|keyboard-interactive)(,(publickey|password|keyboard-interactive)){0,3}$'),
|
|
36
|
+
CONSTRAINT id_ssh_user FOREIGN KEY (id_ssh_user) REFERENCES qpanel.ssh_user (id) ON DELETE CASCADE,
|
|
37
|
+
CONSTRAINT id_password_secret FOREIGN KEY (id_password_secret) REFERENCES qpanel.secret (id) ON DELETE RESTRICT,
|
|
38
|
+
CONSTRAINT id_otp_secret FOREIGN KEY (id_otp_secret) REFERENCES qpanel.secret (id) ON DELETE RESTRICT
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
INSERT INTO qpanel.ssh_login
|
|
42
|
+
(id_ssh_user, position, methods, id_password_secret, id_otp_secret, notes, created_at, updated_at)
|
|
43
|
+
SELECT id, ordinal - 1, methods,
|
|
44
|
+
CASE WHEN password_rank = 1 THEN id_password_secret END,
|
|
45
|
+
CASE WHEN otp_rank = 1 THEN id_otp_secret END,
|
|
46
|
+
CASE WHEN ordinal = 1 THEN notes END,
|
|
47
|
+
created_at, updated_at
|
|
48
|
+
FROM (
|
|
49
|
+
SELECT u.*, way.methods, way.ordinal,
|
|
50
|
+
row_number() OVER (
|
|
51
|
+
PARTITION BY u.id ORDER BY 'password' = ANY (string_to_array(way.methods, ',')) DESC, way.ordinal
|
|
52
|
+
) AS password_rank,
|
|
53
|
+
row_number() OVER (
|
|
54
|
+
PARTITION BY u.id ORDER BY 'keyboard-interactive' = ANY (string_to_array(way.methods, ',')) DESC, way.ordinal
|
|
55
|
+
) AS otp_rank
|
|
56
|
+
FROM qpanel.ssh_user u CROSS JOIN LATERAL unnest(u.logins) WITH ORDINALITY AS way (methods, ordinal)
|
|
57
|
+
) AS ranked;
|
|
58
|
+
|
|
59
|
+
CREATE TRIGGER ssh_login_set_updated_at BEFORE UPDATE ON qpanel.ssh_login
|
|
60
|
+
FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
|
|
61
|
+
CREATE FUNCTION qpanel.delete_ssh_login_secrets() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
62
|
+
BEGIN
|
|
63
|
+
DELETE FROM qpanel.secret WHERE id IN (OLD.id_password_secret, OLD.id_otp_secret);
|
|
64
|
+
RETURN NULL;
|
|
65
|
+
END
|
|
66
|
+
$$;
|
|
67
|
+
CREATE TRIGGER ssh_login_delete_secrets AFTER DELETE ON qpanel.ssh_login
|
|
68
|
+
FOR EACH ROW EXECUTE FUNCTION qpanel.delete_ssh_login_secrets();
|
|
69
|
+
|
|
70
|
+
DROP TRIGGER ssh_user_delete_secrets ON qpanel.ssh_user;
|
|
71
|
+
DROP FUNCTION qpanel.delete_ssh_user_secrets();
|
|
72
|
+
ALTER TABLE qpanel.ssh_user
|
|
73
|
+
DROP COLUMN logins, DROP COLUMN id_password_secret, DROP COLUMN id_otp_secret, DROP COLUMN notes;
|
|
74
|
+
`.execute(db);
|
|
75
|
+
}
|
|
76
|
+
export async function down(db) {
|
|
77
|
+
await sql `
|
|
78
|
+
DO $$
|
|
79
|
+
BEGIN
|
|
80
|
+
IF EXISTS (
|
|
81
|
+
SELECT FROM qpanel.ssh_login GROUP BY id_ssh_user HAVING count(id_password_secret) > 1 OR count(id_otp_secret) > 1
|
|
82
|
+
) THEN
|
|
83
|
+
RAISE EXCEPTION 'an SSH user keeps two passwords or two one-time code secrets: remove all but one of each first';
|
|
84
|
+
END IF;
|
|
85
|
+
END
|
|
86
|
+
$$;
|
|
87
|
+
|
|
88
|
+
ALTER TABLE qpanel.ssh_user
|
|
89
|
+
ADD COLUMN logins text[], ADD COLUMN id_password_secret uuid, ADD COLUMN id_otp_secret uuid, ADD COLUMN notes text;
|
|
90
|
+
|
|
91
|
+
ALTER TABLE qpanel.ssh_user DISABLE TRIGGER ssh_user_set_updated_at;
|
|
92
|
+
UPDATE qpanel.ssh_user u
|
|
93
|
+
SET logins = ways.logins, id_password_secret = ways.id_password_secret, id_otp_secret = ways.id_otp_secret, notes = ways.notes
|
|
94
|
+
FROM (
|
|
95
|
+
SELECT id_ssh_user,
|
|
96
|
+
array_agg(methods ORDER BY position) AS logins,
|
|
97
|
+
(array_agg(id_password_secret) FILTER (WHERE id_password_secret IS NOT NULL))[1] AS id_password_secret,
|
|
98
|
+
(array_agg(id_otp_secret) FILTER (WHERE id_otp_secret IS NOT NULL))[1] AS id_otp_secret,
|
|
99
|
+
string_agg(notes, chr(10) || chr(10) ORDER BY position) AS notes
|
|
100
|
+
FROM qpanel.ssh_login GROUP BY id_ssh_user
|
|
101
|
+
) AS ways
|
|
102
|
+
WHERE u.id = ways.id_ssh_user;
|
|
103
|
+
ALTER TABLE qpanel.ssh_user ENABLE TRIGGER ssh_user_set_updated_at;
|
|
104
|
+
|
|
105
|
+
ALTER TABLE qpanel.ssh_user
|
|
106
|
+
ALTER COLUMN logins SET NOT NULL,
|
|
107
|
+
ADD CONSTRAINT ssh_user_id_password_secret_unique UNIQUE (id_password_secret),
|
|
108
|
+
ADD CONSTRAINT ssh_user_id_otp_secret_unique UNIQUE (id_otp_secret),
|
|
109
|
+
ADD CONSTRAINT ssh_user_logins CHECK (
|
|
110
|
+
array_ndims(logins) = 1
|
|
111
|
+
AND array_to_string(logins, ';', '?') ~ ('^(publickey|password|keyboard-interactive)(,(publickey|password|keyboard-interactive)){0,3}'
|
|
112
|
+
|| '(;(publickey|password|keyboard-interactive)(,(publickey|password|keyboard-interactive)){0,3}){0,7}$')
|
|
113
|
+
AND cardinality(logins) = cardinality(string_to_array(array_to_string(logins, ';', '?'), ';'))
|
|
114
|
+
),
|
|
115
|
+
ADD CONSTRAINT id_password_secret FOREIGN KEY (id_password_secret) REFERENCES qpanel.secret (id) ON DELETE RESTRICT,
|
|
116
|
+
ADD CONSTRAINT id_otp_secret FOREIGN KEY (id_otp_secret) REFERENCES qpanel.secret (id) ON DELETE RESTRICT;
|
|
117
|
+
CREATE FUNCTION qpanel.delete_ssh_user_secrets() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
118
|
+
BEGIN
|
|
119
|
+
DELETE FROM qpanel.secret WHERE id IN (OLD.id_password_secret, OLD.id_otp_secret);
|
|
120
|
+
RETURN NULL;
|
|
121
|
+
END
|
|
122
|
+
$$;
|
|
123
|
+
CREATE TRIGGER ssh_user_delete_secrets AFTER DELETE ON qpanel.ssh_user
|
|
124
|
+
FOR EACH ROW EXECUTE FUNCTION qpanel.delete_ssh_user_secrets();
|
|
125
|
+
|
|
126
|
+
DROP TABLE qpanel.ssh_login;
|
|
127
|
+
DROP FUNCTION qpanel.delete_ssh_login_secrets();
|
|
128
|
+
`.execute(db);
|
|
129
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
export const USAGE = [
|
|
3
|
+
'Usage: qpanel-db-setup <command> [options] (in a checkout: node src/bin.mts <command> [options])',
|
|
4
|
+
'',
|
|
5
|
+
' migrate up apply every pending migration',
|
|
6
|
+
' migrate down revert the last applied migration',
|
|
7
|
+
' migrate status list every migration and whether it is applied',
|
|
8
|
+
' (a checkout also takes them without "migrate": up, down, status)',
|
|
9
|
+
' create <name> write a new, empty migration file (in a checkout only)',
|
|
10
|
+
'',
|
|
11
|
+
' master-key mint create a master key file: one key, version 1',
|
|
12
|
+
' master-key add-version add a key version and make it current (rotation, step 1)',
|
|
13
|
+
' master-key rewrap re-wrap every secret that is not on the current version (step 2)',
|
|
14
|
+
' master-key retire <version> drop a key version no secret uses any more (step 3)',
|
|
15
|
+
'',
|
|
16
|
+
' keygrip seed create the cookie-signing key set in Redis, once, at the first deploy',
|
|
17
|
+
' keygrip rotate mint a new signing key and make it the one that signs',
|
|
18
|
+
' keygrip retire <id> drop one signing key, e.g. k1',
|
|
19
|
+
'',
|
|
20
|
+
' --path <file> the master key file (every master-key command)',
|
|
21
|
+
' --test target the test database: DATABASE_MIGRATOR_URL_TEST for up, down and status,',
|
|
22
|
+
' DATABASE_URL_TEST for master-key rewrap and retire',
|
|
23
|
+
' (without it: DATABASE_MIGRATOR_URL, and DATABASE_URL for those two)'
|
|
24
|
+
].join('\n');
|
|
25
|
+
/** A key version as the master key file writes it: a positive whole number, no sign, no leading zero. */
|
|
26
|
+
const KEY_VERSION_PATTERN = /^[1-9][0-9]*$/;
|
|
27
|
+
function refuseArguments(command, rest) {
|
|
28
|
+
if (rest.length > 0)
|
|
29
|
+
throw new Error(`"${command}" takes no argument, got "${rest.join(' ')}".`);
|
|
30
|
+
}
|
|
31
|
+
function refusePath(command, { path }) {
|
|
32
|
+
if (path !== undefined)
|
|
33
|
+
throw new Error(`"${command}" does not take --path.`);
|
|
34
|
+
}
|
|
35
|
+
const MIGRATION_COMMANDS = ['up', 'down', 'status'];
|
|
36
|
+
function isMigrationCommand(word) {
|
|
37
|
+
return MIGRATION_COMMANDS.some((command) => command === word);
|
|
38
|
+
}
|
|
39
|
+
function parseMigration(command, rest, flags) {
|
|
40
|
+
refuseArguments(command, rest);
|
|
41
|
+
refusePath(command, flags);
|
|
42
|
+
return { command, test: flags.test };
|
|
43
|
+
}
|
|
44
|
+
function parseMasterKey(rest, { test, path }) {
|
|
45
|
+
const [action, ...operands] = rest;
|
|
46
|
+
if (action === undefined)
|
|
47
|
+
throw new Error('"master-key" needs an action: mint, add-version, rewrap or retire.');
|
|
48
|
+
if (action !== 'mint' && action !== 'add-version' && action !== 'rewrap' && action !== 'retire') {
|
|
49
|
+
throw new Error(`Unknown master-key action "${action}".`);
|
|
50
|
+
}
|
|
51
|
+
const name = `master-key ${action}`;
|
|
52
|
+
if (path === undefined || path === '')
|
|
53
|
+
throw new Error(`"${name}" needs --path <file>, the master key file.`);
|
|
54
|
+
if (action === 'retire') {
|
|
55
|
+
const [version, ...extra] = operands;
|
|
56
|
+
if (version === undefined || extra.length > 0) {
|
|
57
|
+
throw new Error(`"${name}" takes exactly one key version, e.g. retire 1.`);
|
|
58
|
+
}
|
|
59
|
+
if (!KEY_VERSION_PATTERN.test(version) || !Number.isSafeInteger(Number(version))) {
|
|
60
|
+
throw new Error(`"${version}" is not a key version: use a positive whole number, e.g. 1.`);
|
|
61
|
+
}
|
|
62
|
+
return { command: 'master-key', action, path, test, version: Number(version) };
|
|
63
|
+
}
|
|
64
|
+
refuseArguments(name, operands);
|
|
65
|
+
if (action === 'rewrap')
|
|
66
|
+
return { command: 'master-key', action, path, test };
|
|
67
|
+
if (test)
|
|
68
|
+
throw new Error(`"${name}" touches no database, so --test makes no sense.`);
|
|
69
|
+
return { command: 'master-key', action, path };
|
|
70
|
+
}
|
|
71
|
+
function parseKeygrip(rest, flags) {
|
|
72
|
+
const [action, ...operands] = rest;
|
|
73
|
+
if (action === undefined)
|
|
74
|
+
throw new Error('"keygrip" needs an action: seed, rotate or retire.');
|
|
75
|
+
if (action !== 'seed' && action !== 'rotate' && action !== 'retire')
|
|
76
|
+
throw new Error(`Unknown keygrip action "${action}".`);
|
|
77
|
+
const name = `keygrip ${action}`;
|
|
78
|
+
refusePath(name, flags);
|
|
79
|
+
if (flags.test)
|
|
80
|
+
throw new Error(`"${name}" works on the Redis namespace REDIS_KEY names, so --test makes no sense.`);
|
|
81
|
+
if (action === 'retire') {
|
|
82
|
+
const [id, ...extra] = operands;
|
|
83
|
+
if (id === undefined || id === '' || extra.length > 0) {
|
|
84
|
+
throw new Error(`"${name}" takes exactly one key id, e.g. retire k1.`);
|
|
85
|
+
}
|
|
86
|
+
return { command: 'keygrip', action, id };
|
|
87
|
+
}
|
|
88
|
+
refuseArguments(name, operands);
|
|
89
|
+
return { command: 'keygrip', action };
|
|
90
|
+
}
|
|
91
|
+
/** Reads the command line. Throws a message-only Error for anything it does not understand. */
|
|
92
|
+
export function parseInvocation(argv) {
|
|
93
|
+
const { positionals, values } = parseArgs({
|
|
94
|
+
args: [...argv],
|
|
95
|
+
allowPositionals: true,
|
|
96
|
+
options: { test: { type: 'boolean' }, path: { type: 'string' } }
|
|
97
|
+
});
|
|
98
|
+
const [command, ...rest] = positionals;
|
|
99
|
+
const flags = { test: values.test === true, path: values.path };
|
|
100
|
+
// `migrate up` is the spelling of the installed package; `up` alone is the one of this repo's scripts.
|
|
101
|
+
if (command === 'migrate') {
|
|
102
|
+
const [action, ...operands] = rest;
|
|
103
|
+
if (!isMigrationCommand(action))
|
|
104
|
+
throw new Error('"migrate" needs an action: up, down or status.');
|
|
105
|
+
return parseMigration(action, operands, flags);
|
|
106
|
+
}
|
|
107
|
+
if (isMigrationCommand(command))
|
|
108
|
+
return parseMigration(command, rest, flags);
|
|
109
|
+
if (command === 'create') {
|
|
110
|
+
const [name, ...extra] = rest;
|
|
111
|
+
if (name === undefined || extra.length > 0) {
|
|
112
|
+
throw new Error('"create" takes exactly one name, e.g. create add-client-index.');
|
|
113
|
+
}
|
|
114
|
+
if (flags.test)
|
|
115
|
+
throw new Error('"create" writes a file and touches no database, so --test makes no sense.');
|
|
116
|
+
refusePath(command, flags);
|
|
117
|
+
return { command, name };
|
|
118
|
+
}
|
|
119
|
+
if (command === 'master-key')
|
|
120
|
+
return parseMasterKey(rest, flags);
|
|
121
|
+
if (command === 'keygrip')
|
|
122
|
+
return parseKeygrip(rest, flags);
|
|
123
|
+
throw new Error(command === undefined ? 'Missing command.' : `Unknown command "${command}".`);
|
|
124
|
+
}
|
package/dist/src/bin.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The one entry point: `yarn migrate:up|down|status|create` runs this file, which Node executes as it is
|
|
3
|
+
// (type stripping). In the published package the compiled `dist/src/bin.mjs` is the `qpanel-db-setup` bin: Node
|
|
4
|
+
// does not strip types under node_modules, which is why `yarn build` exists. Everything it decides lives in
|
|
5
|
+
// cli.mts, which is tested; what is left here is the wiring to the process, and it is named in
|
|
6
|
+
// coverage-exempt.txt for that reason.
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { main } from "./cli.mjs";
|
|
9
|
+
import { findUp, loadEnvFile } from "./env.mjs";
|
|
10
|
+
// The two env files fill in what the shell did not export (direnv, CI), in the order the tests use: the
|
|
11
|
+
// workspace's shared file (Redis, KEYGRIP_KEK, DATABASE_URL, found by walking up from this repo), then this
|
|
12
|
+
// repo's own. Neither overrides an exported value. They are read here and nowhere else, and their values are
|
|
13
|
+
// never printed. What they leave unset may then come from Infisical (cli.mts, ADR-040).
|
|
14
|
+
const shared = findUp('.env.shared', fileURLToPath(new URL('..', import.meta.url)));
|
|
15
|
+
if (shared !== undefined)
|
|
16
|
+
loadEnvFile(shared);
|
|
17
|
+
loadEnvFile(new URL('../.env', import.meta.url));
|
|
18
|
+
process.exitCode = await main(process.argv.slice(2), {
|
|
19
|
+
env: process.env,
|
|
20
|
+
out: (line) => {
|
|
21
|
+
console.log(line);
|
|
22
|
+
},
|
|
23
|
+
err: (line) => {
|
|
24
|
+
console.error(line);
|
|
25
|
+
}
|
|
26
|
+
});
|
package/dist/src/cli.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { createDatabase } from '@axiumine/qpanel-common/db/createDatabase';
|
|
2
|
+
import { readMasterKeyRing } from '@axiumine/qpanel-common/encryption/masterKeyRing';
|
|
3
|
+
import { parseInvocation, USAGE } from "./arguments.mjs";
|
|
4
|
+
import { createMigration } from "./create.mjs";
|
|
5
|
+
import { assertAppRole, assertMigratorRole, openDatabase } from "./database.mjs";
|
|
6
|
+
import { INFISICAL_NAMES, INFISICAL_SECRET_PATHS, INFISICAL_TEST_SECRET_PATHS, loadFromInfisical } from "./infisical.mjs";
|
|
7
|
+
import { runKeygrip } from "./keygrip.mjs";
|
|
8
|
+
import { addVersion, mint, retire, rewrap } from "./masterKey.mjs";
|
|
9
|
+
import { createMigrator, MIGRATIONS_DIR, runCommand } from "./migrator.mjs";
|
|
10
|
+
import { openRedisCluster } from "./redis.mjs";
|
|
11
|
+
import { countSecretsByKeyVersion } from "./secrets.mjs";
|
|
12
|
+
import { resolveAppTarget, resolveTarget } from "./target.mjs";
|
|
13
|
+
/** What an error says, with the children of an AggregateError (a refused connection on every address) spelled out. */
|
|
14
|
+
export function messageOf(error) {
|
|
15
|
+
if (error instanceof AggregateError)
|
|
16
|
+
return error.errors.map(messageOf).join('; ');
|
|
17
|
+
return error instanceof Error ? error.message : String(error);
|
|
18
|
+
}
|
|
19
|
+
/** Every string that would give the connection away: the whole URL, and its password as written and decoded. */
|
|
20
|
+
export function secretsOf(url) {
|
|
21
|
+
const secrets = [url];
|
|
22
|
+
try {
|
|
23
|
+
const { password } = new URL(url);
|
|
24
|
+
secrets.push(password);
|
|
25
|
+
secrets.push(decodeURIComponent(password));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// Not a URL, or a malformed escape: the whole string is all there is to hide.
|
|
29
|
+
}
|
|
30
|
+
return secrets.filter((secret) => secret !== '');
|
|
31
|
+
}
|
|
32
|
+
/** The message with every secret blanked, whatever library put it there. */
|
|
33
|
+
export function redact(message, secrets) {
|
|
34
|
+
return secrets.reduce((text, secret) => text.replaceAll(secret, '***'), message);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Runs `run` against the app role's connection (`DATABASE_URL`, or `DATABASE_URL_TEST` for the test database): the role
|
|
38
|
+
* the services use, data access and no DDL. The URL and its password go to `secrets` before anything can fail with them in
|
|
39
|
+
* the message, the role is checked and named, and the pool is closed whatever happens.
|
|
40
|
+
*/
|
|
41
|
+
async function withAppDatabase(test, env, io, secrets, run) {
|
|
42
|
+
const target = resolveAppTarget(test, env);
|
|
43
|
+
secrets.push(...secretsOf(target.url));
|
|
44
|
+
const db = createDatabase({ connectionString: target.url, max: 2 });
|
|
45
|
+
try {
|
|
46
|
+
io.out(`Target: ${target.label} database, as ${await assertAppRole(db)}`);
|
|
47
|
+
return await run(db);
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
await db.destroy();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function runMasterKey(invocation, env, io, secrets) {
|
|
54
|
+
if (invocation.action === 'mint')
|
|
55
|
+
return mint(invocation.path, io);
|
|
56
|
+
if (invocation.action === 'add-version')
|
|
57
|
+
return addVersion(invocation.path, io);
|
|
58
|
+
if (invocation.action === 'rewrap') {
|
|
59
|
+
const { test, path } = invocation;
|
|
60
|
+
// A ring that cannot be read stops the run before it connects to anything.
|
|
61
|
+
const ring = readMasterKeyRing(path);
|
|
62
|
+
return withAppDatabase(test, env, io, secrets, (db) => rewrap(db, ring, io));
|
|
63
|
+
}
|
|
64
|
+
const { test, path, version } = invocation;
|
|
65
|
+
const countOnVersion = (on) => withAppDatabase(test, env, io, secrets, async (db) => (await countSecretsByKeyVersion(db)).get(on) ?? 0);
|
|
66
|
+
return retire(path, version, countOnVersion, io);
|
|
67
|
+
}
|
|
68
|
+
async function runMigration(command, test, env, io, migrationsDir, secrets) {
|
|
69
|
+
const target = resolveTarget(test, env);
|
|
70
|
+
secrets.push(...secretsOf(target.url));
|
|
71
|
+
const db = openDatabase(target.url);
|
|
72
|
+
try {
|
|
73
|
+
io.out(`Target: ${target.label} database, as ${await assertMigratorRole(db)}`);
|
|
74
|
+
await runCommand(command, createMigrator(db, migrationsDir), io);
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
await db.destroy();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* What a command asks of Infisical, `undefined` for nothing. A new migration file and a key file made or extended read no
|
|
82
|
+
* variable it may hold. A run against the test database asks only when its `*_TEST` URL has no value, and for that URL
|
|
83
|
+
* alone (parent ADR-041). The others run with Infisical unreachable.
|
|
84
|
+
*/
|
|
85
|
+
function wantedFrom(invocation, env) {
|
|
86
|
+
if (invocation.command === 'create')
|
|
87
|
+
return undefined;
|
|
88
|
+
if (invocation.command === 'master-key' && invocation.action !== 'rewrap' && invocation.action !== 'retire')
|
|
89
|
+
return undefined;
|
|
90
|
+
if (!('test' in invocation && invocation.test))
|
|
91
|
+
return { names: INFISICAL_NAMES, secretPaths: INFISICAL_SECRET_PATHS };
|
|
92
|
+
const name = invocation.command === 'master-key' ? 'DATABASE_URL_TEST' : 'DATABASE_MIGRATOR_URL_TEST';
|
|
93
|
+
return env[name] ? undefined : { names: [name], secretPaths: INFISICAL_TEST_SECRET_PATHS };
|
|
94
|
+
}
|
|
95
|
+
async function execute(invocation, context, secrets) {
|
|
96
|
+
const { env, out, migrationsDir = MIGRATIONS_DIR, openRedis = openRedisCluster, fetch = globalThis.fetch } = context;
|
|
97
|
+
const wanted = wantedFrom(invocation, env);
|
|
98
|
+
if (wanted !== undefined)
|
|
99
|
+
await loadFromInfisical(env, fetch, out, wanted);
|
|
100
|
+
if (invocation.command === 'create') {
|
|
101
|
+
out(`Created ${await createMigration(migrationsDir, invocation.name, new Date())}`);
|
|
102
|
+
}
|
|
103
|
+
else if (invocation.command === 'master-key') {
|
|
104
|
+
await runMasterKey(invocation, env, { out }, secrets);
|
|
105
|
+
}
|
|
106
|
+
else if (invocation.command === 'keygrip') {
|
|
107
|
+
await runKeygrip(invocation, env, { out }, openRedis, secrets);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
await runMigration(invocation.command, invocation.test, env, { out }, migrationsDir, secrets);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The command line: returns the exit code, 0 done, 1 failed, 2 not understood. Output goes through `out` and `err`
|
|
115
|
+
* and never includes a connection URL, a password, a key or a token: whatever a library puts in a message, every
|
|
116
|
+
* secret the command has read by then is blanked out of it.
|
|
117
|
+
*/
|
|
118
|
+
export async function main(argv, context) {
|
|
119
|
+
let invocation;
|
|
120
|
+
try {
|
|
121
|
+
invocation = parseInvocation(argv);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
context.err(messageOf(error));
|
|
125
|
+
context.err(USAGE);
|
|
126
|
+
return 2;
|
|
127
|
+
}
|
|
128
|
+
// A command registers its secrets as it reads them. One that fails before it has read any (a variable that is
|
|
129
|
+
// not set) has nothing to blank, and its message names the variable and never its value.
|
|
130
|
+
const secrets = [];
|
|
131
|
+
try {
|
|
132
|
+
await execute(invocation, context, secrets);
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
context.err(redact(messageOf(error), secrets));
|
|
137
|
+
return 1;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join, sep } from 'node:path';
|
|
3
|
+
const NAME_PATTERN = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
|
|
4
|
+
export const TEMPLATE = `import { type Kysely, sql } from 'kysely'
|
|
5
|
+
|
|
6
|
+
// Raw SQL, every object schema-qualified (\`qpanel.<name>\`). Never edit a migration once it is applied
|
|
7
|
+
// anywhere but the test database: add a new one. Write \`down\` so that it leaves the database exactly as
|
|
8
|
+
// \`up\` found it.
|
|
9
|
+
export async function up(db: Kysely<unknown>): Promise<void> {
|
|
10
|
+
await sql\`
|
|
11
|
+
SELECT 1
|
|
12
|
+
\`.execute(db)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function down(db: Kysely<unknown>): Promise<void> {
|
|
16
|
+
await sql\`
|
|
17
|
+
SELECT 1
|
|
18
|
+
\`.execute(db)
|
|
19
|
+
}
|
|
20
|
+
`;
|
|
21
|
+
/** `<UTC timestamp to the second>-<name>.mts`: the timestamp keeps the folder in the order they were written. */
|
|
22
|
+
export function migrationFileName(name, now) {
|
|
23
|
+
if (!NAME_PATTERN.test(name)) {
|
|
24
|
+
throw new Error(`"${name}" is not a valid migration name: use lower-case words joined by hyphens, e.g. add-client-index.`);
|
|
25
|
+
}
|
|
26
|
+
return `${now.toISOString().replaceAll(/\D/g, '').slice(0, 14)}-${name}.mts`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Writes the empty migration and returns its path. Never overwrites a file, and never writes into an installed
|
|
30
|
+
* package: the folder of a copy under `node_modules` holds compiled files, and a new `.mts` file there would be
|
|
31
|
+
* neither compiled nor loadable (Node does not strip types under `node_modules`).
|
|
32
|
+
*/
|
|
33
|
+
export async function createMigration(directory, name, now) {
|
|
34
|
+
if (directory.split(sep).includes('node_modules')) {
|
|
35
|
+
throw new Error('"create" writes a source file: run it in a checkout of qpanel-db-setup, not in an installed copy.');
|
|
36
|
+
}
|
|
37
|
+
const path = join(directory, migrationFileName(name, now));
|
|
38
|
+
await writeFile(path, TEMPLATE, { flag: 'wx' });
|
|
39
|
+
return path;
|
|
40
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Kysely, PostgresDialect, sql } from 'kysely';
|
|
2
|
+
import pg from 'pg';
|
|
3
|
+
/**
|
|
4
|
+
* Opens the migrator's connection. Two connections at most: the migrator role is limited to five, and the
|
|
5
|
+
* integration tests hold connections of their own beside the runner's.
|
|
6
|
+
*/
|
|
7
|
+
export function openDatabase(url) {
|
|
8
|
+
return new Kysely({ dialect: new PostgresDialect({ pool: new pg.Pool({ connectionString: url, max: 2 }) }) });
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Refuses to go on unless the connection is a migrator role (`qpanel_<env>_migrator`). The migrations
|
|
12
|
+
* create and own every object and derive the app role from the name of the role that runs them, and the
|
|
13
|
+
* app role owns nothing: running them as anything else would fail half-way or, worse, succeed on the wrong
|
|
14
|
+
* database. Returns the role name, which is not a secret.
|
|
15
|
+
*/
|
|
16
|
+
export async function assertMigratorRole(db) {
|
|
17
|
+
const role = await currentRole(db);
|
|
18
|
+
if (!role.endsWith('_migrator')) {
|
|
19
|
+
throw new Error(`Refusing to run as "${role}": the migrations run only as a qpanel_<env>_migrator role.`);
|
|
20
|
+
}
|
|
21
|
+
return role;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Refuses to go on unless the connection is an app role (`qpanel_<env>_app`): the role the services use, with data
|
|
25
|
+
* access and no DDL. The master-key commands change rows and never the schema, so the role that owns every table
|
|
26
|
+
* would be more than they need, and a superuser or a migrator in `DATABASE_URL` is a mistake worth stopping on.
|
|
27
|
+
* Returns the role name, which is not a secret.
|
|
28
|
+
*/
|
|
29
|
+
export async function assertAppRole(db) {
|
|
30
|
+
const role = await currentRole(db);
|
|
31
|
+
if (!role.endsWith('_app')) {
|
|
32
|
+
throw new Error(`Refusing to run as "${role}": the master-key commands run only as a qpanel_<env>_app role.`);
|
|
33
|
+
}
|
|
34
|
+
return role;
|
|
35
|
+
}
|
|
36
|
+
async function currentRole(db) {
|
|
37
|
+
const { rows } = await sql `SELECT current_user AS role`.execute(db);
|
|
38
|
+
// `SELECT current_user` always answers with exactly one row.
|
|
39
|
+
const [{ role }] = rows;
|
|
40
|
+
return role;
|
|
41
|
+
}
|
package/dist/src/env.mjs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, parse } from 'node:path';
|
|
3
|
+
import { parseEnv } from 'node:util';
|
|
4
|
+
/** The nearest `name` in `from` or any directory above it, the way direnv finds the nearest `.envrc`. */
|
|
5
|
+
export function findUp(name, from) {
|
|
6
|
+
for (let dir = from;; dir = dirname(dir)) {
|
|
7
|
+
const candidate = join(dir, name);
|
|
8
|
+
if (existsSync(candidate))
|
|
9
|
+
return candidate;
|
|
10
|
+
if (dir === parse(dir).root)
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Loads one dotenv file into `env` the way the workspace layer does (`envrc`): a value that is already
|
|
16
|
+
* set and not empty wins, and an empty value in the file never shadows anything. Returns the NAMES it set,
|
|
17
|
+
* never a value, so a caller can report what it did without printing a secret. A missing file is not an
|
|
18
|
+
* error: CI sets the variables directly and has no file at all.
|
|
19
|
+
*/
|
|
20
|
+
export function loadEnvFile(path, env = process.env) {
|
|
21
|
+
let content;
|
|
22
|
+
try {
|
|
23
|
+
content = readFileSync(path, 'utf8');
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code === 'ENOENT')
|
|
27
|
+
return [];
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
const applied = [];
|
|
31
|
+
for (const [name, value] of Object.entries(parseEnv(content))) {
|
|
32
|
+
if (value === '' || (env[name] ?? '') !== '')
|
|
33
|
+
continue;
|
|
34
|
+
env[name] = value;
|
|
35
|
+
applied.push(name);
|
|
36
|
+
}
|
|
37
|
+
return applied;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The value of a variable a command cannot run without. The message names the variable and never quotes its
|
|
41
|
+
* value, and an empty value counts as not set.
|
|
42
|
+
*/
|
|
43
|
+
export function requireVariable(env, name) {
|
|
44
|
+
const value = env[name];
|
|
45
|
+
if (value === undefined || value === '') {
|
|
46
|
+
throw new Error(`${name} is not set. Put it in this repo's env file (template: env.example) or export it, then run again.`);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// The secrets a command takes from the owner's Infisical (parent ADR-040). The client is qpanel-common's.
|
|
2
|
+
import { describeInfisicalLoad, loadInfisicalSecrets } from '@axiumine/qpanel-common/config/infisical';
|
|
3
|
+
/**
|
|
4
|
+
* What the commands read, and so what Infisical may give them. The `*_TEST` URLs are not here: a run against the test
|
|
5
|
+
* database asks for the one it reads, and for nothing else.
|
|
6
|
+
*/
|
|
7
|
+
export const INFISICAL_NAMES = [
|
|
8
|
+
'DATABASE_MIGRATOR_URL',
|
|
9
|
+
'DATABASE_URL',
|
|
10
|
+
'KEYGRIP_KEK',
|
|
11
|
+
'REDIS_IS_CLUSTER',
|
|
12
|
+
'REDIS_DB1_HOST',
|
|
13
|
+
'REDIS_DB1_PORT',
|
|
14
|
+
'REDIS_DB2_HOST',
|
|
15
|
+
'REDIS_DB2_PORT',
|
|
16
|
+
'REDIS_DB3_HOST',
|
|
17
|
+
'REDIS_DB3_PORT',
|
|
18
|
+
'REDIS_USERNAME',
|
|
19
|
+
'REDIS_PASSWORD',
|
|
20
|
+
'REDIS_KEY'
|
|
21
|
+
];
|
|
22
|
+
/**
|
|
23
|
+
* The folders read unless `INFISICAL_SECRET_PATHS` names others. The migrator's URL belongs in a project of its own, which
|
|
24
|
+
* no service's identity can read, and whoever migrates names that folder.
|
|
25
|
+
*/
|
|
26
|
+
export const INFISICAL_SECRET_PATHS = ['/shared'];
|
|
27
|
+
/** The folders of a run against the test database: the ones this repository's gates read (parent ADR-041). */
|
|
28
|
+
export const INFISICAL_TEST_SECRET_PATHS = ['/shared', '/qpanel-db-setup'];
|
|
29
|
+
/**
|
|
30
|
+
* Fills `env` from Infisical when the `INFISICAL_*` settings are there, and prints which names it set; without them it does
|
|
31
|
+
* nothing. Rejects with qpanel-common's `InfisicalError`, whose message quotes no value.
|
|
32
|
+
*/
|
|
33
|
+
export async function loadFromInfisical(env, fetch, print, wanted) {
|
|
34
|
+
const load = await loadInfisicalSecrets(env, { ...wanted, fetch });
|
|
35
|
+
if (load !== undefined)
|
|
36
|
+
print(describeInfisicalLoad(load));
|
|
37
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { readKek, retireKeygrip, rotateKeygrip, seedKeygrip } from '@axiumine/qpanel-common/session/keygrip';
|
|
2
|
+
import { createKeyspace } from '@axiumine/qpanel-common/session/keyspace';
|
|
3
|
+
import { requireVariable } from "./env.mjs";
|
|
4
|
+
import { redisConfigFromEnv } from "./redis.mjs";
|
|
5
|
+
/**
|
|
6
|
+
* `keygrip seed`, `rotate` and `retire <id>`: the cookie-signing keys of the refresh cookie, in the Redis namespace
|
|
7
|
+
* `REDIS_KEY` names, wrapped under `KEYGRIP_KEK` (qpanel-common's `session/keygrip` does all of it). Every service
|
|
8
|
+
* reads the record when it boots, so a rotation reaches them when they restart.
|
|
9
|
+
*
|
|
10
|
+
* ⚠️ Prints the namespace, the version and the fingerprint (twelve hex characters of the key ids) and never a key.
|
|
11
|
+
* `secrets` receives every value that must not appear in a message, the moment it is read: the Redis password and the
|
|
12
|
+
* KEK. A failure from Redis or from the library is printed by the caller with those blanked.
|
|
13
|
+
*/
|
|
14
|
+
export async function runKeygrip(invocation, env, io, openRedis, secrets) {
|
|
15
|
+
const keys = createKeyspace(requireVariable(env, 'REDIS_KEY'));
|
|
16
|
+
const kekValue = requireVariable(env, 'KEYGRIP_KEK');
|
|
17
|
+
secrets.push(kekValue);
|
|
18
|
+
const kek = readKek(kekValue);
|
|
19
|
+
const config = redisConfigFromEnv(env);
|
|
20
|
+
secrets.push(config.password);
|
|
21
|
+
io.out(`Target: Redis namespace ${keys.prefix}`);
|
|
22
|
+
const redis = await openRedis(config);
|
|
23
|
+
let record;
|
|
24
|
+
try {
|
|
25
|
+
record = await change(invocation, redis, keys, kek);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await redis.close();
|
|
29
|
+
}
|
|
30
|
+
io.out(`${done(invocation)}: version ${record.version}, fingerprint ${record.fp}.`);
|
|
31
|
+
if (invocation.action !== 'seed')
|
|
32
|
+
io.out('Restart every service so that it reads the new key set.');
|
|
33
|
+
}
|
|
34
|
+
/** What was done, for the report. A key id (`k1`) is a label and not key material. */
|
|
35
|
+
function done(invocation) {
|
|
36
|
+
if (invocation.action === 'seed')
|
|
37
|
+
return 'Seeded the key set';
|
|
38
|
+
if (invocation.action === 'rotate')
|
|
39
|
+
return 'Rotated the key set';
|
|
40
|
+
return `Retired key ${invocation.id}`;
|
|
41
|
+
}
|
|
42
|
+
function change(invocation, redis, keys, kek) {
|
|
43
|
+
if (invocation.action === 'seed')
|
|
44
|
+
return seedKeygrip(redis, keys, kek);
|
|
45
|
+
if (invocation.action === 'rotate')
|
|
46
|
+
return rotateKeygrip(redis, keys, kek);
|
|
47
|
+
return retireKeygrip(redis, keys, kek, invocation.id);
|
|
48
|
+
}
|