poad 2.63.0 → 2.65.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/global/start.js +7 -0
- package/package.json +2 -2
- package/poad.js +4 -3
- package/project/auth/import.js +68 -0
- package/project/auth/index.js +7 -0
- package/project/cli.js +7 -2
- package/project/db/import.js +138 -0
- package/project/db/index.js +1 -0
- package/project/deploy.js +22 -0
- package/project/gen/types.js +10 -2
- package/project/logs.js +2 -0
- package/project/source.js +341 -42
- package/project/storage/cp.js +4 -2
- package/project/upgrade.js +10 -0
- package/test/api-exposure.test.js +60 -0
- package/test/auth-import.test.js +113 -0
- package/test/cloud.test.js +1 -0
- package/test/data.test.js +24 -0
- package/test/deps.test.js +108 -0
- package/test/import.test.js +226 -0
- package/test/logs.test.js +12 -0
- package/test/naming.test.js +18 -0
- package/test/source.test.js +116 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +7 -0
- package/utils/api-exposure/api-exposure.sql +42 -0
- package/utils/api-exposure/index.js +97 -0
- package/utils/auth-import.js +204 -0
- package/utils/cloud/bundle.js +16 -2
- package/utils/cloud/deps.js +297 -0
- package/utils/data.js +41 -0
- package/utils/help-details.js +57 -4
- package/utils/import-upload.js +112 -0
- package/utils/logline.js +2 -2
- package/utils/logs.js +8 -1
- package/utils/naming.js +41 -0
- package/utils/runner.js +1 -1
- package/utils/storage-copy.js +31 -3
- package/utils/storage-tus.js +201 -0
- package/utils/storage.js +37 -1
package/test/source.test.js
CHANGED
|
@@ -28,6 +28,7 @@ const LIST = {
|
|
|
28
28
|
],
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
const YAML = 'name: communes-ref\nmode: synchronized\norigin:\n kind: rest\n url: "https://geo.api.gouv.fr/communes"\n format: json\ntable: public.ref_communes\nexisting: true\nkey: [code_insee]\ncolumns:\n code_insee: { from: code }\nrefresh:\n every: "0 4 * * 1"\n';
|
|
31
32
|
const BILAN = { source: 'communes', table: 'public.communes', received: 34969, kept: 34969, inserted: 34969, updated: 0, deleted: 0, unchanged: 0, rows: 34969, forced: false, problems: [], duration_ms: 812 };
|
|
32
33
|
const GUARD = 'source « communes » : 34 700 ligne(s) sur 34 969 seraient supprimées (plus de 20 %). Aucune ligne n\'a été modifiée.';
|
|
33
34
|
|
|
@@ -54,6 +55,14 @@ function fakeCloud(t, behaviour = {}) {
|
|
|
54
55
|
if (req.headers.authorization !== `Bearer ${SERVICE}` || req.headers.apikey !== ANON) return send(res, 401, { error: { code: 'unauthorized', message: 'bad token' } });
|
|
55
56
|
if (req.method === 'GET' && url.pathname === '/meta/v1/sources') return send(res, 200, LIST);
|
|
56
57
|
if (req.method === 'POST' && url.pathname === '/meta/v1/sources/communes/refresh') return send(res, 202, { source: 'communes', flow: 'source-communes', run_id: RUN, force: body && body.force === true, drift: { issues: [], sql: [] } });
|
|
58
|
+
if (req.method === 'GET' && url.pathname === '/meta/v1/sources/communes-ref/yaml') return send(res, 200, { name: 'communes-ref', stored: 'console', file: 'poad/sources/communes-ref.yaml', yaml: YAML });
|
|
59
|
+
if (req.method === 'GET' && url.pathname === '/meta/v1/sources/absente/yaml') return send(res, 404, { error: { code: 'not_found', message: 'source inconnue : absente' } });
|
|
60
|
+
if (req.method === 'POST' && url.pathname === '/meta/v1/sources/linked/inspect') {
|
|
61
|
+
if (body.host === '10.0.0.5') return send(res, 400, { error: { code: 'internal_address', message: 'adresse interne refusée (10.0.0.5) : une table liée lit une base sur internet' } });
|
|
62
|
+
return send(res, 200, { ok: true, schema: body.schema, table: body.table, key: ['id'], columns: [{ name: 'id', from: 'id', type: 'integer' }, { name: 'nom_client', from: 'Nom Client', type: 'text' }, { name: 'ville', from: 'ville', type: 'character varying(60)' }] });
|
|
63
|
+
}
|
|
64
|
+
if (req.method === 'POST' && url.pathname === '/meta/v1/sources') return send(res, 201, { name: 'clients', stored: 'file', file: 'poad/sources/clients.yaml', table: 'public.clients', mode: 'virtual', problems: [], report: { created: { migration: 'poad/migrations/20261202000000_source_clients_liee.sql' } } });
|
|
65
|
+
if (req.method === 'POST' && url.pathname === '/meta/v1/sources/clients/test') return send(res, 200, { ok: true, source: 'clients', readable: true, duration_ms: 12 });
|
|
57
66
|
if (req.method === 'POST' && url.pathname === '/meta/v1/sources/inconnue/refresh') return send(res, 404, { error: { code: 'not_found', message: 'source inconnue : inconnue', hint: 'déclarez-la dans poad/sources/inconnue.yaml' } });
|
|
58
67
|
if (req.method === 'GET' && url.pathname === `/flows/v1/runs/${RUN}`) {
|
|
59
68
|
state.polls++;
|
|
@@ -173,6 +182,40 @@ test('source refresh : source inconnue (message de meta), nom invalide et usage'
|
|
|
173
182
|
assert.strictEqual(other.status, 2, other.all);
|
|
174
183
|
});
|
|
175
184
|
|
|
185
|
+
test('source pull --env : déclaration créée dans la console écrite dans poad/sources, jamais écrasée sans --force', async (t) => {
|
|
186
|
+
const cloud = await fakeCloud(t);
|
|
187
|
+
const box = sandbox(t);
|
|
188
|
+
const file = path.join(box.app, 'poad', 'sources', 'communes-ref.yaml');
|
|
189
|
+
const r = await poad(box, cloud.api, ['source', 'pull', 'communes-ref', '--env', 'dev']);
|
|
190
|
+
noSecret(r);
|
|
191
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
192
|
+
assert.strictEqual(fs.readFileSync(file, 'utf8'), YAML);
|
|
193
|
+
assert.match(r.stdout, /✔ poad\/sources\/communes-ref\.yaml .*created in the console/);
|
|
194
|
+
assert.match(r.stdout, /poad deploy --env dev/);
|
|
195
|
+
// Déjà là : refusé sans --force, rien d'écrit ni de demandé
|
|
196
|
+
fs.writeFileSync(file, 'local\n');
|
|
197
|
+
const before = cloud.state.requests.length;
|
|
198
|
+
const again = await poad(box, cloud.api, ['source', 'pull', 'communes-ref', '--env', 'dev']);
|
|
199
|
+
assert.strictEqual(again.status, 1, again.all);
|
|
200
|
+
assert.match(again.stdout, /already exists: --force replaces it/);
|
|
201
|
+
assert.strictEqual(fs.readFileSync(file, 'utf8'), 'local\n');
|
|
202
|
+
assert.strictEqual(cloud.state.requests.length, before);
|
|
203
|
+
const forced = await poad(box, cloud.api, ['source', 'pull', 'communes-ref', '--force', '--env', 'dev']);
|
|
204
|
+
assert.strictEqual(forced.status, 0, forced.all);
|
|
205
|
+
assert.strictEqual(fs.readFileSync(file, 'utf8'), YAML);
|
|
206
|
+
// --stdout : rien d'écrit
|
|
207
|
+
fs.unlinkSync(file);
|
|
208
|
+
const out = await poad(box, cloud.api, ['source', 'pull', 'communes-ref', '--stdout', '--env', 'dev']);
|
|
209
|
+
assert.strictEqual(out.stdout, YAML);
|
|
210
|
+
assert.ok(!fs.existsSync(file));
|
|
211
|
+
// Inconnue, nom invalide, sans nom
|
|
212
|
+
const missing = await poad(box, cloud.api, ['source', 'pull', 'absente', '--env', 'dev']);
|
|
213
|
+
assert.strictEqual(missing.status, 1, missing.all);
|
|
214
|
+
assert.match(missing.stdout, /source inconnue : absente/);
|
|
215
|
+
assert.strictEqual((await poad(box, cloud.api, ['source', 'pull', '../x', '--env', 'dev'])).status, 2);
|
|
216
|
+
assert.strictEqual((await poad(box, cloud.api, ['source', 'pull', '--env', 'dev'])).status, 2);
|
|
217
|
+
});
|
|
218
|
+
|
|
176
219
|
// --- engine local (main avec deps) -----------------------------------------------
|
|
177
220
|
|
|
178
221
|
test('source ls en local : clé service_role du projet, engine 0.64.0 exigé, projet lancé exigé', async (t) => {
|
|
@@ -243,3 +286,76 @@ test('poad deploy : poad/sources est dans l’archive', (t) => {
|
|
|
243
286
|
assert.ok(files.some((f) => f.path === 'sources/communes.yaml'), JSON.stringify(files));
|
|
244
287
|
assert.ok(zlib.gunzipSync(bundle.build(dir).tgz).includes(Buffer.from('sources/communes.yaml')));
|
|
245
288
|
});
|
|
289
|
+
|
|
290
|
+
// --- Tables liées (mode virtual, engine 0.66.0) -----------------------------------------
|
|
291
|
+
|
|
292
|
+
test('source link --env : colonnes proposées par l’engine, brouillon sans secret, puis source test', async (t) => {
|
|
293
|
+
const cloud = await fakeCloud(t);
|
|
294
|
+
const box = sandbox(t);
|
|
295
|
+
const r = await poad(box, cloud.api, ['source', 'link', 'clients', '--host', 'db.example.com', '--database', 'crm', '--remote', 'ventes.Clients', '--credential', 'crm-lecture', '--columns', 'id,Nom Client', '--env', 'dev']);
|
|
296
|
+
noSecret(r);
|
|
297
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
298
|
+
const inspect = cloud.state.requests.find((q) => q.path === '/meta/v1/sources/linked/inspect').body;
|
|
299
|
+
assert.deepStrictEqual(inspect, { host: 'db.example.com', database: 'crm', credential: 'crm-lecture', sslmode: 'require', name: 'clients', schema: 'ventes', table: 'Clients' });
|
|
300
|
+
const draft = cloud.state.requests.find((q) => q.path === '/meta/v1/sources' && q.method === 'POST').body.draft;
|
|
301
|
+
assert.deepStrictEqual(draft, {
|
|
302
|
+
table: 'public.clients',
|
|
303
|
+
mode: 'virtual',
|
|
304
|
+
origin: { kind: 'postgres', host: 'db.example.com', database: 'crm', schema: 'ventes', table: 'Clients', credential: 'crm-lecture', sslmode: 'require' },
|
|
305
|
+
columns: [{ name: 'id', from: 'id', type: 'integer' }, { name: 'nom_client', from: 'Nom Client', type: 'text' }],
|
|
306
|
+
key: ['id'],
|
|
307
|
+
});
|
|
308
|
+
assert.match(r.stdout, /✔ clients {2}public\.clients → db\.example\.com\/crm · ventes\.Clients, 2 columns, nothing copied/);
|
|
309
|
+
assert.match(r.stdout, /never served by the API/);
|
|
310
|
+
const tst = await poad(box, cloud.api, ['source', 'test', 'clients', '--env', 'dev']);
|
|
311
|
+
assert.strictEqual(tst.status, 0, tst.all);
|
|
312
|
+
assert.match(tst.stdout, /✔ clients {2}the remote table answers \(12 ms\)/);
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
test('source link : adresse interne refusée par l’engine, colonne inconnue, usage', async (t) => {
|
|
316
|
+
const cloud = await fakeCloud(t);
|
|
317
|
+
const box = sandbox(t);
|
|
318
|
+
const r = await poad(box, cloud.api, ['source', 'link', 'clients', '--host', '10.0.0.5', '--database', 'crm', '--remote', 'Clients', '--credential', 'c', '--env', 'dev']);
|
|
319
|
+
assert.strictEqual(r.status, 1, r.all);
|
|
320
|
+
assert.match(r.stdout, /adresse interne refusée \(10\.0\.0\.5\)/);
|
|
321
|
+
assert.ok(!cloud.state.requests.some((q) => q.path === '/meta/v1/sources' && q.method === 'POST'), 'nothing declared');
|
|
322
|
+
const col = await poad(box, cloud.api, ['source', 'link', 'clients', '--host', 'db.example.com', '--database', 'crm', '--remote', 'Clients', '--credential', 'c', '--columns', 'absente', '--env', 'dev']);
|
|
323
|
+
assert.strictEqual(col.status, 1, col.all);
|
|
324
|
+
assert.match(col.stdout, /has no column "absente"/);
|
|
325
|
+
for (const args of [['source', 'link', 'clients'], ['source', 'link', 'clients', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c', '--sslmode', 'prefer'], ['source', 'test']]) {
|
|
326
|
+
const u = await poad(box, cloud.api, args);
|
|
327
|
+
assert.strictEqual(u.status, 2, u.all);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
test('sourceLines : table liée branchée ou non, origine sans identifiant', () => {
|
|
332
|
+
const s = { name: 'clients', valid: true, mode: 'virtual', table: 'public.clients', table_exists: true, origin: { kind: 'postgres', host: 'db.example.com', port: 6543, database: 'crm', schema: 'ventes', table: 'Clients', credential: 'crm-lecture' }, linked: { attached: true, address: '203.0.113.7', credential_problem: null }, problems: [] };
|
|
333
|
+
const strip = (lines) => lines.join('\n').replace(/\u001b\[[0-9;]*m/g, '');
|
|
334
|
+
assert.match(strip(source.sourceLines(s)), /✔ clients {2}linked table {2}public\.clients {2}db\.example\.com:6543\/crm · ventes\.Clients {2}linked \(203\.0\.113\.7\)/);
|
|
335
|
+
const off = strip(source.sourceLines({ ...s, linked: { attached: false, address: null, credential_problem: 'credential crm-lecture absent du coffre' } }));
|
|
336
|
+
assert.match(off, /! clients .*not linked/);
|
|
337
|
+
assert.match(off, /credential: credential crm-lecture absent du coffre/);
|
|
338
|
+
assert.match(off, /poad source test clients tells why/);
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
test('source import : formats lus par source-read et options du lecteur, refus clairs avant tout envoi', async (t) => {
|
|
342
|
+
const cloud = await fakeCloud(t);
|
|
343
|
+
const box = sandbox(t);
|
|
344
|
+
fs.writeFileSync(path.join(box.app, 'mesures.xlsx'), 'PK');
|
|
345
|
+
const badFormat = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--format', 'parquet']);
|
|
346
|
+
assert.strictEqual(badFormat.status, 2, badFormat.all);
|
|
347
|
+
assert.match(badFormat.all, /--format: csv, json, geojson, jsonl, ics, xlsx, ods, xml, kml, kmz, gpx \(got "parquet"\)/);
|
|
348
|
+
const badHeader = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--header', 'deux']);
|
|
349
|
+
assert.strictEqual(badHeader.status, 2, badHeader.all);
|
|
350
|
+
assert.match(badHeader.all, /--header takes a row number, or none/);
|
|
351
|
+
const badUntil = await poad(box, cloud.api, ['source', 'import', 'agenda.ics', '--expand-until', '31/12/2027']);
|
|
352
|
+
assert.strictEqual(badUntil.status, 2, badUntil.all);
|
|
353
|
+
assert.match(badUntil.all, /--expand-until takes a date, YYYY-MM-DD/);
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
test('describeReader : feuille, en-tête, enregistrements, répétitions, exécution', () => {
|
|
357
|
+
assert.strictEqual(source.describeReader({ details: { sheets: ['A', 'Mesures'], sheet: 'Mesures', header_row: 3 }, options: { sheet: 'Mesures', header: 3 }, run_id: 'r1' }), 'sheet "Mesures" (of "A", "Mesures"; --sheet), header on row 3, read by source-read (run r1)');
|
|
358
|
+
assert.strictEqual(source.describeReader({ details: { events: 9 }, options: { expand: { until: '2027-12-31' } } }), 'recurrences expanded until 2027-12-31, 9 event(s)');
|
|
359
|
+
assert.strictEqual(source.describeReader({ format: 'csv', csv: { delimiter: ';' } }), null);
|
|
360
|
+
assert.deepStrictEqual(source.FORMATS, ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx']);
|
|
361
|
+
});
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// poad storage cp : envoi en morceaux reprenables (utils/storage-tus.js), contre un faux Stockage TUS.
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const crypto = require('crypto');
|
|
8
|
+
const s = require('../utils/storage');
|
|
9
|
+
const c = require('../utils/storage-copy');
|
|
10
|
+
const t = require('../utils/storage-tus');
|
|
11
|
+
|
|
12
|
+
const ID = '0b8e8f7e-1b2c-4d5e-8f90-123456789abc';
|
|
13
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-tus-'));
|
|
14
|
+
process.env.POAD_UPLOADS_FILE = path.join(tmp, 'uploads.json');
|
|
15
|
+
test.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
|
|
16
|
+
|
|
17
|
+
/** Faux Stockage TUS : cut(n) → le n-ième PATCH n'en garde que la moitié et coupe la connexion */
|
|
18
|
+
function fakeTus({ cut = new Set(), tus = true, limit = Infinity } = {}) {
|
|
19
|
+
const uploads = new Map();
|
|
20
|
+
const objects = new Map();
|
|
21
|
+
const seen = [];
|
|
22
|
+
let patches = 0;
|
|
23
|
+
const doFetch = async (url, init = {}) => {
|
|
24
|
+
const route = new URL(url).pathname.replace('/storage/v1', '');
|
|
25
|
+
const h = init.headers || {};
|
|
26
|
+
seen.push({ method: init.method, route, headers: h });
|
|
27
|
+
const res = (status, headers = {}, body = null) => new Response(body, { status, headers });
|
|
28
|
+
if (route === '/upload/resumable' && init.method === 'POST') {
|
|
29
|
+
if (!tus) return res(404, {}, JSON.stringify({ error: 'NotFound', message: 'route inconnue' }));
|
|
30
|
+
if (Number(h['upload-length']) > limit) return res(413, {}, JSON.stringify({ error: 'EntityTooLarge', message: `taille maximale : ${limit} octets` }));
|
|
31
|
+
const meta = Object.fromEntries(h['upload-metadata'].split(',').map((p) => p.split(' ')).map(([k, v]) => [k, Buffer.from(v, 'base64').toString()]));
|
|
32
|
+
uploads.set(ID, { length: Number(h['upload-length']), got: Buffer.alloc(0), meta, upsert: h['x-upsert'] === 'true' });
|
|
33
|
+
return res(201, { location: `resumable/${ID}` });
|
|
34
|
+
}
|
|
35
|
+
const m = /^\/upload\/resumable\/(.+)$/.exec(route);
|
|
36
|
+
if (m) {
|
|
37
|
+
const u = uploads.get(m[1]);
|
|
38
|
+
if (!u) return res(404, {}, JSON.stringify({ message: 'envoi introuvable' }));
|
|
39
|
+
if (init.method === 'HEAD') return res(200, { 'upload-offset': String(u.got.length), 'upload-length': String(u.length) });
|
|
40
|
+
if (init.method === 'PATCH') {
|
|
41
|
+
patches++;
|
|
42
|
+
if (Number(h['upload-offset']) !== u.got.length) return res(409, { 'upload-offset': String(u.got.length) });
|
|
43
|
+
const body = Buffer.from(init.body);
|
|
44
|
+
if (cut.has(patches)) {
|
|
45
|
+
u.got = Buffer.concat([u.got, body.subarray(0, body.length >> 1)]);
|
|
46
|
+
throw new TypeError('fetch failed');
|
|
47
|
+
}
|
|
48
|
+
u.got = Buffer.concat([u.got, body]);
|
|
49
|
+
if (u.got.length === u.length) {
|
|
50
|
+
objects.set(`${u.meta.bucketName}/${u.meta.objectName}`, { body: u.got, type: u.meta.contentType });
|
|
51
|
+
uploads.delete(m[1]);
|
|
52
|
+
}
|
|
53
|
+
return res(204, { 'upload-offset': String(u.got.length) });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (/^\/object\/list\//.test(route)) return res(200, {}, '[]');
|
|
57
|
+
const o = /^\/object\/(.+)$/.exec(route);
|
|
58
|
+
if (o && init.method === 'PUT') {
|
|
59
|
+
const chunks = [];
|
|
60
|
+
for await (const ch of init.body) chunks.push(Buffer.from(ch));
|
|
61
|
+
objects.set(o[1], { body: Buffer.concat(chunks), type: h['content-type'] });
|
|
62
|
+
return res(201, {}, '{}');
|
|
63
|
+
}
|
|
64
|
+
if (o && objects.has(o[1])) return res(200, { 'content-type': objects.get(o[1]).type }, objects.get(o[1]).body);
|
|
65
|
+
return res(404, {}, JSON.stringify({ message: 'route inconnue' }));
|
|
66
|
+
};
|
|
67
|
+
return { doFetch, seen, objects, uploads };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const bigFile = (name, size) => {
|
|
71
|
+
const file = path.join(tmp, name);
|
|
72
|
+
fs.writeFileSync(file, crypto.randomBytes(size));
|
|
73
|
+
return file;
|
|
74
|
+
};
|
|
75
|
+
const md5 = (b) => crypto.createHash('md5').update(b).digest('hex');
|
|
76
|
+
const noWait = async () => {};
|
|
77
|
+
|
|
78
|
+
test('metadata and resume key', () => {
|
|
79
|
+
assert.strictEqual(t.metadata({ bucket: 'docs', key: 'a.pdf', type: 'application/pdf' }), `bucketName ${Buffer.from('docs').toString('base64')},objectName ${Buffer.from('a.pdf').toString('base64')},contentType ${Buffer.from('application/pdf').toString('base64')}`);
|
|
80
|
+
assert.strictEqual(t.idOf(`resumable/${ID}`), ID);
|
|
81
|
+
assert.notStrictEqual(t.resumeKey({ base: 'a', bucket: 'b', key: 'c', size: 1, mtimeMs: 1 }), t.resumeKey({ base: 'a', bucket: 'b', key: 'c', size: 2, mtimeMs: 1 }));
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('cp: above 6 MiB, chunks of 6 MiB, content intact, nothing kept after', async () => {
|
|
85
|
+
const f = fakeTus();
|
|
86
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
87
|
+
const file = bigFile('big.pdf', t.CHUNK * 2 + 77);
|
|
88
|
+
const { items } = await c.plan(api, file, 'poad:docs/');
|
|
89
|
+
const r = await c.run(api, items, {});
|
|
90
|
+
assert.strictEqual(r.errors.length, 0, r.errors.map((e) => e.error.message).join());
|
|
91
|
+
const patches = f.seen.filter((x) => x.method === 'PATCH');
|
|
92
|
+
assert.deepStrictEqual(patches.map((p) => Number(p.headers['content-length'])), [t.CHUNK, t.CHUNK, 77]);
|
|
93
|
+
assert.strictEqual(md5(f.objects.get('docs/big.pdf').body), md5(fs.readFileSync(file)));
|
|
94
|
+
assert.strictEqual(f.objects.get('docs/big.pdf').type, 'application/pdf');
|
|
95
|
+
assert.strictEqual(items[0].chunked, true);
|
|
96
|
+
assert.deepStrictEqual(t.readState(), {});
|
|
97
|
+
// Jamais la clé dans une URL ni dans le fichier de reprise
|
|
98
|
+
assert.ok(f.seen.every((x) => !x.route.includes('k=') && x.headers.authorization === 'Bearer k'));
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test('cp: connection cut in the middle of a chunk → HEAD, resumed at the right offset', async () => {
|
|
102
|
+
const f = fakeTus({ cut: new Set([2]) });
|
|
103
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
104
|
+
const file = bigFile('cut.bin', t.CHUNK * 3);
|
|
105
|
+
const resumed = [];
|
|
106
|
+
await t.tusUpload(api, t.fileSource(file, t.CHUNK * 3), { bucket: 'docs', key: 'cut.bin', base: 'http://x', mtimeMs: 1, onResume: (o) => resumed.push(o), sleep: noWait });
|
|
107
|
+
assert.deepStrictEqual(resumed, [t.CHUNK + t.CHUNK / 2]);
|
|
108
|
+
assert.strictEqual(md5(f.objects.get('docs/cut.bin').body), md5(fs.readFileSync(file)));
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('cp: command interrupted, run again → resumed where the server is, no new upload', async () => {
|
|
112
|
+
const cut = new Set([2, 3, 4, 5, 6, 7, 8, 9]);
|
|
113
|
+
const f = fakeTus({ cut });
|
|
114
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
115
|
+
const file = bigFile('again.bin', t.CHUNK * 3);
|
|
116
|
+
const st = fs.statSync(file);
|
|
117
|
+
const opts = { bucket: 'docs', key: 'again.bin', base: 'http://x', mtimeMs: st.mtimeMs, sleep: noWait };
|
|
118
|
+
await assert.rejects(t.tusUpload(api, t.fileSource(file, st.size), opts), /connection lost/);
|
|
119
|
+
assert.strictEqual(Object.keys(t.readState()).length, 1);
|
|
120
|
+
assert.ok(!fs.readFileSync(process.env.POAD_UPLOADS_FILE, 'utf8').includes('Bearer'));
|
|
121
|
+
cut.clear();
|
|
122
|
+
const r = await t.tusUpload(api, t.fileSource(file, st.size), opts);
|
|
123
|
+
assert.ok(r.resumedFrom > t.CHUNK);
|
|
124
|
+
assert.strictEqual(f.seen.filter((x) => x.method === 'POST').length, 1);
|
|
125
|
+
assert.strictEqual(md5(f.objects.get('docs/again.bin').body), md5(fs.readFileSync(file)));
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('cp: refused before any byte when the announced size is above the limit', async () => {
|
|
129
|
+
const f = fakeTus({ limit: 1000 });
|
|
130
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
131
|
+
const file = bigFile('huge.bin', t.CHUNK + 1);
|
|
132
|
+
const { items } = await c.plan(api, file, 'poad:docs/');
|
|
133
|
+
const r = await c.run(api, items, {});
|
|
134
|
+
assert.strictEqual(r.errors.length, 1);
|
|
135
|
+
assert.match(s.reason(r.errors[0].error), /at most 1000 bytes/);
|
|
136
|
+
assert.strictEqual(f.seen.filter((x) => x.method === 'PATCH').length, 0);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test('cp: an engine without chunked uploads → one request, as before', async () => {
|
|
140
|
+
const f = fakeTus({ tus: false });
|
|
141
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
142
|
+
const file = bigFile('old.bin', t.CHUNK + 5);
|
|
143
|
+
const { items } = await c.plan(api, file, 'poad:docs/');
|
|
144
|
+
const r = await c.run(api, items, {});
|
|
145
|
+
assert.strictEqual(r.errors.length, 0);
|
|
146
|
+
assert.ok(f.seen.some((x) => x.method === 'PUT'));
|
|
147
|
+
assert.strictEqual(api.noTus, true);
|
|
148
|
+
assert.strictEqual(f.objects.get('docs/old.bin').body.length, t.CHUNK + 5);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('cp: storage → storage above 6 MiB, read from the stream in chunks', async () => {
|
|
152
|
+
const f = fakeTus();
|
|
153
|
+
const data = crypto.randomBytes(t.CHUNK * 2 + 9);
|
|
154
|
+
f.objects.set('src/a.bin', { body: data, type: 'application/octet-stream' });
|
|
155
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
156
|
+
await c.transfer(api, { from: { bucket: 'src', key: 'a.bin' }, to: { bucket: 'dst', key: 'a.bin' }, size: data.length, type: 'application/octet-stream' });
|
|
157
|
+
assert.strictEqual(md5(f.objects.get('dst/a.bin').body), md5(data));
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test('[storage] file_size_limit of config.toml → POAD_STORAGE_FILE_SIZE_LIMIT in bytes', () => {
|
|
161
|
+
assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: '200MB' } }), ['POAD_STORAGE_FILE_SIZE_LIMIT=200000000']);
|
|
162
|
+
assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: '1GiB' } }), ['POAD_STORAGE_FILE_SIZE_LIMIT=1073741824']);
|
|
163
|
+
assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: 52428800 } }), ['POAD_STORAGE_FILE_SIZE_LIMIT=52428800']);
|
|
164
|
+
assert.deepStrictEqual(s.engineEnv({}), []);
|
|
165
|
+
const bad = s.fileSizeLimit({ storage: { file_size_limit: 'beaucoup' } });
|
|
166
|
+
assert.strictEqual(bad.value, null);
|
|
167
|
+
assert.match(bad.warning, /not a size/);
|
|
168
|
+
assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: 'beaucoup' } }), []);
|
|
169
|
+
});
|
package/test/storage.test.js
CHANGED
|
@@ -150,6 +150,13 @@ test('plan and run: storage → storage keeps the base name and the original typ
|
|
|
150
150
|
assert.strictEqual(one.items[0].to.key, 'z.png');
|
|
151
151
|
// Copie dans elle-même refusée
|
|
152
152
|
await assert.rejects(c.plan(api, 'poad:img/2024', 'poad:img/2024/', { recursive: true }), /inside/);
|
|
153
|
+
// Vers la racine du bucket qui la contient déjà : son contenu monte d'un cran (plus de refus « is inside »)
|
|
154
|
+
const up = await c.plan(api, 'poad:img/2024', 'poad:img', { recursive: true });
|
|
155
|
+
assert.deepStrictEqual(up.items.map((i) => i.to.key).sort(), ['b.png', 'sub/c.png']);
|
|
156
|
+
const up2 = await c.plan(api, 'poad:img/2024/sub', 'poad:img/2024/', { recursive: true });
|
|
157
|
+
assert.deepStrictEqual(up2.items.map((i) => i.to.key), ['2024/c.png']);
|
|
158
|
+
// La racine entière dans un de ses dossiers : toujours refusé
|
|
159
|
+
await assert.rejects(c.plan(api, 'poad:img/', 'poad:img/2024/', { recursive: true }), /inside/);
|
|
153
160
|
// Les deux chemins sur le disque : refusé
|
|
154
161
|
await assert.rejects(c.plan(api, 'a', 'b'), /must be in the storage/);
|
|
155
162
|
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
-- Ce que l'API de l'engine ne sert pas à anon ni à authenticated, parce qu'il leur ferait contourner le RLS
|
|
2
|
+
-- (service data 0.10.0, engine 0.64.0 ; servi à service_role depuis data 0.12.0, engine 0.66.0) : fonctions
|
|
3
|
+
-- SECURITY DEFINER, vues sans security_invoker = true, vues matérialisées des schémas exposés. Seuls ceux que anon
|
|
4
|
+
-- ou authenticated atteignent comptent (droit EXECUTE, ou SELECT / INSERT : l'interrupteur « API ») : ce sont
|
|
5
|
+
-- ceux qu'un front perd. Mêmes règles que services/data/src/schema.ts de l'engine (triggers, membres
|
|
6
|
+
-- d'extensions et fonctions à arguments OUT / INOUT / VARIADIC ne sont jamais servis : exclus).
|
|
7
|
+
--
|
|
8
|
+
-- Lecture seule, une ligne JSON. Lu ici plutôt que demandé au service data : la base d'un engine plus ancien que
|
|
9
|
+
-- 0.66.0 (celui qu'on s'apprête à mettre à jour) n'a pas de route pour le dire.
|
|
10
|
+
-- psql -v schemas=public,autre -f api-exposure.sql (poad upgrade ; même requête que poad-site deploy/cloud/api-exposure.sql)
|
|
11
|
+
set default_transaction_read_only = on;
|
|
12
|
+
\set ON_ERROR_STOP 1
|
|
13
|
+
select json_build_object(
|
|
14
|
+
'schemas', to_json(s.names),
|
|
15
|
+
'items', coalesce((select json_agg(i order by i.kind, i.schema, i.name) from (
|
|
16
|
+
select 'function' as kind, n.nspname as schema, p.proname as name, p.oid::regprocedure::text as signature,
|
|
17
|
+
'security_definer' as reason,
|
|
18
|
+
has_function_privilege('anon', p.oid, 'execute') as anon,
|
|
19
|
+
has_function_privilege('authenticated', p.oid, 'execute') as authenticated
|
|
20
|
+
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
|
21
|
+
where n.nspname = any (s.names) and p.prokind = 'f' and p.prosecdef
|
|
22
|
+
and p.prorettype not in ('trigger'::regtype, 'event_trigger'::regtype)
|
|
23
|
+
and not exists (select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e')
|
|
24
|
+
and not coalesce(p.proargmodes::text[] && array['o', 'b', 'v'], false)
|
|
25
|
+
-- une surcharge INVOKER du même nom est servie à sa place : rien n'est perdu
|
|
26
|
+
and not exists (select 1 from pg_proc o where o.pronamespace = p.pronamespace and o.proname = p.proname and not o.prosecdef and o.prokind = 'f')
|
|
27
|
+
and (has_function_privilege('anon', p.oid, 'execute') or has_function_privilege('authenticated', p.oid, 'execute'))
|
|
28
|
+
union all
|
|
29
|
+
select case c.relkind when 'm' then 'materialized_view' else 'view' end, n.nspname, c.relname, null,
|
|
30
|
+
case c.relkind when 'm' then 'materialized_view' else 'view_owner_rights' end,
|
|
31
|
+
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')
|
|
33
|
+
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
34
|
+
where n.nspname = any (s.names)
|
|
35
|
+
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)))
|
|
36
|
+
and not exists (select 1 from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')
|
|
37
|
+
and (has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select')
|
|
38
|
+
or has_table_privilege('anon', c.oid, 'insert') or has_table_privilege('authenticated', c.oid, 'insert'))
|
|
39
|
+
) i), '[]'::json)
|
|
40
|
+
)::jsonb::text -- une seule ligne (json_agg en met une par élément)
|
|
41
|
+
from (select array(select x from unnest(string_to_array(:'schemas', ',')) x
|
|
42
|
+
where x <> '' and x not in ('auth', 'storage', 'private', 'pg_catalog', 'information_schema')) as names) s;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Fonctions et vues qu'un front (clés anon / authenticated) ne reçoit pas par l'API de l'engine : SECURITY
|
|
2
|
+
// DEFINER, vues sans security_invoker, vues matérialisées. Elles lui feraient contourner le RLS.
|
|
3
|
+
// - engine avant 0.64.0 : servies à tout rôle qui a le droit ;
|
|
4
|
+
// - 0.64.0 à 0.65.x : refusées à tous les rôles (403 not_exposed) ;
|
|
5
|
+
// - 0.66.0 et plus : refusées à anon et authenticated, servies à service_role (qui contourne déjà le RLS).
|
|
6
|
+
// Même règle que poad.io (poad-site deploy/cloud/control/api-exposure.mjs) : poad deploy reçoit la liste du serveur,
|
|
7
|
+
// poad upgrade la lit dans la base locale (api-exposure.sql) avant de proposer la mise à jour.
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { spawnSync } = require('child_process');
|
|
11
|
+
|
|
12
|
+
const HIDDEN_SINCE = '0.64.0';
|
|
13
|
+
const SERVICE_ROLE_SINCE = '0.66.0';
|
|
14
|
+
const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
15
|
+
const cmp = (a, b) => {
|
|
16
|
+
const x = SEMVER.exec(a).slice(1).map(Number);
|
|
17
|
+
const y = SEMVER.exec(b).slice(1).map(Number);
|
|
18
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
19
|
+
return 0;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** served, refused_all, service_role_only ; null : version inconnue */
|
|
23
|
+
function phaseOf(engine) {
|
|
24
|
+
// Une image de dev (0.66.0-rpc) suit la règle de sa version
|
|
25
|
+
engine = String(engine || '').replace(/-.*$/, '');
|
|
26
|
+
if (!SEMVER.test(engine)) return null;
|
|
27
|
+
if (cmp(engine, SERVICE_ROLE_SINCE) >= 0) return 'service_role_only';
|
|
28
|
+
if (cmp(engine, HIDDEN_SINCE) >= 0) return 'refused_all';
|
|
29
|
+
return 'served';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const WHY = {
|
|
33
|
+
security_definer: 'SECURITY DEFINER: runs with its owner’s privileges',
|
|
34
|
+
view_owner_rights: 'view without security_invoker: reads with its owner’s privileges',
|
|
35
|
+
materialized_view: 'materialized view: no RLS',
|
|
36
|
+
};
|
|
37
|
+
const quote = (s) => (/^[a-z_][a-z0-9_]*$/.test(s) ? s : `"${String(s).replace(/"/g, '""')}"`);
|
|
38
|
+
|
|
39
|
+
/** Le correctif qui sert de nouveau l'objet à anon et authenticated, sous RLS */
|
|
40
|
+
function fixFor(i) {
|
|
41
|
+
const id = `${quote(i.schema)}.${quote(i.name)}`;
|
|
42
|
+
if (i.reason === 'security_definer') return `alter function ${i.signature || `${id}(…)`} security invoker; (or a SECURITY INVOKER function that calls it and checks auth.uid())`;
|
|
43
|
+
if (i.reason === 'view_owner_rights') return `alter view ${id} set (security_invoker = true);`;
|
|
44
|
+
return 'read it through a SECURITY INVOKER function that returns only allowed rows, or replace it with a table and policies';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Ce que la version visée change ; { change: lost | regained_service_role | unchanged | none, items } */
|
|
48
|
+
function impact({ current = null, target = null, items = [] } = {}) {
|
|
49
|
+
const from = phaseOf(current);
|
|
50
|
+
const to = phaseOf(target || current);
|
|
51
|
+
const all = items.map((i) => ({ kind: i.kind, schema: i.schema, name: i.name, ...(i.signature ? { signature: i.signature } : {}), reason: i.reason, why: WHY[i.reason] || i.reason, roles: ['anon', 'authenticated'].filter((r) => i[r] !== false), fix: fixFor(i), ...(i.source ? { source: i.source } : {}), ...(i.file ? { file: i.file } : {}) }));
|
|
52
|
+
let change = 'none';
|
|
53
|
+
if (all.length && to !== 'served') {
|
|
54
|
+
if (from === 'served' || from === null) change = 'lost';
|
|
55
|
+
else if (from === 'refused_all' && to === 'service_role_only') change = 'regained_service_role';
|
|
56
|
+
else change = 'unchanged';
|
|
57
|
+
}
|
|
58
|
+
return { current, target: target || current, phase: to, change, count: all.length, items: all };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** La liste lue dans la base de l'engine local (lecture seule) ; null si illisible */
|
|
62
|
+
function readLocal(container) {
|
|
63
|
+
const env = spawnSync('docker', ['exec', container, 'printenv', 'POAD_DATA_SCHEMAS'], { encoding: 'utf8', timeout: 10000 });
|
|
64
|
+
let schemas = String((env.status === 0 && env.stdout) || '').replace(/\s/g, '');
|
|
65
|
+
if (!/^[A-Za-z0-9_,]{1,200}$/.test(schemas)) schemas = 'public';
|
|
66
|
+
const sql = fs.readFileSync(path.join(__dirname, 'api-exposure.sql'), 'utf8');
|
|
67
|
+
const r = spawnSync('docker', ['exec', '-i', container, 'psql', '-X', '-qtA', '-U', 'postgres', '-h', '/var/run/postgresql', '-d', 'postgres', '-v', `schemas=${schemas}`, '-f', '-'], { input: sql, encoding: 'utf8', timeout: 30000 });
|
|
68
|
+
if (r.status !== 0) return null;
|
|
69
|
+
const line = String(r.stdout || '').trim().split('\n').pop();
|
|
70
|
+
try {
|
|
71
|
+
const o = JSON.parse(line);
|
|
72
|
+
return Array.isArray(o.items) ? o : null;
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Lignes à montrer (poad deploy, poad upgrade) ; [] si rien à dire */
|
|
79
|
+
function lines(x, chalk, { max = 20 } = {}) {
|
|
80
|
+
if (!x || !x.count || !x.change || x.change === 'none') return [];
|
|
81
|
+
const n = `${x.count} function(s) or view(s)`;
|
|
82
|
+
const head =
|
|
83
|
+
x.change === 'lost'
|
|
84
|
+
? `⚠ With engine ${x.target}, the API no longer serves ${n} to anon or authenticated: they would let them bypass RLS (403 not_exposed). service_role still gets them; they keep working in SQL.`
|
|
85
|
+
: x.change === 'regained_service_role'
|
|
86
|
+
? `ℹ ${n} stay refused to anon and authenticated (they would bypass RLS); with engine ${x.target}, service_role gets them again.`
|
|
87
|
+
: `ℹ ${n} are refused to anon and authenticated by the API (they would bypass RLS); service_role gets them.`;
|
|
88
|
+
const out = [x.change === 'lost' ? chalk.yellowBright(` ${head}`) : chalk.cyan(` ${head}`)];
|
|
89
|
+
for (const i of x.items.slice(0, max)) {
|
|
90
|
+
out.push(` ${chalk.bold(`${i.schema}.${i.name}`)} ${chalk.grey(`(${i.why}${i.roles.length ? `; ${i.roles.join(', ')}` : ''}${i.source === 'pending_migration' ? `; created by ${i.file || 'a pending migration'}` : ''})`)}`);
|
|
91
|
+
out.push(chalk.grey(` fix: ${i.fix}`));
|
|
92
|
+
}
|
|
93
|
+
if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (--json lists them all)`));
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines };
|