poad 2.76.0 → 2.76.2
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 +1 -1
- package/project/deploy.js +23 -8
- package/project/migrate.js +1 -1
- package/project/ref/index.js +2 -2
- package/project/ref/load.js +58 -18
- package/project/ref/ls.js +14 -4
- package/project/upgrade.js +1 -1
- package/test/api-exposure.test.js +40 -0
- package/test/fake-storage.js +150 -0
- package/test/project-sync.test.js +126 -10
- package/test/push-resume.test.js +179 -0
- package/test/reference-reload.test.js +94 -4
- package/utils/api-exposure/api-exposure.sql +11 -2
- package/utils/api-exposure/index.js +33 -11
- package/utils/help-details.js +13 -6
- package/utils/migrate-run.js +1 -1
- package/utils/project-sync/plan.js +55 -0
- package/utils/project-sync/run.js +216 -62
- package/utils/reference-store.js +93 -23
- package/utils/reference.js +87 -4
- package/utils/seed/apply.js +68 -4
- package/utils/seed/run.js +62 -2
- package/utils/storage-sync.js +164 -24
- package/utils/storage-tus.js +40 -4
- package/utils/storage.js +69 -19
package/package.json
CHANGED
package/project/deploy.js
CHANGED
|
@@ -98,7 +98,13 @@ function exposureOf(x) {
|
|
|
98
98
|
const items = x.items
|
|
99
99
|
.filter((i) => i && typeof i.schema === 'string' && typeof i.name === 'string')
|
|
100
100
|
.map((i) => ({ kind: String(i.kind || ''), schema: i.schema, name: i.name, signature: typeof i.signature === 'string' ? i.signature : undefined, reason: String(i.reason || ''), anon: Array.isArray(i.roles) ? i.roles.includes('anon') : true, authenticated: Array.isArray(i.roles) ? i.roles.includes('authenticated') : true, source: i.source, file: i.file }));
|
|
101
|
-
|
|
101
|
+
// Fonctions DEFINER des politiques RLS : à part, sans correctif (poad.io 0.70+ les sépare ; sinon policies/policies_indirect)
|
|
102
|
+
const policy_functions = (Array.isArray(x.policy_functions) ? x.policy_functions : []).filter((i) => i && typeof i.schema === 'string' && typeof i.name === 'string');
|
|
103
|
+
for (const i of items) {
|
|
104
|
+
const raw = x.items.find((r) => r && r.schema === i.schema && r.name === i.name && String(r.kind || '') === i.kind);
|
|
105
|
+
if (raw && (raw.policies || raw.policies_indirect || raw.policy)) Object.assign(i, { policies: raw.policies, policies_indirect: raw.policies_indirect, policy: raw.policy });
|
|
106
|
+
}
|
|
107
|
+
const out = require('../utils/api-exposure').impact({ current: x.current || null, target: x.target || x.current || null, items, policy_functions });
|
|
102
108
|
// La décision du serveur prime (il connaît la version de l'environnement)
|
|
103
109
|
if (typeof x.change === 'string') out.change = x.change;
|
|
104
110
|
return out;
|
|
@@ -119,7 +125,7 @@ function gitState(dir) {
|
|
|
119
125
|
}
|
|
120
126
|
|
|
121
127
|
module.exports = (args, raw) =>
|
|
122
|
-
require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss'] }, async ({ opts, out }) => {
|
|
128
|
+
require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss', 'verbose'] }, async ({ opts, out }) => {
|
|
123
129
|
const path = require('path');
|
|
124
130
|
const api = require('../utils/cloud/api');
|
|
125
131
|
const cli = require('../utils/cloud/cli');
|
|
@@ -168,7 +174,8 @@ module.exports = (args, raw) =>
|
|
|
168
174
|
if (b.deps && b.deps.packages.length) out.log(chalk.grey(` npm packages of the functions: ${b.deps.packages.join(', ')} (${b.deps.files} file(s) of poad/functions/node_modules)`));
|
|
169
175
|
for (const m of (b.deps && b.deps.missing) || []) out.log(chalk.yellowBright(` ⚠ ${m.from} imports "${m.spec}", not installed in poad/functions/node_modules: run "npm install ${m.spec}" in poad/functions, or this function will not build on poad.io.`));
|
|
170
176
|
if (b.deps && b.deps.outside.length) out.log(chalk.yellowBright(` ⚠ ${b.deps.outside.join(', ')}: installed above poad/functions, not sent. Install in poad/functions (npm install there).`));
|
|
171
|
-
|
|
177
|
+
// Grosses références : une ligne chacune ; ce qui les attend (déjà chargée, à charger…) est dit après les migrations
|
|
178
|
+
if (large.length) out.log(chalk.grey(` ${large.length} reference file(s) too large for git, through the reference store: ${large.map((f) => `${f.rel} (${kb(f.size)})`).join(', ')}`));
|
|
172
179
|
for (const f of ignored.tracked) out.log(chalk.yellowBright(` ⚠ poad/${f.rel} is tracked by git although it is too large: git rm --cached poad/${f.rel}`));
|
|
173
180
|
|
|
174
181
|
if (env.production && !dryRun) {
|
|
@@ -251,18 +258,26 @@ module.exports = (args, raw) =>
|
|
|
251
258
|
}
|
|
252
259
|
if (!m.applied.length && !m.pending.length && !m.errors.length) out.log(chalk.grey(' No migration to apply.'));
|
|
253
260
|
// Ce que l'API ne sert pas à anon ni à authenticated : jamais bloquant, toujours dit (avec le correctif)
|
|
254
|
-
|
|
261
|
+
// Fonctions DEFINER appelées par des politiques RLS : normales, hors sortie par défaut (--verbose, --json)
|
|
262
|
+
for (const l of require('../utils/api-exposure').lines(result.api_exposure, chalk, { verbose: Boolean(opts.verbose) })) out.log(l);
|
|
255
263
|
// Grosses références : après les migrations (les tables existent), envoi puis chargement
|
|
264
|
+
// État lu dans la base de l'environnement (marque posée au chargement, lignes) : un volume recréé vide recharge
|
|
256
265
|
let references = null;
|
|
257
|
-
if (large.length && !
|
|
258
|
-
|
|
259
|
-
|
|
266
|
+
if (large.length && !result.failed && !lossRefused) {
|
|
267
|
+
out.log(' ');
|
|
268
|
+
try {
|
|
269
|
+
references = await refStore.sendAndLoad(id, env.branch, poadDir, large, opts, out, { dryRun });
|
|
270
|
+
} catch (e) {
|
|
271
|
+
if (!dryRun) throw e;
|
|
272
|
+
out.log(chalk.yellowBright(` ⚠ reference tables: state not readable (${e.message})`));
|
|
273
|
+
}
|
|
274
|
+
if (references && references.failed) result.failed = true;
|
|
260
275
|
}
|
|
261
276
|
|
|
262
277
|
out.log(' ');
|
|
263
278
|
if (lossRefused) out.log(chalk.redBright(' Deploy refused: pending migrations lose data on production.'));
|
|
264
279
|
else if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
|
|
265
|
-
else if (dryRun &&
|
|
280
|
+
else if (dryRun && references && references.tables.some((t) => t.action !== 'unchanged')) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${references.tables.filter((t) => t.action !== 'unchanged').map((t) => t.target).join(', ')} would be ${references.tables.some((t) => t.action === 'send') ? 'sent and ' : ''}loaded.`);
|
|
266
281
|
else if (dryRun) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}.`);
|
|
267
282
|
else out.log(`${chalk.greenBright('✔')} Deployed to ${env.branch}${result.deploy_id ? chalk.grey(` (${result.deploy_id})`) : ''}.`);
|
|
268
283
|
out.log(' ');
|
package/project/migrate.js
CHANGED
|
@@ -37,7 +37,7 @@ module.exports = async (args, raw = []) => {
|
|
|
37
37
|
if (dryRun) report.dry_run = true;
|
|
38
38
|
// Tables de référence : après les migrations, quand leur structure est à jour
|
|
39
39
|
// --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
|
|
40
|
-
if (ok && !dryRun) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
|
|
40
|
+
if (ok && !dryRun) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference'), via: 'poad migrate' });
|
|
41
41
|
} finally {
|
|
42
42
|
console.log = log;
|
|
43
43
|
}
|
package/project/ref/index.js
CHANGED
|
@@ -6,8 +6,8 @@ module.exports = async () => {
|
|
|
6
6
|
console.log(' ');
|
|
7
7
|
console.log(` ${c('poad ref inspect <file>')} What the file holds, column by column, and its weight: nothing is sent`);
|
|
8
8
|
console.log(` ${c('poad ref push <file>')} Send each table of a .sql (INSERT, COPY) or .csv file as a reference table`);
|
|
9
|
-
console.log(` ${c('poad ref ls')} Reference tables stored on poad.io, and
|
|
10
|
-
console.log(` ${c('poad ref load [table…]')} Load them into an environment (--env), or into the local engine (--local)`);
|
|
9
|
+
console.log(` ${c('poad ref ls')} Reference tables stored on poad.io, and their state in each environment (read in its database)`);
|
|
10
|
+
console.log(` ${c('poad ref load [table…]')} Load them into an environment (--env), or into the local engine (--local); already loaded: skipped (--force)`);
|
|
11
11
|
console.log(` ${c('poad ref rm <table>')} Remove a reference from poad.io (the table keeps its rows)`);
|
|
12
12
|
console.log(' ');
|
|
13
13
|
console.log(chalk.grey(' Reference tables (municipalities, code lists…) are part of the project and are loaded everywhere,'));
|
package/project/ref/load.js
CHANGED
|
@@ -1,25 +1,50 @@
|
|
|
1
|
-
// poad ref load [table…] [--env <branche>] [--project <id>] [--json]
|
|
1
|
+
// poad ref load [table…] [--env <branche>] [--project <id>] [--force] [--json]
|
|
2
2
|
// poad ref load [table…] --local : dans l'engine Docker du projet de ce dossier
|
|
3
|
-
// Sans table : toutes celles du registre (
|
|
3
|
+
// Sans table : toutes celles du registre. Une table déjà chargée (marque posée au chargement, à l'empreinte du
|
|
4
|
+
// registre, autant de lignes qu'à la pose : lu dans la base visée) n'est pas rechargée, sauf --force.
|
|
4
5
|
module.exports = (args, raw) =>
|
|
5
|
-
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['local'] }, async ({ opts, positionals, out }) => {
|
|
6
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['local', 'force'] }, async ({ opts, positionals, out }) => {
|
|
6
7
|
const api = require('../../utils/cloud/api');
|
|
7
8
|
const cli = require('../../utils/cloud/cli');
|
|
9
|
+
const refStore = require('../../utils/reference-store');
|
|
8
10
|
const { parseTarget } = require('../../utils/seed/convert');
|
|
9
11
|
const S = require('../../utils/seed/run');
|
|
12
|
+
const A = require('../../utils/seed/apply');
|
|
10
13
|
const { chalk } = out;
|
|
14
|
+
const force = Boolean(opts.force);
|
|
11
15
|
const targets = positionals.map((t) => {
|
|
12
16
|
const v = parseTarget(t);
|
|
13
17
|
if (!v) throw api.usageError(`"${t}" is not schema.table`);
|
|
14
18
|
return v;
|
|
15
19
|
});
|
|
20
|
+
const pick = (items) => {
|
|
21
|
+
if (!targets.length) return items;
|
|
22
|
+
const missing = targets.filter((t) => !items.some((s) => s.target === t));
|
|
23
|
+
if (missing.length) throw api.usageError(`unknown reference: ${missing.join(', ')} ("poad ref ls")`);
|
|
24
|
+
return items.filter((s) => targets.includes(s.target));
|
|
25
|
+
};
|
|
16
26
|
const { id, root } = cli.targetProject(opts);
|
|
17
27
|
if (!opts.local) {
|
|
18
28
|
const branches = require('../../utils/cloud/branches');
|
|
19
29
|
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
30
|
+
const registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds?verify=${encodeURIComponent(env.branch)}`, { what: 'references' });
|
|
31
|
+
const items = pick(registry.items || []);
|
|
32
|
+
if (!items.length) throw api.usageError('No reference to load ("poad ref ls").');
|
|
33
|
+
const todo = [];
|
|
34
|
+
for (const s of items) {
|
|
35
|
+
const st = refStore.cloudState(registry, env.branch, s.target, s.sha256);
|
|
36
|
+
const loaded = st.state === 'loaded';
|
|
37
|
+
const line = { target: s.target, action: loaded && !force ? 'loaded' : 'load', state: loaded ? 'forced' : st.state, rows: st.rows, mark_rows: st.mark_rows, sha256: st.sha256 || s.sha256, expected_rows: s.rows, checked: st.checked };
|
|
38
|
+
out.log(refStore.planLine(line, env.branch, chalk));
|
|
39
|
+
if (!loaded || force) todo.push(s.target);
|
|
40
|
+
}
|
|
41
|
+
if (!todo.length) {
|
|
42
|
+
out.result({ project: id, branch: env.branch, load: null, unchanged: items.map((s) => s.target) });
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
20
45
|
const { startAndWait } = require('./push');
|
|
21
|
-
const l = await startAndWait(id, env.branch,
|
|
22
|
-
out.result({ project: id, load: l });
|
|
46
|
+
const l = await startAndWait(id, env.branch, todo, opts, out);
|
|
47
|
+
out.result({ project: id, branch: env.branch, load: l, unchanged: items.map((s) => s.target).filter((t) => !todo.includes(t)) });
|
|
23
48
|
return l.status === 'failed' ? api.EXIT.failed : 0;
|
|
24
49
|
}
|
|
25
50
|
// Engine local : le projet de ce dossier, démarré
|
|
@@ -27,25 +52,40 @@ module.exports = (args, raw) =>
|
|
|
27
52
|
const { readConfig } = require('../../utils/config');
|
|
28
53
|
const { isDockerExist } = require('../../utils/docker');
|
|
29
54
|
const config = readConfig(root);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const missing = targets.filter((t) => !items.some((s) => s.target === t));
|
|
35
|
-
if (missing.length) throw api.usageError(`unknown reference: ${missing.join(', ')} ("poad ref ls")`);
|
|
36
|
-
items = items.filter((s) => targets.includes(s.target));
|
|
37
|
-
}
|
|
55
|
+
const container = config.project_uuid;
|
|
56
|
+
if (!(await isDockerExist(container))) throw api.usageError('The local project is not started: "poad start".');
|
|
57
|
+
const list = await api.call('GET', `v1/projects/${api.enc(id)}/seeds?verify=0`, { what: 'references' });
|
|
58
|
+
const items = pick(list.items || []);
|
|
38
59
|
if (!items.length) throw api.usageError('No reference to load ("poad ref ls").');
|
|
39
|
-
const
|
|
40
|
-
|
|
60
|
+
const order = A.loadOrder(items.map((s) => s.target), await S.localEdges(container));
|
|
61
|
+
// État réel dans la base locale : une base remise à zéro ou une table vidée redeviennent « à charger »
|
|
62
|
+
const state = await S.localState(container, order);
|
|
63
|
+
if (!state) throw new api.CloudError('The local database cannot be read.', { code: 'local_db' });
|
|
41
64
|
const results = [];
|
|
42
65
|
for (const target of order) {
|
|
66
|
+
const s = items.find((x) => x.target === target);
|
|
67
|
+
const raw = state[target];
|
|
68
|
+
const st = A.referenceState(s.sha256, raw);
|
|
69
|
+
await S.localLog(container, [{ msg: `reference ${target}: ${st}`, attrs: { event: 'reference_state', table: target, state: st, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, sha256: s.sha256.slice(0, 12), env: 'local', via: 'poad ref load' } }]);
|
|
70
|
+
const line = { target, action: st === 'loaded' && !force ? 'loaded' : 'load', state: st === 'loaded' ? 'forced' : st, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, sha256: s.sha256, expected_rows: s.rows };
|
|
71
|
+
out.log(refStore.stateLine(line, 'locally', chalk));
|
|
72
|
+
if (st === 'no_table') {
|
|
73
|
+
results.push({ target, state: st, action: 'none' });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (line.action === 'loaded') {
|
|
77
|
+
results.push({ target, state: st, action: 'unchanged', rows: raw.rows });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
43
80
|
const t0 = Date.now();
|
|
44
81
|
const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
|
|
45
|
-
const r = await S.loadLocal(
|
|
46
|
-
|
|
82
|
+
const r = await S.loadLocal(container, d);
|
|
83
|
+
const ms = Date.now() - t0;
|
|
84
|
+
out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${(ms / 1000).toFixed(1)} s)`);
|
|
47
85
|
for (const w of r.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
|
|
48
|
-
|
|
86
|
+
await S.localLog(container, [{ msg: `reference ${target} loaded locally: ${r.written} rows`, attrs: { event: 'reference_load', table: target, outcome: 'loaded', reason: st, rows: r.written, deleted: r.deleted, duration_ms: ms, sha256: s.sha256.slice(0, 12), env: 'local', via: 'poad ref load' } }]);
|
|
87
|
+
results.push({ target, state: st, action: 'loaded', ...r });
|
|
49
88
|
}
|
|
50
89
|
out.result({ project: id, local: true, tables: results });
|
|
90
|
+
return results.some((r) => r.state === 'no_table') ? api.EXIT.failed : 0;
|
|
51
91
|
});
|
package/project/ref/ls.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// poad ref ls [--project <id>] [--json] : registre des références, quota, ce que chaque environnement a chargé
|
|
2
|
+
// (lu dans sa base par poad.io : déjà chargée, lignes et empreinte, ou à charger et pourquoi)
|
|
2
3
|
module.exports = (args, raw) =>
|
|
3
4
|
require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, out }) => {
|
|
4
5
|
const api = require('../../utils/cloud/api');
|
|
@@ -12,15 +13,24 @@ module.exports = (args, raw) =>
|
|
|
12
13
|
if (!r.store) out.log(chalk.yellowBright(' The reference store is not configured on this poad.io instance.'));
|
|
13
14
|
out.log(` Store: ${fmt(r.quota.used)} used of ${fmt(r.quota.limit)} (account quota, outside the project volume)`);
|
|
14
15
|
if (!r.items.length) return out.log(chalk.grey(' No reference stored yet: poad ref inspect <file>, then poad ref push <file>'));
|
|
15
|
-
|
|
16
|
+
// État lu dans la base de chaque environnement (poad.io : marque posée au chargement, lignes) ; sinon son registre
|
|
17
|
+
const { WHY } = require('../../utils/reference-store');
|
|
18
|
+
const envs = [...new Set([...Object.keys(r.state || {}), ...Object.keys(r.applied)])];
|
|
19
|
+
const n = (x) => Number(x || 0).toLocaleString('en-US');
|
|
16
20
|
out.log('');
|
|
17
21
|
for (const s of r.items) {
|
|
18
22
|
const state = envs.map((e) => {
|
|
19
|
-
const
|
|
20
|
-
|
|
23
|
+
const v = r.state && r.state[e] && r.state[e][s.target];
|
|
24
|
+
if (v && v.state === 'loaded') return chalk.greenBright(`${e}: already loaded (${n(v.rows)} rows, sha256 ${String(v.sha256).slice(0, 12)})`);
|
|
25
|
+
if (v && v.state === 'incomplete') return chalk.yellowBright(`${e}: to load (${n(v.rows)} of ${n(v.mark_rows)} rows)`);
|
|
26
|
+
if (v && WHY[v.state]) return chalk.yellowBright(`${e}: to load (${WHY[v.state]})`);
|
|
27
|
+
const a = r.applied[e] && r.applied[e][s.target];
|
|
28
|
+
const note = v && v.state === 'not_running' ? ', engine stopped: not checked' : v ? ', not checked' : '';
|
|
29
|
+
if (a) return a.sha256 === s.sha256 ? chalk.green(`${e}: loaded as recorded${note}`) : chalk.yellowBright(`${e}: to load (another version is loaded${note})`);
|
|
30
|
+
return v ? chalk.grey(`${e}: not loaded${note}`) : null;
|
|
21
31
|
}).filter(Boolean);
|
|
22
32
|
out.log(` ${chalk.bold(s.target)} ${s.rows} rows ${fmt(s.stored_bytes)} stored${s.db_bytes ? `, ≈ ${fmt(s.db_bytes)} in the database` : ''} ${chalk.grey(s.source || '')}${s.dropped && s.dropped.length ? chalk.grey(` without ${s.dropped.join(', ')}`) : ''}`);
|
|
23
|
-
|
|
33
|
+
for (const l of state.length ? state : [chalk.grey('not loaded anywhere yet')]) out.log(` ${l}`);
|
|
24
34
|
}
|
|
25
35
|
const last = r.loads[0];
|
|
26
36
|
if (last) out.log(chalk.grey(`\n Last load: ${last.branch}, ${last.status}${last.error ? ` (${last.error})` : ''}, ${new Date(last.started_at).toLocaleString()}`));
|
package/project/upgrade.js
CHANGED
|
@@ -148,7 +148,7 @@ module.exports = async (args = {}) => {
|
|
|
148
148
|
const exposure = require('../utils/api-exposure');
|
|
149
149
|
const found = exposure.readLocal(config.project_uuid);
|
|
150
150
|
if (found) {
|
|
151
|
-
const lines = exposure.lines(exposure.impact({ current, target, items: found.items }), chalk);
|
|
151
|
+
const lines = exposure.lines(exposure.impact({ current, target, items: found.items }), chalk, { verbose: process.argv.includes('--verbose') });
|
|
152
152
|
for (const l of lines) console.log(l);
|
|
153
153
|
if (lines.length) console.log(' ');
|
|
154
154
|
}
|
|
@@ -95,3 +95,43 @@ test('query : même requête que api-exposure.sql, sans les lignes psql, schéma
|
|
|
95
95
|
assert.deepEqual(seen.params, ['public,api']);
|
|
96
96
|
assert.equal(await exposure.query({ query: async () => { throw new Error('role "anon" does not exist'); } }, ['public']), null);
|
|
97
97
|
});
|
|
98
|
+
|
|
99
|
+
// --- Fonctions DEFINER appelées par des politiques RLS (motif contre la récursion) : pas de correctif ---------
|
|
100
|
+
|
|
101
|
+
test('fonction d’une politique RLS : à part, sans correctif ; mention courte seulement en --verbose', () => {
|
|
102
|
+
const helper = { kind: 'function', schema: 'public', name: 'mes_equipes', signature: 'mes_equipes()', reason: 'security_definer', anon: true, authenticated: true, policies: 2, policies_indirect: 0 };
|
|
103
|
+
const indirect = { ...helper, name: 'est_admin_brut', signature: 'est_admin_brut()', policies: 0, policies_indirect: 1 };
|
|
104
|
+
const x = exposure.afterMigrate({ engine: '0.73.1', before: [], after: [helper, indirect, definer] });
|
|
105
|
+
assert.equal(x.count, 1, 'seule la DEFINER isolée est avertie');
|
|
106
|
+
assert.deepEqual(x.items.map((i) => i.name), ['est_admin']);
|
|
107
|
+
assert.deepEqual(x.policy_functions.map((i) => i.name), ['mes_equipes', 'est_admin_brut']);
|
|
108
|
+
const quiet = exposure.migrateLines(x, chalk).join('\n');
|
|
109
|
+
assert.match(quiet, /alter function public\.est_admin\(uuid\) security invoker;/);
|
|
110
|
+
assert.ok(!/mes_equipes|est_admin_brut|RLS policies/.test(quiet), quiet);
|
|
111
|
+
const verbose = exposure.migrateLines(x, chalk, { verbose: true }).join('\n');
|
|
112
|
+
assert.match(verbose, /2 SECURITY DEFINER function\(s\) used by RLS policies: normal, not callable directly by the API \(rpc\) — public\.mes_equipes, public\.est_admin_brut/);
|
|
113
|
+
assert.ok(!/mes_equipes\(\) security invoker/.test(verbose), 'jamais le correctif pour elles');
|
|
114
|
+
// Seulement des fonctions de politiques : rien par défaut
|
|
115
|
+
const only = exposure.afterMigrate({ engine: '0.73.1', before: [], after: [helper] });
|
|
116
|
+
assert.equal(only.count, 0);
|
|
117
|
+
assert.deepEqual(exposure.migrateLines(only, chalk), []);
|
|
118
|
+
assert.equal(exposure.migrateLines(only, chalk, { verbose: true }).length, 1);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('poad deploy : poad.io sépare policy_functions (sans correctif), --json les garde', () => {
|
|
122
|
+
const r = summarize({
|
|
123
|
+
outcome: 'success',
|
|
124
|
+
api_exposure: { current: '0.73.1', target: '0.73.1', change: 'unchanged', items: [], policy_functions: [{ schema: 'public', name: 'mes_equipes', signature: 'mes_equipes()', policies: 2, policies_indirect: 0 }] },
|
|
125
|
+
});
|
|
126
|
+
assert.equal(r.api_exposure.count, 0);
|
|
127
|
+
assert.equal(r.api_exposure.policy_count, 1);
|
|
128
|
+
assert.deepEqual(exposure.lines(r.api_exposure, chalk), []);
|
|
129
|
+
assert.match(exposure.lines(r.api_exposure, chalk, { verbose: true }).join('\n'), /1 SECURITY DEFINER function\(s\) used by RLS policies/);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('api-exposure.sql compte les politiques qui appellent la fonction (pg_depend), directement ou par une fonction', () => {
|
|
133
|
+
const sql = fs.readFileSync(path.join(__dirname, '../utils/api-exposure/api-exposure.sql'), 'utf8');
|
|
134
|
+
assert.match(sql, /classid = 'pg_policy'::regclass/);
|
|
135
|
+
assert.match(sql, /as policies,/);
|
|
136
|
+
assert.match(sql, /as policies_indirect/);
|
|
137
|
+
});
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Faux Stockage poad en HTTP (storage 0.6+) pour les essais de poad push / pull et de poad storage sync :
|
|
2
|
+
// buckets, /sync/location, /sync/list, objets (GET avec Range, PUT, DELETE), envois TUS (POST, HEAD, PATCH).
|
|
3
|
+
// opts.backend 'file' (disque de l'engine) par défaut
|
|
4
|
+
// opts.slowPut ms d'attente entre deux morceaux lus d'un PUT (serveur lent)
|
|
5
|
+
// opts.stallPut le PUT n'est jamais lu (serveur figé)
|
|
6
|
+
// opts.cutAfter octets reçus par TUS au-delà desquels toute requête PATCH coupe la connexion (panne) ;
|
|
7
|
+
// fake.heal() rétablit
|
|
8
|
+
// opts.truncate un PUT n'enregistre que la moitié du contenu (serveur fautif)
|
|
9
|
+
// opts.ranges false : le service ignore Range (rend tout l'objet)
|
|
10
|
+
'use strict';
|
|
11
|
+
const http = require('http');
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
|
|
14
|
+
const md5 = (b) => crypto.createHash('md5').update(b).digest('hex');
|
|
15
|
+
|
|
16
|
+
function fakeStorage(t, opts = {}) {
|
|
17
|
+
const buckets = new Set(opts.buckets || []);
|
|
18
|
+
const objects = new Map(); // "bucket/name" → { body, type }
|
|
19
|
+
const uploads = new Map();
|
|
20
|
+
const stats = { put: 0, patchBytes: 0, rangeReads: 0, posts: 0, heads: 0 };
|
|
21
|
+
let cutAfter = opts.cutAfter ?? Infinity;
|
|
22
|
+
const put = (bucket, name, body, type = 'application/octet-stream') => {
|
|
23
|
+
buckets.add(bucket);
|
|
24
|
+
objects.set(`${bucket}/${name}`, { body: Buffer.from(body), type });
|
|
25
|
+
};
|
|
26
|
+
const row = (k, o) => ({ name: k.slice(k.indexOf('/') + 1), key: null, size: o.body.length, etag: md5(o.body), mimetype: o.type, cacheControl: 'no-cache' });
|
|
27
|
+
|
|
28
|
+
const server = http.createServer(async (req, res) => {
|
|
29
|
+
const url = new URL(req.url, 'http://x');
|
|
30
|
+
const route = decodeURIComponent(url.pathname.replace(/^\/storage\/v1/, ''));
|
|
31
|
+
const json = (status, body, headers = {}) => {
|
|
32
|
+
res.writeHead(status, { 'content-type': 'application/json', ...headers });
|
|
33
|
+
res.end(body === undefined ? '' : JSON.stringify(body));
|
|
34
|
+
};
|
|
35
|
+
const readAll = async () => {
|
|
36
|
+
const chunks = [];
|
|
37
|
+
for await (const c of req) chunks.push(c);
|
|
38
|
+
return Buffer.concat(chunks);
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
if (req.method === 'GET' && route === '/bucket') return json(200, [...buckets].map((id) => ({ id, name: id, public: false })));
|
|
42
|
+
if (req.method === 'POST' && route === '/bucket') {
|
|
43
|
+
const b = JSON.parse((await readAll()).toString());
|
|
44
|
+
if (buckets.has(b.name)) return json(409, { message: 'exists' });
|
|
45
|
+
buckets.add(b.name);
|
|
46
|
+
return json(200, { name: b.name });
|
|
47
|
+
}
|
|
48
|
+
if (req.method === 'GET' && route === '/sync/location') return json(200, { backend: opts.backend || 'file', location: null, fingerprint: null, shareable: false, project: {} });
|
|
49
|
+
if (req.method === 'GET' && route === '/status') return json(200, { backend: opts.backend || 'file' });
|
|
50
|
+
let m = /^\/sync\/list\/(.+)$/.exec(route);
|
|
51
|
+
if (req.method === 'POST' && m) {
|
|
52
|
+
await readAll();
|
|
53
|
+
if (!buckets.has(m[1])) return json(404, { message: 'bucket introuvable' });
|
|
54
|
+
return json(200, { objects: [...objects].filter(([k]) => k.startsWith(`${m[1]}/`)).map(([k, o]) => row(k, o)), next: null });
|
|
55
|
+
}
|
|
56
|
+
m = /^\/object\/([^/]+)$/.exec(route);
|
|
57
|
+
if (req.method === 'DELETE' && m) {
|
|
58
|
+
const { prefixes } = JSON.parse((await readAll()).toString());
|
|
59
|
+
const gone = prefixes.filter((n) => objects.delete(`${m[1]}/${n}`));
|
|
60
|
+
return json(200, gone.map((name) => ({ name })));
|
|
61
|
+
}
|
|
62
|
+
m = /^\/object\/([^/]+)\/(.+)$/.exec(route);
|
|
63
|
+
if (m && req.method === 'GET') {
|
|
64
|
+
const o = objects.get(`${m[1]}/${m[2]}`);
|
|
65
|
+
if (!o) return json(404, { message: 'introuvable' });
|
|
66
|
+
const r = /^bytes=(\d+)-(\d+)$/.exec(req.headers.range || '');
|
|
67
|
+
if (r && opts.ranges !== false) {
|
|
68
|
+
stats.rangeReads++;
|
|
69
|
+
const a = Number(r[1]);
|
|
70
|
+
const b = Math.min(o.body.length - 1, Number(r[2]));
|
|
71
|
+
res.writeHead(206, { 'content-type': o.type, 'content-length': String(b - a + 1), 'content-range': `bytes ${a}-${b}/${o.body.length}` });
|
|
72
|
+
return res.end(o.body.subarray(a, b + 1));
|
|
73
|
+
}
|
|
74
|
+
res.writeHead(200, { 'content-type': o.type, 'content-length': String(o.body.length) });
|
|
75
|
+
return res.end(o.body);
|
|
76
|
+
}
|
|
77
|
+
if (m && req.method === 'PUT') {
|
|
78
|
+
stats.put++;
|
|
79
|
+
if (opts.stallPut) return req.pause();
|
|
80
|
+
const chunks = [];
|
|
81
|
+
for await (const c of req) {
|
|
82
|
+
chunks.push(c);
|
|
83
|
+
if (opts.slowPut) {
|
|
84
|
+
req.pause();
|
|
85
|
+
await new Promise((r) => setTimeout(r, opts.slowPut));
|
|
86
|
+
req.resume();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const body = Buffer.concat(chunks);
|
|
90
|
+
put(m[1], m[2], opts.truncate ? body.subarray(0, body.length >> 1) : body, req.headers['content-type']);
|
|
91
|
+
return json(200, { name: m[2] });
|
|
92
|
+
}
|
|
93
|
+
if (req.method === 'POST' && route === '/upload/resumable') {
|
|
94
|
+
stats.posts++;
|
|
95
|
+
await readAll();
|
|
96
|
+
const meta = Object.fromEntries(String(req.headers['upload-metadata']).split(',').map((p) => p.split(' ')).map(([k, v]) => [k, Buffer.from(v, 'base64').toString()]));
|
|
97
|
+
const id = crypto.randomUUID();
|
|
98
|
+
uploads.set(id, { length: Number(req.headers['upload-length']), got: Buffer.alloc(0), meta });
|
|
99
|
+
return json(201, undefined, { location: `/storage/v1/upload/resumable/${id}` });
|
|
100
|
+
}
|
|
101
|
+
m = /^\/upload\/resumable\/(.+)$/.exec(route);
|
|
102
|
+
if (m) {
|
|
103
|
+
const u = uploads.get(m[1]);
|
|
104
|
+
if (!u) return json(404, { message: 'envoi introuvable' });
|
|
105
|
+
if (req.method === 'HEAD') {
|
|
106
|
+
stats.heads++;
|
|
107
|
+
res.writeHead(200, { 'upload-offset': String(u.got.length), 'upload-length': String(u.length) });
|
|
108
|
+
return res.end();
|
|
109
|
+
}
|
|
110
|
+
if (req.method === 'PATCH') {
|
|
111
|
+
if (Number(req.headers['upload-offset']) !== u.got.length) return json(409, { message: 'offset' }, { 'upload-offset': String(u.got.length) });
|
|
112
|
+
if (u.got.length >= cutAfter) return req.socket.destroy();
|
|
113
|
+
const body = await readAll();
|
|
114
|
+
u.got = Buffer.concat([u.got, body]);
|
|
115
|
+
stats.patchBytes += body.length;
|
|
116
|
+
if (u.got.length === u.length) {
|
|
117
|
+
put(u.meta.bucketName, u.meta.objectName, u.got, u.meta.contentType);
|
|
118
|
+
uploads.delete(m[1]);
|
|
119
|
+
}
|
|
120
|
+
res.writeHead(204, { 'upload-offset': String(u.got.length) });
|
|
121
|
+
return res.end();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
json(404, { message: 'route inconnue' });
|
|
125
|
+
} catch (e) {
|
|
126
|
+
if (!res.headersSent) json(500, { message: e.message });
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
return new Promise((resolve) => {
|
|
130
|
+
server.listen(0, '127.0.0.1', () => {
|
|
131
|
+
t.after(() => {
|
|
132
|
+
server.closeAllConnections?.();
|
|
133
|
+
server.close();
|
|
134
|
+
});
|
|
135
|
+
resolve({
|
|
136
|
+
base: `http://127.0.0.1:${server.address().port}`,
|
|
137
|
+
objects,
|
|
138
|
+
uploads,
|
|
139
|
+
buckets,
|
|
140
|
+
stats,
|
|
141
|
+
put,
|
|
142
|
+
heal: () => (cutAfter = Infinity),
|
|
143
|
+
cut: (n) => (cutAfter = n),
|
|
144
|
+
md5,
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
module.exports = { fakeStorage, md5 };
|