poad 2.76.1 → 2.76.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.76.1",
3
+ "version": "2.76.3",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
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
- const out = require('../utils/api-exposure').impact({ current: x.current || null, target: x.target || x.current || null, items });
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
- for (const f of large) out.log(chalk.grey(` ${f.rel} (${kb(f.size)}): too large for git: reference store, sent only if it changed (sha256), loaded if not yet loaded in ${env.branch}`));
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
- for (const l of require('../utils/api-exposure').lines(result.api_exposure, chalk)) out.log(l);
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 && !dryRun && !result.failed) {
258
- references = await refStore.sendAndLoad(id, env.branch, poadDir, large, opts, out);
259
- if (references.failed) result.failed = true;
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 && large.length) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${large.map((f) => f.target).join(', ')} would go to the reference store, then be loaded.`);
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(' ');
@@ -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
  }
@@ -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 what each environment has loaded`);
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,'));
@@ -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 (--reference : seulement les références).
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, targets.length ? targets : undefined, opts, out);
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
- if (!(await isDockerExist(config.project_uuid))) throw api.usageError('The local project is not started: "poad start".');
31
- const list = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
32
- let items = list.items;
33
- if (targets.length) {
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 A = require('../../utils/seed/apply');
40
- const order = A.loadOrder(items.map((s) => s.target), await S.localEdges(config.project_uuid));
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(config.project_uuid, d);
46
- out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${((Date.now() - t0) / 1000).toFixed(1)} s)`);
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
- results.push({ target, ...r });
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
- const envs = Object.keys(r.applied);
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 a = r.applied[e][s.target];
20
- return a ? (a.sha256 === s.sha256 ? chalk.greenBright(`${e} ✔`) : chalk.yellowBright(`${e} outdated`)) : null;
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
- out.log(` ${state.length ? state.join(' ') : chalk.grey('not loaded anywhere yet')}`);
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/source.js CHANGED
@@ -27,6 +27,7 @@
27
27
  // storage-token du plan de contrôle, renouvelé pendant un long suivi) et la
28
28
  // clé anon : jamais affichés. En local : la clé service_role du projet.
29
29
  const flows = require('./flows');
30
+ const { directUrl } = require('../utils/redirectors');
30
31
 
31
32
  const NAME_RE = /^(?:[a-z][a-z0-9-]{0,55}|[a-z_][a-z0-9_]{0,62})$/; // meta, sources.ts : SOURCE_NAME_RE (nom de table, ou d'avant 0.65.0)
32
33
  /** Formats d'une source (meta : sources.ts FORMATS ; ics… lus par l'étape source-read 1.3.0, engine avec meta 1.43.0) */
@@ -140,6 +141,10 @@ const parseLinkArgs = (words) => {
140
141
  if (o.url !== null && o.storage !== null) return { ok: false, message: 'poad source link: --url or --storage, not both.' };
141
142
  for (const k of ['host', 'port', 'database', 'remote', 'credential', 'sslmode']) if (o[k] !== null) return { ok: false, message: `--${k} is for a linked PostgreSQL table, not a file (--url or --storage).` };
142
143
  if (o.url !== null) {
144
+ // Lien de redirection (google.com/url?url=…, Outlook, Facebook…) : l'adresse du fichier qu'il porte
145
+ const d = directUrl(o.url);
146
+ o.url = d.url;
147
+ o.redirect = d.via;
143
148
  let u;
144
149
  try {
145
150
  u = new URL(o.url);
@@ -795,6 +800,7 @@ const main = async (args = {}, raw, deps = {}) => {
795
800
  const t = await ready();
796
801
  if (!t) return;
797
802
  const where = o.storage ? { storage: o.storage } : { url: o.url };
803
+ if (o.redirect && !json) console.log(chalk.grey(` ${o.redirect} redirect link: reading the file it points to, ${remoteLocation(where)}`));
798
804
  const csv = { ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) };
799
805
  const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/remote/inspect', { ...where, ...(o.format ? { format: o.format } : {}), ...(o.root ? { root: o.root } : {}), ...(Object.keys(csv).length ? { csv } : {}), ...(Object.keys(readerOptions(o)).length ? { options: readerOptions(o) } : {}), name: o.table }));
800
806
  if (!seen) return;
@@ -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
+ });
@@ -162,7 +162,7 @@ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, eve
162
162
  seen.push({ method: req.method, url: req.url, body });
163
163
  const send = (s, o) => (res.writeHead(s, { 'content-type': 'application/json' }), res.end(JSON.stringify(o)));
164
164
  if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
165
- if (/\/seeds$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
165
+ if (/\/seeds(\?.*)?$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
166
166
  if (/\/sync-plan$/.test(req.url)) return send(200, { space });
167
167
  if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
168
168
  if (/\/sync-events$/.test(req.url)) {
@@ -0,0 +1,23 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const { directUrl } = require('../utils/redirectors');
4
+ const source = require('../project/source');
5
+
6
+ const google = 'https://www.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://www.data.gouv.fr/api/1/organizations/meteo-france/datasets.csv&ved=2ahUKE&usg=AOvVaw3';
7
+
8
+ test('directUrl : liens de redirection déballés, adresses directes gardées', () => {
9
+ assert.deepStrictEqual(directUrl(google), { url: 'https://www.data.gouv.fr/api/1/organizations/meteo-france/datasets.csv', via: 'Google' });
10
+ assert.deepStrictEqual(directUrl('https://www.google.fr/url?q=https%3A%2F%2Fa.org%2Ff.csv%3Fx%3D1'), { url: 'https://a.org/f.csv?x=1', via: 'Google' });
11
+ assert.deepStrictEqual(directUrl('https://l.facebook.com/l.php?u=https%3A%2F%2Fa.org%2Ff.json&h=x'), { url: 'https://a.org/f.json', via: 'Facebook' });
12
+ assert.deepStrictEqual(directUrl('https://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fa.org%2Ff.csv&data=x'), { url: 'https://a.org/f.csv', via: 'Outlook' });
13
+ assert.deepStrictEqual(directUrl('https://a.org/f.csv'), { url: 'https://a.org/f.csv', via: null });
14
+ assert.deepStrictEqual(directUrl('https://www.google.com/search?q=https://a.org'), { url: 'https://www.google.com/search?q=https://a.org', via: null });
15
+ assert.deepStrictEqual(directUrl('https://www.google.com/url?q=javascript:alert(1)').via, null);
16
+ });
17
+
18
+ test('poad source link --url : un lien Google lit le fichier qu’il porte', () => {
19
+ const r = source.parseLinkArgs(['meteo', '--url', google]);
20
+ assert.strictEqual(r.ok, true);
21
+ assert.strictEqual(r.o.url, 'https://www.data.gouv.fr/api/1/organizations/meteo-france/datasets.csv');
22
+ assert.strictEqual(r.o.redirect, 'Google');
23
+ });
@@ -44,7 +44,7 @@ test('envoyée, jamais chargée dans cet environnement → chargée au deploy su
44
44
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
45
45
  let polls = 0;
46
46
  const calls = fakeApi(t, [
47
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
47
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
48
48
  [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l1', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
49
49
  [/^GET .*\/seeds\/loads\/l1$/, () => (++polls < 2 ? { status: 'running', steps: [{ target: 'public.commune', status: 'running' }] } : { status: 'done', steps: [{ target: 'public.commune', status: 'done', written: 4, deleted: 0, duration_ms: 1200 }] })],
50
50
  ]);
@@ -61,7 +61,7 @@ test('envoyée, jamais chargée dans cet environnement → chargée au deploy su
61
61
  test('déjà chargée dans cet environnement : ni envoi ni chargement', async (t) => {
62
62
  const { dir, files } = project();
63
63
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
64
- const calls = fakeApi(t, [[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
64
+ const calls = fakeApi(t, [[/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
65
65
  const { out } = output();
66
66
  const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
67
67
  assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
@@ -73,7 +73,7 @@ test('poad.io refuse faute de place (aucun ordre ne tient) : chaque table dite,
73
73
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
74
74
  const message = 'place insuffisante, même table par table : public.commune demande à elle seule environ 700.0 Mio, + 10 % de marge = 770.0 Mio, plus 256.0 Mio pour le journal (il manquerait 76.3 Mio). Pour passer : poad ref inspect public.commune, --exclude, ou une offre plus grande.';
75
75
  fakeApi(t, [
76
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
76
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
77
77
  [/^POST .*\/seeds\/load$/, () => {
78
78
  throw new api.CloudError(`reference load: ${message} (seed_no_space)`, { status: 413, code: 'seed_no_space', details: { code: 'seed_no_space', message, margin: 1.1, required: 1100, free: 1000, limit: 1024, tables: [{ target: 'public.commune', need: 734003200, status: 'refused' }, { target: 'public.region', need: 1, status: 'pending' }] } });
79
79
  }],
@@ -93,7 +93,7 @@ test('chargement table par table : annoncé, puis une table refusée en cours et
93
93
  const { dir, files } = project();
94
94
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
95
95
  fakeApi(t, [
96
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
96
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
97
97
  [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'stepwise', order: ['public.a', 'public.commune', 'public.c'] } })],
98
98
  [/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'failed', steps: [
99
99
  { target: 'public.a', status: 'done', written: 1, deleted: 0, duration_ms: 10, warnings: ['place restante faible sur l’engine main : 200.0 Mio libres sur 1.00 Gio (20 %)'] },
@@ -111,3 +111,93 @@ test('chargement table par table : annoncé, puis une table refusée en cours et
111
111
  assert.match(text, /public\.commune: refusée : place insuffisante/);
112
112
  assert.match(text, /public\.c: pending, not loaded into main; the next "poad deploy" loads it/);
113
113
  });
114
+
115
+ // --- État réel lu dans la base de l'environnement (poad.io : GET seeds?verify) : seed_applied n'est qu'un cache ---
116
+
117
+ const doneLoad = (written) => [
118
+ [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
119
+ [/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'done', steps: [{ target: 'public.commune', status: 'done', written, deleted: 0, duration_ms: 900 }] })],
120
+ ];
121
+
122
+ test('volume recréé vide : le registre dit « chargée », la base dit vide → rechargée, ligne « to load (table empty) »', async (t) => {
123
+ const { dir, files } = project();
124
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
125
+ const calls = fakeApi(t, [
126
+ [/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA, rows: 4 } } }, state: { main: { 'public.commune': { state: 'empty', rows: null, mark_rows: null, sha256: null } } } })],
127
+ ...doneLoad(4),
128
+ ]);
129
+ const { lines, out } = output();
130
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
131
+ assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action, x.state, x.reason]), [['public.commune', 'load', 'loaded', 'empty']]);
132
+ assert.ok(calls.some(([m, route]) => m === 'POST' && /seeds\/load$/.test(route)), 'rechargée');
133
+ assert.ok(!calls.some(([, route]) => /seeds\/upload/.test(route)), 'pas renvoyée');
134
+ assert.match(lines.join('\n'), /○ public\.commune to load in main \(table empty; 4 rows to load\)/);
135
+ });
136
+
137
+ test('déjà chargée, lu dans la base : ni envoi ni chargement, ligne avec lignes et empreinte', async (t) => {
138
+ const { dir, files } = project();
139
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
140
+ const calls = fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: {}, state: { main: { 'public.commune': { state: 'loaded', rows: 4, mark_rows: 4, sha256: SHA } } } })]]);
141
+ const { lines, out } = output();
142
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
143
+ assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
144
+ assert.strictEqual(calls.length, 1);
145
+ assert.match(lines.join('\n'), /✔ public\.commune already loaded in main \(4 rows, sha256 aaaaaaaaaaaa\)/);
146
+ assert.ok(!/not checked/.test(lines.join('\n')));
147
+ });
148
+
149
+ test('table vidée à la main : moins de lignes qu’à la pose de la marque → rechargée', async (t) => {
150
+ const { dir, files } = project();
151
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
152
+ fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA } } }, state: { main: { 'public.commune': { state: 'incomplete', rows: 0, mark_rows: 4, sha256: SHA } } } })], ...doneLoad(4)]);
153
+ const { lines, out } = output();
154
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
155
+ assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['load', 'loaded']]);
156
+ assert.match(lines.join('\n'), /to load in main \(0 of 4 rows/);
157
+ });
158
+
159
+ test('--dry-run : une ligne par table (déjà chargée / à charger / à envoyer puis charger), rien d’envoyé ni de chargé', async (t) => {
160
+ const { dir } = project();
161
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
162
+ fs.writeFileSync(path.join(dir, 'reference', 'public.region.jsonl'), '{"id":1}\n'.repeat(8));
163
+ fs.writeFileSync(path.join(dir, 'reference', 'public.zone.jsonl'), '{"id":1}\n'.repeat(8));
164
+ const files = store.largeFiles(dir, 5);
165
+ const cache = JSON.parse(fs.readFileSync(path.join(dir, 'data', 'reference-store.json'), 'utf8'));
166
+ const reg = files.find((f) => f.target === 'public.region');
167
+ cache[reg.file] = { size: reg.size, mtimeMs: reg.mtimeMs, sha256: 'b'.repeat(64), target: reg.target };
168
+ fs.writeFileSync(path.join(dir, 'data', 'reference-store.json'), JSON.stringify(cache));
169
+ const calls = fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({
170
+ store: true,
171
+ items: [{ target: 'public.commune', sha256: SHA, rows: 4 }, { target: 'public.region', sha256: 'b'.repeat(64), rows: 8 }],
172
+ applied: {},
173
+ state: { main: { 'public.commune': { state: 'loaded', rows: 4, mark_rows: 4, sha256: SHA }, 'public.region': { state: 'unmarked', rows: null, sha256: null } } },
174
+ })]]);
175
+ const { lines, out } = output();
176
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out, { dryRun: true });
177
+ assert.strictEqual(calls.length, 1, 'une lecture, rien d’autre');
178
+ assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action]), [['public.commune', 'unchanged'], ['public.region', 'load'], ['public.zone', 'send']]);
179
+ const text = lines.join('\n');
180
+ assert.match(text, /✔ public\.commune already loaded in main \(4 rows, sha256 aaaaaaaaaaaa\)/);
181
+ assert.match(text, /○ public\.region would be loaded in main \(rows without the load mark; 8 rows to load\)/);
182
+ assert.match(text, /○ public\.zone would be sent, then loaded in main \(never sent\)/);
183
+ assert.ok(!/loaded if not yet loaded/.test(text), 'plus de message générique');
184
+ });
185
+
186
+ test('poad.io d’avant la vérification (pas de state) : le registre, dit « not checked »', async (t) => {
187
+ const { dir, files } = project();
188
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
189
+ fakeApi(t, [[/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA, rows: 4 } } } })]]);
190
+ const { lines, out } = output();
191
+ await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out, { dryRun: true });
192
+ assert.match(lines.join('\n'), /already loaded in main \(4 rows, sha256 aaaaaaaaaaaa, as recorded by poad\.io: not checked in the database\)/);
193
+ });
194
+
195
+ test('verdict partagé avec poad.io (seed-format.mjs) : marque, empreinte, lignes', () => {
196
+ const A = require('../utils/seed/apply');
197
+ assert.strictEqual(A.referenceState(SHA, { exists: true, empty: true }), 'empty');
198
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: SHA, rows: 3, mark_rows: 4 }), 'incomplete');
199
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: 'b'.repeat(64), rows: 4, mark_rows: 4 }), 'outdated');
200
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: SHA, rows: 4, mark_rows: 4 }), 'loaded');
201
+ assert.ok(A.tail('public.commune', ['id'], SHA).includes("insert into _poad.reference_loads (target, sha256, rows) select 'public.commune'"));
202
+ assert.ok(!A.tail('public.commune', ['id']).includes('reference_loads'));
203
+ });
@@ -16,7 +16,15 @@ select json_build_object(
16
16
  select 'function' as kind, n.nspname as schema, p.proname as name, p.oid::regprocedure::text as signature,
17
17
  'security_definer' as reason,
18
18
  has_function_privilege('anon', p.oid, 'execute') as anon,
19
- has_function_privilege('authenticated', p.oid, 'execute') as authenticated
19
+ has_function_privilege('authenticated', p.oid, 'execute') as authenticated,
20
+ -- Appelée par des politiques RLS (motif classique contre leur récursion) : normal, pas de correctif
21
+ -- « security invoker » (il casserait les politiques). Directement (pg_depend de pg_policy : USING,
22
+ -- WITH CHECK), ou par une fonction qu'une politique appelle et dont le corps la nomme (un niveau).
23
+ (select count(distinct d.objid) from pg_depend d
24
+ where d.classid = 'pg_policy'::regclass and d.refclassid = 'pg_proc'::regclass and d.refobjid = p.oid) as policies,
25
+ (select count(distinct d.objid) from pg_depend d join pg_proc f on f.oid = d.refobjid
26
+ where d.classid = 'pg_policy'::regclass and d.refclassid = 'pg_proc'::regclass and f.oid <> p.oid
27
+ and f.prosrc ~* ('\m' || regexp_replace(p.proname, '([^A-Za-z0-9_])', '\\\1', 'g') || '\M')) as policies_indirect
20
28
  from pg_proc p join pg_namespace n on n.oid = p.pronamespace
21
29
  where n.nspname = any (s.names) and p.prokind = 'f' and p.prosecdef
22
30
  and p.prorettype not in ('trigger'::regtype, 'event_trigger'::regtype)
@@ -29,7 +37,8 @@ select json_build_object(
29
37
  select case c.relkind when 'm' then 'materialized_view' else 'view' end, n.nspname, c.relname, null,
30
38
  case c.relkind when 'm' then 'materialized_view' else 'view_owner_rights' end,
31
39
  has_table_privilege('anon', c.oid, 'select') or has_table_privilege('anon', c.oid, 'insert'),
32
- has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert')
40
+ has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert'),
41
+ 0, 0
33
42
  from pg_class c join pg_namespace n on n.oid = c.relnamespace
34
43
  where n.nspname = any (s.names)
35
44
  and (c.relkind = 'm' or (c.relkind = 'v' and not coalesce((select bool_or(lower(o) in ('security_invoker=true', 'security_invoker=on', 'security_invoker=yes', 'security_invoker=1')) from unnest(c.reloptions) o), false)))