@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,80 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { addMasterKeyVersion, readMasterKeyRing, serializeMasterKeyRing } from '@axiumine/qpanel-common/encryption/masterKeyRing';
|
|
3
|
+
import { assertPrivateDirectory, replaceFile, writeNewFile } from "./masterKeyFile.mjs";
|
|
4
|
+
import { countSecretsByKeyVersion, recordRewrap, rewrapSecrets } from "./secrets.mjs";
|
|
5
|
+
/**
|
|
6
|
+
* A ring with no key at all: the start of `mint`. `addMasterKeyVersion` gives it version 1, which becomes current.
|
|
7
|
+
* It is never written, and never read back: `serializeMasterKeyRing` only sees the ring after it has a key.
|
|
8
|
+
*/
|
|
9
|
+
const NO_KEYS = { current: 0, keys: new Map() };
|
|
10
|
+
/** The key versions of a ring, as the file lists them: ascending. */
|
|
11
|
+
function versionsOf(ring) {
|
|
12
|
+
return [...ring.keys.keys()].join(', ');
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* `master-key mint`: a new master key file, one random key, version 1, current. Refuses a file that exists and a
|
|
16
|
+
* directory that the group or the others can write to. ⚠️ Prints the path and the version, never a key.
|
|
17
|
+
*/
|
|
18
|
+
export async function mint(path, io, ops) {
|
|
19
|
+
await assertPrivateDirectory(dirname(path));
|
|
20
|
+
const ring = addMasterKeyVersion(NO_KEYS);
|
|
21
|
+
await writeNewFile(path, serializeMasterKeyRing(ring), ops);
|
|
22
|
+
io.out(`Created ${path}: master key version ${ring.current}, current.`);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `master-key add-version`, step 1 of a rotation: a new random key, one version above the highest, current from now on.
|
|
26
|
+
* The old versions stay in the file, so every secret still opens. The file is replaced atomically, mode 0600.
|
|
27
|
+
*/
|
|
28
|
+
export async function addVersion(path, io, ops) {
|
|
29
|
+
const ring = readMasterKeyRing(path);
|
|
30
|
+
await assertPrivateDirectory(dirname(path));
|
|
31
|
+
const next = addMasterKeyVersion(ring);
|
|
32
|
+
await replaceFile(path, serializeMasterKeyRing(next), ops);
|
|
33
|
+
io.out(`Added master key version ${next.current} to ${path} and made it current. Versions in the file: ${versionsOf(next)}.`);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* `master-key rewrap`, step 2: every secret that is not on the ring's current version gets its data key wrapped under it.
|
|
37
|
+
* An `audit_event` records the run when it touched or refused at least one secret, even when the run then fails, so that
|
|
38
|
+
* what was committed is on the trail. Counts only; a failure to re-wrap any secret ends the run with an error.
|
|
39
|
+
*/
|
|
40
|
+
export async function rewrap(db, ring, io, batchSize) {
|
|
41
|
+
io.out(`Master key ring: current version ${ring.current}, versions ${versionsOf(ring)}.`);
|
|
42
|
+
const progress = { rewrapped: 0, failed: 0 };
|
|
43
|
+
try {
|
|
44
|
+
await rewrapSecrets(db, ring, progress, batchSize);
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
if (progress.rewrapped + progress.failed > 0)
|
|
48
|
+
await recordRewrap(db, ring.current, progress);
|
|
49
|
+
}
|
|
50
|
+
io.out(`Re-wrapped ${progress.rewrapped} secret(s) to key version ${ring.current}.`);
|
|
51
|
+
const counts = await countSecretsByKeyVersion(db);
|
|
52
|
+
io.out(`Secrets by key version: ${counts.size === 0 ? 'none' : [...counts].map(([version, n]) => `${version}: ${n}`).join(', ')}.`);
|
|
53
|
+
if (progress.failed > 0) {
|
|
54
|
+
throw new Error(`${progress.failed} secret(s) could not be re-wrapped and were left as they are: a key version missing from this ring, or a row that does not decrypt.`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* `master-key retire <version>`, step 3: drops an old key version from the file once no secret uses it. Never the current
|
|
59
|
+
* one, never a version the file does not have. `countOnVersion` answers how many secrets are on a version (it is only
|
|
60
|
+
* called when the file allows the retirement, so a refusal needs no database), and any secret on it refuses the run:
|
|
61
|
+
* without its key that secret is lost. The file is replaced atomically.
|
|
62
|
+
*/
|
|
63
|
+
export async function retire(path, version, countOnVersion, io, ops) {
|
|
64
|
+
const ring = readMasterKeyRing(path);
|
|
65
|
+
if (version === ring.current) {
|
|
66
|
+
throw new Error(`Key version ${version} is the current one and cannot be retired: add a newer version first.`);
|
|
67
|
+
}
|
|
68
|
+
if (!ring.keys.has(version))
|
|
69
|
+
throw new Error(`${path} has no master key version ${version}.`);
|
|
70
|
+
await assertPrivateDirectory(dirname(path));
|
|
71
|
+
const using = await countOnVersion(version);
|
|
72
|
+
if (using > 0) {
|
|
73
|
+
throw new Error(`${using} secret(s) still use key version ${version}: run master-key rewrap first. The file is unchanged.`);
|
|
74
|
+
}
|
|
75
|
+
const keys = new Map(ring.keys);
|
|
76
|
+
keys.delete(version);
|
|
77
|
+
const next = { current: ring.current, keys };
|
|
78
|
+
await replaceFile(path, serializeMasterKeyRing(next), ops);
|
|
79
|
+
io.out(`Retired master key version ${version} from ${path}. Versions left: ${versionsOf(next)}.`);
|
|
80
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { open, rename, stat, unlink } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* The permission bits of a master key file: its owner reads and writes it, and nobody else has any access.
|
|
6
|
+
* `readMasterKeyRing` (qpanel-common) refuses a file with any group or other bit.
|
|
7
|
+
*/
|
|
8
|
+
export const MASTER_KEY_FILE_MODE = 0o600;
|
|
9
|
+
/** The write bits of group and others. A directory that grants either lets someone else swap the file or put another beside it. */
|
|
10
|
+
const GROUP_AND_OTHER_WRITE = 0o022;
|
|
11
|
+
export const nodeFileOps = { open, rename, unlink };
|
|
12
|
+
/**
|
|
13
|
+
* Refuses a directory the group or the others can write to. A master key file in such a directory can be replaced
|
|
14
|
+
* under the operator's feet, whatever the mode of the file itself, so neither `master-key mint` nor the rewrite of
|
|
15
|
+
* a rotation writes there. Throws the error of `stat` when the directory does not exist.
|
|
16
|
+
*/
|
|
17
|
+
export async function assertPrivateDirectory(directory) {
|
|
18
|
+
const stats = await stat(directory);
|
|
19
|
+
if (!stats.isDirectory())
|
|
20
|
+
throw new Error(`${directory} is not a directory.`);
|
|
21
|
+
if ((stats.mode & GROUP_AND_OTHER_WRITE) !== 0) {
|
|
22
|
+
throw new Error(`The directory ${directory} is writable by its group or by others: refusing to write a master key there.`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Creates `path` with `text`, mode 0600, and syncs it to the disk. It fails (`EEXIST`) when anything is already at
|
|
27
|
+
* `path`, a dangling symbolic link included, and leaves that alone. A write that fails half-way removes the file it
|
|
28
|
+
* created, so a retry is never blocked by a stub.
|
|
29
|
+
*
|
|
30
|
+
* ⚠️ `text` is key material: it is written and never returned, logged or put in an error.
|
|
31
|
+
*/
|
|
32
|
+
export async function writeNewFile(path, text, ops = nodeFileOps) {
|
|
33
|
+
const handle = await ops.open(path, 'wx', MASTER_KEY_FILE_MODE);
|
|
34
|
+
try {
|
|
35
|
+
try {
|
|
36
|
+
await handle.writeFile(text);
|
|
37
|
+
await handle.sync();
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
await handle.close();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
await ops.unlink(path);
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Replaces the file at `path` with `text`, atomically: the new content is written to a temporary file in the same
|
|
50
|
+
* directory (mode 0600, synced), then renamed over `path`. A reader sees the old file or the new one, whole, and a
|
|
51
|
+
* crash leaves one of the two. Any failure removes the temporary file and leaves `path` as it was.
|
|
52
|
+
*
|
|
53
|
+
* The directory itself is not synced: the rename is atomic, and the worst a crash right after it can do is bring the
|
|
54
|
+
* old file back, which the rotation procedure tolerates (it re-runs from where it stopped).
|
|
55
|
+
*/
|
|
56
|
+
export async function replaceFile(path, text, ops = nodeFileOps) {
|
|
57
|
+
const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
58
|
+
await writeNewFile(temporary, text, ops);
|
|
59
|
+
try {
|
|
60
|
+
await ops.rename(temporary, path);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
await ops.unlink(temporary);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { readdir } from 'node:fs/promises';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
12
|
+
import { inspect } from 'node:util';
|
|
13
|
+
import { FileMigrationProvider, Migrator } from 'kysely/migration';
|
|
14
|
+
/** The schema every qPanel object lives in, the migrations' own bookkeeping tables included. */
|
|
15
|
+
export const SCHEMA = 'qpanel';
|
|
16
|
+
export const MIGRATIONS_DIR = fileURLToPath(new URL('../migrations/', import.meta.url));
|
|
17
|
+
/**
|
|
18
|
+
* The migrations of a folder, in file-name order. A file in that folder that is not a migration module fails
|
|
19
|
+
* the run instead of being skipped: a `.sql` file or a typo in an export name would otherwise leave a
|
|
20
|
+
* migration silently unapplied.
|
|
21
|
+
*/
|
|
22
|
+
export function migrationProvider(migrationFolder) {
|
|
23
|
+
return new FileMigrationProvider({
|
|
24
|
+
fs: { readdir },
|
|
25
|
+
path: { join },
|
|
26
|
+
migrationFolder,
|
|
27
|
+
// Through our own `import()` so that a test run loads the files through Vite, which is what lets the
|
|
28
|
+
// coverage report see them. Node loads them natively, type stripping included, everywhere else.
|
|
29
|
+
import: (filePath) => import(__rewriteRelativeImportExtension(pathToFileURL(filePath).href)),
|
|
30
|
+
onFileIgnored: (fileName, reason) => {
|
|
31
|
+
throw new Error(reason === 'Extension'
|
|
32
|
+
? `${fileName} is not a migration: only .mts files belong in the migrations folder.`
|
|
33
|
+
: `${fileName} exports no "up" function, so it is not a migration.`);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/** Kysely's migrator over a folder (the real one by default), bookkeeping in `qpanel.kysely_migration`. */
|
|
38
|
+
export function createMigrator(db, migrationFolder = MIGRATIONS_DIR) {
|
|
39
|
+
return new Migrator({ db, migrationTableSchema: SCHEMA, provider: migrationProvider(migrationFolder) });
|
|
40
|
+
}
|
|
41
|
+
/** Prints what a run did, then turns the error Kysely returns (it never throws) into a thrown one. */
|
|
42
|
+
export function report(resultSet, io, nothingToDo) {
|
|
43
|
+
const { error, results = [] } = resultSet;
|
|
44
|
+
for (const { direction, status, migrationName } of results)
|
|
45
|
+
io.out(`${direction} ${status} ${migrationName}`);
|
|
46
|
+
if (error !== undefined)
|
|
47
|
+
throw error instanceof Error ? error : new Error(`A migration threw something that is not an Error: ${inspect(error)}`);
|
|
48
|
+
if (results.length === 0)
|
|
49
|
+
io.out(nothingToDo);
|
|
50
|
+
}
|
|
51
|
+
/** `up`, `down` (one migration) or `status` against an open migrator. */
|
|
52
|
+
export async function runCommand(command, migrator, io) {
|
|
53
|
+
if (command === 'up') {
|
|
54
|
+
report(await migrator.migrateToLatest(), io, 'Already up to date.');
|
|
55
|
+
}
|
|
56
|
+
else if (command === 'down') {
|
|
57
|
+
report(await migrator.migrateDown(), io, 'Nothing to revert.');
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
for (const { name, executedAt } of await migrator.getMigrations()) {
|
|
61
|
+
io.out(`${executedAt === undefined ? 'pending' : 'applied'} ${name}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createCluster } from 'redis';
|
|
2
|
+
import { requireVariable } from "./env.mjs";
|
|
3
|
+
/**
|
|
4
|
+
* The cluster the services talk to, described by the variables `@axiumine/koa-utils`' Redis client reads:
|
|
5
|
+
* `REDIS_IS_CLUSTER=1`, the three root nodes `REDIS_DB1..3_HOST` / `_PORT`, `REDIS_USERNAME` and `REDIS_PASSWORD`. Throws
|
|
6
|
+
* a message that names the variable and never quotes a value. qPanel's Redis is a cluster only, so anything but
|
|
7
|
+
* `REDIS_IS_CLUSTER=1` is refused instead of falling back to one node.
|
|
8
|
+
*/
|
|
9
|
+
export function redisConfigFromEnv(env) {
|
|
10
|
+
if (env.REDIS_IS_CLUSTER !== '1')
|
|
11
|
+
throw new Error('REDIS_IS_CLUSTER is not 1: qPanel talks to a Redis cluster only.');
|
|
12
|
+
const rootNodes = [1, 2, 3].map((node) => `redis://${requireVariable(env, `REDIS_DB${String(node)}_HOST`)}:${requireVariable(env, `REDIS_DB${String(node)}_PORT`)}`);
|
|
13
|
+
return { rootNodes, username: requireVariable(env, 'REDIS_USERNAME'), password: requireVariable(env, 'REDIS_PASSWORD') };
|
|
14
|
+
}
|
|
15
|
+
/** Connects to the cluster and returns it as the Keygrip commands see it. Rejects when no root node answers. */
|
|
16
|
+
export const openRedisCluster = async ({ rootNodes, username, password }) => {
|
|
17
|
+
const cluster = createCluster({
|
|
18
|
+
rootNodes: rootNodes.map((url) => ({ url })),
|
|
19
|
+
defaults: { username, password }
|
|
20
|
+
});
|
|
21
|
+
await cluster.connect();
|
|
22
|
+
return cluster;
|
|
23
|
+
};
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { decryptSecret, rewrapSecret } from '@axiumine/qpanel-common/encryption/secretCipher';
|
|
2
|
+
import { sql } from 'kysely';
|
|
3
|
+
/** How many secrets one transaction re-wraps. A batch holds row locks, so it stays small. */
|
|
4
|
+
export const REWRAP_BATCH_SIZE = 100;
|
|
5
|
+
/** The `audit_event.action` of a re-wrap run. */
|
|
6
|
+
export const REWRAP_AUDIT_ACTION = 'master_key_rewrapped';
|
|
7
|
+
/**
|
|
8
|
+
* One batch, inside the caller's transaction. It first reads the ids of the next secrets that are not on the current
|
|
9
|
+
* key version, in id order, after `after`. A plain read: `SELECT … FOR UPDATE … LIMIT` can come back short under READ
|
|
10
|
+
* COMMITTED when a row it was about to lock has just been changed, and a short batch is indistinguishable from the end.
|
|
11
|
+
* Then it locks those rows and looks again at which of them still are not on the current version, so a secret that a
|
|
12
|
+
* service has just written (always under the current version) is left alone instead of being overwritten with a
|
|
13
|
+
* wrapped key that no longer fits its ciphertext.
|
|
14
|
+
*
|
|
15
|
+
* A row is re-wrapped, and the new wrap is opened again with the ring before the row is written, as `rewrapSecret`
|
|
16
|
+
* advises: a data key wrapped wrongly is a secret lost. A row that cannot be unwrapped, or whose new wrap does not
|
|
17
|
+
* open, is counted and left as it is. Only the two columns of the wrap, and `rotated_at`, are written: the ciphertext,
|
|
18
|
+
* the IV and the tag of the value do not change. Returns `undefined` when there is nothing left to look at.
|
|
19
|
+
*/
|
|
20
|
+
async function rewrapBatch(trx, ring, after, limit) {
|
|
21
|
+
let next = trx.selectFrom('secret').select('id').where('keyVersion', '<>', ring.current).orderBy('id').limit(limit);
|
|
22
|
+
if (after !== undefined)
|
|
23
|
+
next = next.where('id', '>', after);
|
|
24
|
+
const ids = (await next.execute()).map((row) => row.id);
|
|
25
|
+
const last = ids.at(-1);
|
|
26
|
+
if (last === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
const rows = await trx
|
|
29
|
+
.selectFrom('secret')
|
|
30
|
+
.select(['id', 'purpose', 'ciphertext', 'iv', 'authTag', 'wrappedDek', 'keyVersion'])
|
|
31
|
+
.where('id', 'in', ids)
|
|
32
|
+
.where('keyVersion', '<>', ring.current)
|
|
33
|
+
.forUpdate()
|
|
34
|
+
.execute();
|
|
35
|
+
const result = { last, rewrapped: 0, failed: 0 };
|
|
36
|
+
for (const row of rows) {
|
|
37
|
+
const binding = { id: row.id, purpose: row.purpose };
|
|
38
|
+
let wrap;
|
|
39
|
+
try {
|
|
40
|
+
wrap = rewrapSecret(ring, binding, row);
|
|
41
|
+
decryptSecret(ring, binding, { ...row, ...wrap });
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
result.failed += 1;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
await trx
|
|
48
|
+
.updateTable('secret')
|
|
49
|
+
.set({ wrappedDek: wrap.wrappedDek, keyVersion: wrap.keyVersion, rotatedAt: sql `now()` })
|
|
50
|
+
.where('id', '=', row.id)
|
|
51
|
+
.execute();
|
|
52
|
+
result.rewrapped += 1;
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Re-wraps the data key of every secret that is not on the ring's current key version, in batches of `batchSize`, one
|
|
58
|
+
* transaction each, and adds to `progress` after each batch commits. So it is idempotent and resumable: a run that
|
|
59
|
+
* stops half-way (the connection drops, the operator hits Ctrl-C) has committed whole batches, and the next run
|
|
60
|
+
* finds the rest by the version column. A secret it cannot re-wrap is counted in `progress.failed`, skipped, and not
|
|
61
|
+
* looked at again in this run, so one bad row never stops the others.
|
|
62
|
+
*
|
|
63
|
+
* ⚠️ The plaintext of a secret exists in this process for the instant of the check above and is never stored, printed or
|
|
64
|
+
* put in an error: every message `qpanel-common` throws is fixed.
|
|
65
|
+
*/
|
|
66
|
+
export async function rewrapSecrets(db, ring, progress, batchSize = REWRAP_BATCH_SIZE) {
|
|
67
|
+
let after;
|
|
68
|
+
for (;;) {
|
|
69
|
+
const batch = await db.transaction().execute((trx) => rewrapBatch(trx, ring, after, batchSize));
|
|
70
|
+
if (batch === undefined)
|
|
71
|
+
return;
|
|
72
|
+
progress.rewrapped += batch.rewrapped;
|
|
73
|
+
progress.failed += batch.failed;
|
|
74
|
+
after = batch.last;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** How many secrets sit on each key version, ascending by version. A version no secret uses is absent. */
|
|
78
|
+
export async function countSecretsByKeyVersion(db) {
|
|
79
|
+
const rows = await db
|
|
80
|
+
.selectFrom('secret')
|
|
81
|
+
.select(['keyVersion', (eb) => eb.fn.countAll().as('total')])
|
|
82
|
+
.groupBy('keyVersion')
|
|
83
|
+
.orderBy('keyVersion')
|
|
84
|
+
.execute();
|
|
85
|
+
return new Map(rows.map((row) => [row.keyVersion, Number(row.total)]));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Appends the `audit_event` of a re-wrap run: which version the secrets went to and how many were re-wrapped or left
|
|
89
|
+
* alone. No id, no key, nothing from a secret: `detail` never holds one (docs/data-model.md).
|
|
90
|
+
*/
|
|
91
|
+
export async function recordRewrap(db, toKeyVersion, { rewrapped, failed }) {
|
|
92
|
+
await db
|
|
93
|
+
.insertInto('auditEvent')
|
|
94
|
+
.values({ action: REWRAP_AUDIT_ACTION, entityType: 'secret', detail: JSON.stringify({ toKeyVersion, rewrapped, failed }) })
|
|
95
|
+
.execute();
|
|
96
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { requireVariable } from "./env.mjs";
|
|
2
|
+
function resolve(test, env, mainKey) {
|
|
3
|
+
const key = test ? `${mainKey}_TEST` : mainKey;
|
|
4
|
+
return { label: test ? 'test' : 'main', key, url: requireVariable(env, key) };
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* The database a migration run targets: `DATABASE_MIGRATOR_URL` normally, `DATABASE_MIGRATOR_URL_TEST` for the
|
|
8
|
+
* test database. Both hold the URL of a `qpanel_<env>_migrator` role. Throws a message that names the variable
|
|
9
|
+
* and never quotes its value.
|
|
10
|
+
*/
|
|
11
|
+
export function resolveTarget(test, env) {
|
|
12
|
+
return resolve(test, env, 'DATABASE_MIGRATOR_URL');
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The database a master-key run targets: `DATABASE_URL` normally, `DATABASE_URL_TEST` for the test database. Both
|
|
16
|
+
* hold the URL of a `qpanel_<env>_app` role, the one the services use (it has data access and no DDL): the
|
|
17
|
+
* master-key commands change rows and never the schema, so they have no use for the migrator. The same rules as
|
|
18
|
+
* `resolveTarget` otherwise.
|
|
19
|
+
*/
|
|
20
|
+
export function resolveAppTarget(test, env) {
|
|
21
|
+
return resolve(test, env, 'DATABASE_URL');
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,85 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axiumine/qpanel-db-setup",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.9.0-rc.0",
|
|
4
|
+
"description": "qPanel PostgreSQL migrations and the runner that applies them",
|
|
5
|
+
"homepage": "https://github.com/Axiumine/qpanel-db-setup#readme",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Axiumine/qpanel-db-setup.git"
|
|
9
|
+
},
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/Axiumine/qpanel-db-setup/issues"
|
|
12
|
+
},
|
|
13
|
+
"license": "AGPL-3.0-or-later",
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public",
|
|
16
|
+
"registry": "https://registry.npmjs.org/"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": "^26.13.1"
|
|
21
|
+
},
|
|
22
|
+
"packageManager": "yarn@4.18.1",
|
|
23
|
+
"bin": "./dist/src/bin.mjs",
|
|
24
|
+
"exports": {
|
|
25
|
+
"./package.json": "./package.json"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"sql",
|
|
30
|
+
"redis",
|
|
31
|
+
"CHANGELOG.md"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/src/bin.mjs",
|
|
35
|
+
"prepack": "yarn run build",
|
|
36
|
+
"upload": "npm stage publish --registry=https://registry.npmjs.org/",
|
|
37
|
+
"migrate:up": "node src/bin.mts up",
|
|
38
|
+
"migrate:down": "node src/bin.mts down",
|
|
39
|
+
"migrate:status": "node src/bin.mts status",
|
|
40
|
+
"migrate:create": "node src/bin.mts create",
|
|
41
|
+
"master-key": "node src/bin.mts master-key",
|
|
42
|
+
"keygrip": "node src/bin.mts keygrip",
|
|
43
|
+
"lint": "eslint --fix . && prettier --write .",
|
|
44
|
+
"lint:check": "eslint . && prettier --check .",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
46
|
+
"test": "vitest run",
|
|
47
|
+
"test:unit": "vitest run test/unit",
|
|
48
|
+
"test:cov": "vitest run --coverage && node scripts/coverage-audit.mjs",
|
|
49
|
+
"test:mutation": "stryker run",
|
|
50
|
+
"semgrep": "semgrep scan --metrics=off --disable-version-check --scan-unknown-extensions --config semgrep/ $(find src migrations scripts test -type f \\( -name '*.mts' -o -name '*.cts' -o -name '*.ts' -o -name '*.mjs' -o -name '*.cjs' -o -name '*.js' \\))",
|
|
51
|
+
"semgrep:ci": "semgrep scan --metrics=off --disable-version-check --scan-unknown-extensions --error --sarif --output semgrep.sarif --config semgrep/ $(find src migrations scripts test -type f \\( -name '*.mts' -o -name '*.cts' -o -name '*.ts' -o -name '*.mjs' -o -name '*.cjs' -o -name '*.js' \\))",
|
|
52
|
+
"qodana": "./qodana.sh",
|
|
53
|
+
"hooks:install": "git rev-parse --git-dir > /dev/null 2>&1 && git config core.hooksPath .githooks || true",
|
|
54
|
+
"postinstall": "[ ! -d .githooks ] || yarn run hooks:install"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@axiumine/qpanel-common": "^0.11.0",
|
|
58
|
+
"kysely": "^0.29.9",
|
|
59
|
+
"pg": "^8.23.1",
|
|
60
|
+
"redis": "^6"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@eslint/js": "^10.0.1",
|
|
64
|
+
"@stryker-mutator/core": "^10.1.1",
|
|
65
|
+
"@stryker-mutator/vitest-runner": "^10.1.1",
|
|
66
|
+
"@types/node": "^26.6.11",
|
|
67
|
+
"@types/pg": "^8.23.1",
|
|
68
|
+
"@vitest/coverage-v8": "^5.1.2",
|
|
69
|
+
"eslint": "^10.15.0",
|
|
70
|
+
"eslint-config-prettier": "^10.1.9",
|
|
71
|
+
"eslint-plugin-simple-import-sort": "^14.0.0",
|
|
72
|
+
"fast-check": "^4.11.0",
|
|
73
|
+
"globals": "^17.14.0",
|
|
74
|
+
"prettier": "^3.10.1",
|
|
75
|
+
"typescript": "^6.0.3",
|
|
76
|
+
"typescript-eslint": "^8.74.0",
|
|
77
|
+
"vite": "^8.4.0",
|
|
78
|
+
"vitest": "^5.1.2"
|
|
79
|
+
},
|
|
80
|
+
"resolutions": {
|
|
81
|
+
"minimatch@npm:~10.2.4": "npm:^11.0.9",
|
|
82
|
+
"qs@npm:6.15.1": "npm:^6.17.1",
|
|
83
|
+
"tar@npm:^7.5.7": "npm:^8.0.5"
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# qPanel — Redis Cluster ACL bootstrap.
|
|
3
|
+
#
|
|
4
|
+
# Creates (or resets) one environment's ACL user, `qpanel_<env>`, on every node of the cluster: keys and
|
|
5
|
+
# Pub/Sub channels limited to `qpanel_<env>:*`, data commands only (no @admin, no @dangerous, nothing that lists or flushes
|
|
6
|
+
# what other projects own), plus the read-only CLUSTER subcommands a cluster client needs to discover
|
|
7
|
+
# the topology. Manual steps: docs/redis-setup-manual.md. The meaning of each rule: docs/redis.md.
|
|
8
|
+
#
|
|
9
|
+
# ⚠️ Redis keeps ACL users per node — they are NOT propagated across a cluster. List every master AND
|
|
10
|
+
# every replica, and run this again whenever a node is added.
|
|
11
|
+
#
|
|
12
|
+
# Usage (from any machine that reaches the nodes, redis-cli 7+):
|
|
13
|
+
#
|
|
14
|
+
# BEs/qpanel-db-setup/redis/bootstrap-acl.sh [--tls] <env> <admin-user> <host:port> [<host:port> ...]
|
|
15
|
+
#
|
|
16
|
+
# <env> is dev (a developer's machine: the app and the integration tests, which use the prefix qpanel_dev:test:),
|
|
17
|
+
# staging or prod. Each has its own user and password; none can reach another's keys.
|
|
18
|
+
#
|
|
19
|
+
# It asks, at hidden prompts, for the admin user's password and for the new user's password (twice).
|
|
20
|
+
# That password reaches Redis only as its SHA-256 hash (`#<hex>` rule), so the plaintext never
|
|
21
|
+
# appears in a command line, the shell history, the Redis log or `ACL LIST`. The admin password is
|
|
22
|
+
# handed to redis-cli through REDISCLI_AUTH, never on the command line.
|
|
23
|
+
#
|
|
24
|
+
# Each node then persists its ACL: `ACL SAVE` when it runs with an aclfile, `CONFIG REWRITE` otherwise.
|
|
25
|
+
# Finally ACL DRYRUN proves the user may touch `qpanel_<env>:*` and may not touch anything else.
|
|
26
|
+
#
|
|
27
|
+
# The services connect through @axiumine/koa-utils, with keys set in .env.shared (env.shared.example):
|
|
28
|
+
# REDIS_IS_CLUSTER=1, any three of these nodes as REDIS_DB1..3_HOST / _PORT, REDIS_USERNAME=qpanel_<env>,
|
|
29
|
+
# REDIS_PASSWORD (the plaintext chosen here) and REDIS_KEY=qpanel_<env>: (inside the ACL's pattern).
|
|
30
|
+
|
|
31
|
+
set -euo pipefail
|
|
32
|
+
|
|
33
|
+
tls=()
|
|
34
|
+
if [[ ${1:-} == --tls ]]; then
|
|
35
|
+
tls=(--tls)
|
|
36
|
+
shift
|
|
37
|
+
fi
|
|
38
|
+
if (( $# < 3 )); then
|
|
39
|
+
echo "usage: $0 [--tls] <env> <admin-user> <host:port> [<host:port> ...] (env: dev, staging or prod)" >&2
|
|
40
|
+
exit 64
|
|
41
|
+
fi
|
|
42
|
+
case $1 in
|
|
43
|
+
dev | staging | prod) user=qpanel_$1 ;;
|
|
44
|
+
*)
|
|
45
|
+
echo "Unknown environment '$1': use dev, staging or prod (the tests use dev's user)." >&2
|
|
46
|
+
exit 64
|
|
47
|
+
;;
|
|
48
|
+
esac
|
|
49
|
+
admin=$2
|
|
50
|
+
shift 2
|
|
51
|
+
|
|
52
|
+
read -rsp "Password of Redis user ${admin}: " admin_pw
|
|
53
|
+
echo
|
|
54
|
+
read -rsp "New password for Redis user ${user}: " pw1
|
|
55
|
+
echo
|
|
56
|
+
read -rsp "Repeat it: " pw2
|
|
57
|
+
echo
|
|
58
|
+
if [[ $pw1 != "$pw2" ]]; then
|
|
59
|
+
echo "The two passwords differ." >&2
|
|
60
|
+
exit 1
|
|
61
|
+
fi
|
|
62
|
+
if (( ${#pw1} < 24 )); then
|
|
63
|
+
echo "Use at least 24 characters (e.g. openssl rand -base64 36)." >&2
|
|
64
|
+
exit 1
|
|
65
|
+
fi
|
|
66
|
+
hash=$(printf '%s' "$pw1" | sha256sum | cut -d' ' -f1)
|
|
67
|
+
unset pw1 pw2
|
|
68
|
+
|
|
69
|
+
export REDISCLI_AUTH=$admin_pw
|
|
70
|
+
unset admin_pw
|
|
71
|
+
|
|
72
|
+
# Same rules as docs/redis.md, which explains each one.
|
|
73
|
+
rules=(
|
|
74
|
+
reset on "#$hash"
|
|
75
|
+
"~${user}:*"
|
|
76
|
+
resetchannels "&${user}:*"
|
|
77
|
+
+@connection +@transaction +@keyspace +@string +@hash +@list +@set +@sortedset
|
|
78
|
+
+@stream +@bitmap +@hyperloglog +@geo +@pubsub +@scripting
|
|
79
|
+
-@admin -@dangerous
|
|
80
|
+
-scan -randomkey -pubsub -function -fcall -fcall_ro
|
|
81
|
+
'-script|flush' '-script|kill' '-script|debug'
|
|
82
|
+
'+cluster|slots' '+cluster|shards' '+cluster|info'
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
failed=0
|
|
86
|
+
for node in "$@"; do
|
|
87
|
+
host=${node%:*}
|
|
88
|
+
port=${node##*:}
|
|
89
|
+
cli=(redis-cli "${tls[@]}" -h "$host" -p "$port" --user "$admin" --no-auth-warning)
|
|
90
|
+
|
|
91
|
+
# Every call is judged where it is made. redis-cli exits non-zero when it cannot reach the node, and under
|
|
92
|
+
# `set -e` an assignment left unjudged would end the script there, silently, with the later nodes untouched.
|
|
93
|
+
if ! out=$("${cli[@]}" ACL SETUSER "$user" "${rules[@]}" 2>&1) || [[ $out != OK ]]; then
|
|
94
|
+
echo "$node: ACL SETUSER failed: $out" >&2
|
|
95
|
+
failed=1
|
|
96
|
+
continue
|
|
97
|
+
fi
|
|
98
|
+
|
|
99
|
+
if ! reply=$("${cli[@]}" CONFIG GET aclfile 2>&1); then
|
|
100
|
+
echo "$node: user set, but NOT persisted (a restart would drop it): $reply" >&2
|
|
101
|
+
failed=1
|
|
102
|
+
continue
|
|
103
|
+
fi
|
|
104
|
+
aclfile=$(sed -n 2p <<< "$reply")
|
|
105
|
+
if [[ -n $aclfile ]]; then
|
|
106
|
+
persist=(ACL SAVE)
|
|
107
|
+
else
|
|
108
|
+
persist=(CONFIG REWRITE)
|
|
109
|
+
fi
|
|
110
|
+
if ! out=$("${cli[@]}" "${persist[@]}" 2>&1) || [[ $out != OK ]]; then
|
|
111
|
+
echo "$node: user set, but NOT persisted (a restart would drop it): $out" >&2
|
|
112
|
+
failed=1
|
|
113
|
+
fi
|
|
114
|
+
|
|
115
|
+
# The exit status matters here too: a probe that never reached the node answers something other than OK, which is
|
|
116
|
+
# not a refusal.
|
|
117
|
+
denied=''
|
|
118
|
+
if ! allowed=$("${cli[@]}" ACL DRYRUN "$user" SET "${user}:bootstrap-check" 1 2>&1) ||
|
|
119
|
+
! denied=$("${cli[@]}" ACL DRYRUN "$user" GET not-qpanel 2>&1); then
|
|
120
|
+
echo "$node: ACL DRYRUN failed: ${denied:-$allowed}" >&2
|
|
121
|
+
failed=1
|
|
122
|
+
elif [[ $allowed == OK && $denied != OK ]]; then
|
|
123
|
+
echo "$node: ok (${user}:* allowed, other keys denied)"
|
|
124
|
+
else
|
|
125
|
+
echo "$node: unexpected DRYRUN result — allowed: '$allowed', denied: '$denied'" >&2
|
|
126
|
+
failed=1
|
|
127
|
+
fi
|
|
128
|
+
done
|
|
129
|
+
|
|
130
|
+
exit "$failed"
|