test: liaison de compte, exécution isolée, quota par utilisateur
- consentement obligatoire (400 sans case, rien stocké), drapeau de désactivation, onboarding bloquant - secrets absents de la base, des journaux, des réponses et des erreurs - le secret vient du user_id du job, environnement enfant assaini, argv bubblewrap, clones git durcis - quota et budget propres à chaque compte, délier
This commit is contained in:
parent
74b8d27b6c
commit
1d6f6e1544
11 changed files with 887 additions and 20 deletions
|
|
@ -95,8 +95,11 @@ test('Google : inscription automatique à la première connexion, session, PKCE
|
||||||
assert.ok(u.last_login_at);
|
assert.ok(u.last_login_at);
|
||||||
assert.equal(u.claude_link_json, null);
|
assert.equal(u.claude_link_json, null);
|
||||||
|
|
||||||
const home = await s.client(sid.split(';')[0]).get('/');
|
const home = await s.client(sid.split(';')[0]).get('/', { headers: { accept: 'text/html' } });
|
||||||
assert.equal(home.status, 200, 'la session ouvre le tableau de bord');
|
// Nouveau compte sans liaison Claude : l'onboarding bloquant renvoie vers la page de liaison
|
||||||
|
assert.equal(home.status, 303);
|
||||||
|
assert.equal(home.headers.get('location'), '/link');
|
||||||
|
assert.equal((await s.client(sid.split(';')[0]).get('/link')).status, 200, 'la session ouvre la page de liaison');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Google : seconde connexion = même compte, pas de doublon', async () => {
|
test('Google : seconde connexion = même compte, pas de doublon', async () => {
|
||||||
|
|
|
||||||
445
test/claude-link.test.js
Normal file
445
test/claude-link.test.js
Normal file
|
|
@ -0,0 +1,445 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { now, getSetting, setSetting } from '../src/db.js';
|
||||||
|
import { decrypt } from '../src/crypto.js';
|
||||||
|
import { enqueue, Worker, jobRefusal } from '../src/services/jobs.js';
|
||||||
|
import { AI_JOBS } from '../src/services/budget.js';
|
||||||
|
import { makeClaude } from '../src/handlers.js';
|
||||||
|
import {
|
||||||
|
LINK_REQUIRED_MESSAGE, CONSENT_VERSION, CONSENT_CHECKBOX, aiRefusal, validateApiKey, getLinkState,
|
||||||
|
} from '../src/claudelink.js';
|
||||||
|
import { startApp } from './helpers/server.js';
|
||||||
|
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||||
|
|
||||||
|
// Liaison Claude : clé API, jeton d'abonnement avec consentement, mode serveur, onboarding bloquant, déliaison.
|
||||||
|
// Aucun appel réseau ni CLI réel : fetch injecté, CLI simulé par les fixtures.
|
||||||
|
let s, binDir;
|
||||||
|
const KEY_A = `sk-ant-api03-${'A'.repeat(40)}ZZ12`;
|
||||||
|
const KEY_B = `sk-ant-api03-${'B'.repeat(40)}QQ34`;
|
||||||
|
const TOKEN = `sk-ant-oat01-${'T'.repeat(48)}`;
|
||||||
|
const AI_ROUTES = ['analyze', 'template', 'followup_template', 'prospect', 'evolution'];
|
||||||
|
const logs = [];
|
||||||
|
const realConsole = { log: console.log, warn: console.warn, error: console.error };
|
||||||
|
|
||||||
|
// Réponses de « api.anthropic.com » : 200 par défaut, modifiable par test
|
||||||
|
let apiStatus = 200, apiThrows = false;
|
||||||
|
const apiCalls = [];
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
binDir = mkdtempSync(join(tmpdir(), 'aitools-bin-'));
|
||||||
|
s = await startApp({ cfg: { claudeBin: makeClaudeBin(binDir) } });
|
||||||
|
s.app.fetch = async (url, opts) => {
|
||||||
|
apiCalls.push({ url, headers: opts?.headers });
|
||||||
|
if (apiThrows) throw new Error('ECONNRESET');
|
||||||
|
return { status: apiStatus, ok: apiStatus >= 200 && apiStatus < 300 };
|
||||||
|
};
|
||||||
|
for (const k of Object.keys(realConsole)) console[k] = (...a) => { logs.push(a.map(String).join(' ')); };
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
Object.assign(console, realConsole);
|
||||||
|
await s.close();
|
||||||
|
rmSync(binDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const row = (id) => s.db.prepare('SELECT claude_link_json FROM users WHERE id = ?').get(id);
|
||||||
|
const dump = async () => JSON.stringify([
|
||||||
|
await s.db.prepare('SELECT * FROM users').all(), await s.db.prepare('SELECT * FROM user_settings').all(),
|
||||||
|
await s.db.prepare('SELECT * FROM jobs').all(), await s.db.prepare('SELECT * FROM sessions').all(),
|
||||||
|
]);
|
||||||
|
const project = async (u) => Number((await s.db.prepare(`INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at)
|
||||||
|
VALUES(?, 'P', ?, ?, ?, 1, ?)`).run(u.id, `https://git.test/u${u.id}/p.git`, JSON.stringify({ resume: 'x' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||||
|
|
||||||
|
test('clé API : validée sans coût (GET /v1/models), chiffrée, jamais réaffichée', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
apiCalls.length = 0; apiStatus = 200;
|
||||||
|
const r = await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal(apiCalls.length, 1);
|
||||||
|
assert.equal(apiCalls[0].url, 'https://api.anthropic.com/v1/models');
|
||||||
|
assert.equal(apiCalls[0].headers['x-api-key'], KEY_A);
|
||||||
|
assert.equal(apiCalls[0].headers['anthropic-version'], '2023-06-01');
|
||||||
|
|
||||||
|
const stored = (await row(u.id)).claude_link_json;
|
||||||
|
assert.ok(!stored.includes(KEY_A), 'pas en clair en base');
|
||||||
|
const link = JSON.parse(stored);
|
||||||
|
assert.equal(link.mode, 'api_key');
|
||||||
|
assert.equal(link.last4, 'ZZ12');
|
||||||
|
assert.equal(decrypt(s.app.cfg.secretKey, link.secret_enc), KEY_A, 'chiffré avec SECRET_KEY, relisible');
|
||||||
|
assert.ok(!(await dump()).includes(KEY_A));
|
||||||
|
|
||||||
|
for (const path of ['/link', '/account', '/api/system']) {
|
||||||
|
const body = await (await u.get(path, { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.ok(!body.includes(KEY_A), `${path} ne renvoie jamais la clé`);
|
||||||
|
assert.ok(!body.includes('A'.repeat(20)), `${path} ne renvoie pas de morceau de la clé`);
|
||||||
|
}
|
||||||
|
const account = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(account, /sk-ant-…ZZ12/);
|
||||||
|
assert.ok(!logs.some((l) => l.includes(KEY_A)), 'aucune trace de la clé dans les journaux');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clé API : refus 401/403 et erreur réseau distincts, rien n\'est stocké', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
apiStatus = 401;
|
||||||
|
let r = await u.post('/link/api-key', { apiKey: KEY_B });
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
const refused = (await r.json()).error;
|
||||||
|
assert.match(refused, /refusée/);
|
||||||
|
apiStatus = 403;
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: KEY_B })).status, 400);
|
||||||
|
apiStatus = 200; apiThrows = true;
|
||||||
|
r = await u.post('/link/api-key', { apiKey: KEY_B });
|
||||||
|
apiThrows = false;
|
||||||
|
assert.equal(r.status, 502);
|
||||||
|
const network = (await r.json()).error;
|
||||||
|
assert.match(network, /réseau/);
|
||||||
|
assert.notEqual(network, refused);
|
||||||
|
assert.ok(!JSON.stringify(network).includes(KEY_B));
|
||||||
|
apiStatus = 500;
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: KEY_B })).status, 502);
|
||||||
|
apiStatus = 200;
|
||||||
|
assert.equal((await row(u.id)).claude_link_json, null, 'aucune liaison enregistrée');
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: 'pas-une-cle' })).status, 400);
|
||||||
|
assert.equal((await u.post('/link/api-key', {})).status, 400);
|
||||||
|
assert.ok(!logs.some((l) => l.includes(KEY_B)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validateApiKey : fetch injectable, 401/403 refusé, réseau distinct', async () => {
|
||||||
|
await assert.rejects(validateApiKey(KEY_A, async () => ({ status: 401, ok: false })), { status: 400 });
|
||||||
|
await assert.rejects(validateApiKey(KEY_A, async () => ({ status: 403, ok: false })), { status: 400 });
|
||||||
|
await assert.rejects(validateApiKey(KEY_A, async () => { throw new Error('boom'); }), { status: 502 });
|
||||||
|
await validateApiKey(KEY_A, async () => ({ status: 200, ok: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode abonnement : sans la case, 400 et rien n\'est stocké ni validé', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
let validated = 0;
|
||||||
|
s.app.validateToken = async () => { validated++; };
|
||||||
|
try {
|
||||||
|
for (const body of [{ token: TOKEN }, { token: TOKEN, accept: '' }, { token: TOKEN, accept: 'off' }, { token: TOKEN, accept: false }]) {
|
||||||
|
const r = await u.post('/link/subscription', body);
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
assert.match((await r.json()).error, new RegExp(CONSENT_CHECKBOX));
|
||||||
|
}
|
||||||
|
assert.equal(validated, 0, 'le jeton n\'est même pas vérifié sans consentement');
|
||||||
|
assert.equal((await row(u.id)).claude_link_json, null);
|
||||||
|
assert.equal(await getSetting(s.db, u.id, 'claude_cli_consent_json'), null);
|
||||||
|
assert.ok(!(await dump()).includes(TOKEN));
|
||||||
|
} finally { delete s.app.validateToken; }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode abonnement : case cochée, consentement horodaté avec la version du texte, jeton chiffré', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
s.app.validateToken = async () => {};
|
||||||
|
const before = now();
|
||||||
|
try {
|
||||||
|
const r = await u.post('/link/subscription', { token: TOKEN, accept: true });
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
} finally { delete s.app.validateToken; }
|
||||||
|
const stored = (await row(u.id)).claude_link_json;
|
||||||
|
assert.ok(!stored.includes(TOKEN));
|
||||||
|
const link = JSON.parse(stored);
|
||||||
|
assert.equal(link.mode, 'subscription_token');
|
||||||
|
assert.ok(link.consent.at >= before && link.consent.at <= now());
|
||||||
|
assert.equal(link.consent.version, CONSENT_VERSION);
|
||||||
|
assert.equal(decrypt(s.app.cfg.secretKey, link.secret_enc), TOKEN);
|
||||||
|
assert.ok(!(await dump()).includes(TOKEN));
|
||||||
|
const account = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.ok(!account.includes(TOKEN));
|
||||||
|
assert.match(account, new RegExp(CONSENT_VERSION.replace(/\./g, '\\.')));
|
||||||
|
assert.doesNotMatch(account, /sk-ant-…/, 'pas de 4 derniers caractères pour un jeton');
|
||||||
|
assert.ok(!logs.some((l) => l.includes(TOKEN)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode abonnement via le CLI simulé : jeton révoqué refusé, jeton valide accepté, jamais dans les erreurs', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const revoked = `${TOKEN}REVOKED`;
|
||||||
|
const r = await u.post('/link/subscription', { token: revoked, accept: true });
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
assert.ok(!JSON.stringify(await r.json()).includes(revoked));
|
||||||
|
assert.equal((await row(u.id)).claude_link_json, null);
|
||||||
|
assert.equal((await u.post('/link/subscription', { token: TOKEN, accept: 'on' })).status, 200);
|
||||||
|
assert.equal((await getLinkState(s.db, u.id)).mode, 'subscription_token');
|
||||||
|
// une clé API collée dans le champ jeton est signalée
|
||||||
|
assert.equal((await u.post('/link/subscription', { token: KEY_A, accept: true })).status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('formulaire HTML : l\'erreur revient sur /link, la page affiche la fenêtre d\'avertissement avec la case', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const r = await u.post('/link/subscription', { token: TOKEN }, { form: true });
|
||||||
|
assert.equal(r.status, 400, 'ce client demande du JSON');
|
||||||
|
const form = await fetch(`${s.base}/link/subscription`, {
|
||||||
|
method: 'POST', redirect: 'manual',
|
||||||
|
headers: { cookie: u.cookie, origin: 'https://ai.tony-averty.dev', 'content-type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: new URLSearchParams({ token: TOKEN }).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(form.status, 303);
|
||||||
|
assert.match(decodeURIComponent(form.headers.get('location')), /^\/link\?e=.*cocher/);
|
||||||
|
const page = (await (await u.get('/link', { headers: { accept: 'text/html' } })).text()).replace(/'/g, "'");
|
||||||
|
assert.match(page, /<dialog[^>]*id="consent-dialog"/);
|
||||||
|
assert.match(page, /contrevenir aux conditions d'utilisation d'Anthropic/);
|
||||||
|
assert.match(page, /suspension/);
|
||||||
|
assert.match(page, /ne peut en être tenu responsable/);
|
||||||
|
assert.match(page, /<input type="checkbox" name="accept" id="consent-accept" required>/);
|
||||||
|
assert.match(page, /id="consent-submit" disabled/);
|
||||||
|
assert.match(page, /claude setup-token/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('drapeau CLAUDE_CLI_MODE_ENABLED=false : mode abonnement masqué et refusé côté serveur', async () => {
|
||||||
|
const off = await startApp({ cfg: { claudeBin: 'inexistant', cliModeEnabled: false } });
|
||||||
|
try {
|
||||||
|
const u = await off.newUser({ admin: false });
|
||||||
|
let validated = 0;
|
||||||
|
off.app.validateToken = async () => { validated++; };
|
||||||
|
const r = await u.post('/link/subscription', { token: TOKEN, accept: true });
|
||||||
|
assert.equal(r.status, 403);
|
||||||
|
assert.equal(validated, 0);
|
||||||
|
assert.equal((await off.db.prepare('SELECT claude_link_json FROM users WHERE id = ?').get(u.id)).claude_link_json, null);
|
||||||
|
const page = await (await u.get('/link', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.doesNotMatch(page, /consent-dialog|setup-token|abonnement/);
|
||||||
|
assert.match(page, /Clé API Anthropic/);
|
||||||
|
// une liaison abonnement déjà en base ne permet plus de lancer de job
|
||||||
|
const linked = await off.newUser({ admin: false, link: { v: 1, mode: 'subscription_token', valid: true, secret_enc: 'x' } });
|
||||||
|
assert.match(await aiRefusal(off.db, linked.id, { cliModeEnabled: false }), /désactivé/);
|
||||||
|
assert.equal(await aiRefusal(off.db, linked.id, { cliModeEnabled: true }), null);
|
||||||
|
} finally { await off.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode « Claude du serveur » : réservé aux admins (liaison et exécution)', async () => {
|
||||||
|
const user = await s.newUser({ admin: false });
|
||||||
|
assert.equal((await user.post('/link/server', {})).status, 403);
|
||||||
|
assert.equal((await row(user.id)).claude_link_json, null);
|
||||||
|
assert.ok(!(await (await user.get('/link', { headers: { accept: 'text/html' } })).text()).includes('/link/server'));
|
||||||
|
const admin = await s.newUser({ admin: true, link: null });
|
||||||
|
assert.match(await (await admin.get('/link', { headers: { accept: 'text/html' } })).text(), /action="\/link\/server"/);
|
||||||
|
assert.equal((await admin.post('/link/server', {})).status, 200);
|
||||||
|
assert.equal((await getLinkState(s.db, admin.id)).mode, 'server');
|
||||||
|
assert.equal(await aiRefusal(s.db, admin.id), null);
|
||||||
|
// un admin rétrogradé (ADMIN_EMAILS) perd le mode serveur
|
||||||
|
await s.db.prepare('UPDATE users SET is_admin = 0 WHERE id = ?').run(admin.id);
|
||||||
|
assert.match(await aiRefusal(s.db, admin.id), /réservé aux administrateurs/);
|
||||||
|
await s.db.prepare('UPDATE users SET is_admin = 1 WHERE id = ?').run(admin.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onboarding bloquant : sans liaison, tout est refusé côté serveur sauf liaison, compte, déconnexion', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const html = { headers: { accept: 'text/html' } };
|
||||||
|
let r = await u.get('/', html);
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/link');
|
||||||
|
assert.equal((await u.get('/settings', html)).headers.get('location'), '/link');
|
||||||
|
|
||||||
|
const p = await project(u);
|
||||||
|
const blocked = [
|
||||||
|
['get', '/api/system'], ['get', `/api/projects/${p}/status`], ['get', `/api/projects/${p}/prospects`],
|
||||||
|
['get', `/api/projects/${p}/prospects.csv`], ['get', `/api/projects/${p}/recap`], ['get', `/api/projects/${p}/history`],
|
||||||
|
['post', '/api/projects', { name: 'x', gitUrl: 'https://git.test/u/x.git' }],
|
||||||
|
['post', `/api/projects/${p}/send`, { count: 1, confirm: true }],
|
||||||
|
['post', `/api/projects/${p}/target`, {}], ['post', `/api/projects/${p}/delete`, {}],
|
||||||
|
['post', `/api/projects/${p}/prospects/import`, { csv: 'a' }], ['post', '/api/report/send', {}],
|
||||||
|
['post', '/api/notify/test', {}], ['post', '/settings', {}], ['post', '/api/jobs/1/cancel', {}],
|
||||||
|
...AI_ROUTES.map((t) => ['post', `/api/projects/${p}/${t}`, {}]),
|
||||||
|
];
|
||||||
|
for (const [method, path, body] of blocked) {
|
||||||
|
r = method === 'get' ? await u.get(path) : await u.post(path, body ?? {});
|
||||||
|
assert.equal(r.status, 403, `${method} ${path}`);
|
||||||
|
const j = await r.json();
|
||||||
|
assert.equal(j.code, 'link_required');
|
||||||
|
assert.equal(j.error, LINK_REQUIRED_MESSAGE);
|
||||||
|
}
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM jobs WHERE user_id = ?').get(u.id)).n, 0);
|
||||||
|
|
||||||
|
// Ce qui reste accessible
|
||||||
|
for (const path of ['/link', '/account']) assert.equal((await u.get(path, html)).status, 200, path);
|
||||||
|
assert.equal((await u.post('/logout', {})).status, 303);
|
||||||
|
assert.equal((await s.client(u.cookie).get('/link', html)).status, 303, 'la session est détruite par la déconnexion');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onboarding : une fois relié, l\'application est accessible', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const html = { headers: { accept: 'text/html' } };
|
||||||
|
assert.equal((await u.get('/', html)).status, 303);
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal((await u.get('/', html)).status, 200);
|
||||||
|
assert.equal((await u.get('/api/system')).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('garde « compte relié » à chaque couche : route, enqueue, worker, wrapper', async () => {
|
||||||
|
const linked = await s.newUser({ admin: false });
|
||||||
|
await linked.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
const bare = await s.newUser({ admin: false });
|
||||||
|
const pBare = await project(bare);
|
||||||
|
const pLinked = await project(linked);
|
||||||
|
// enqueue
|
||||||
|
for (const type of AI_JOBS) {
|
||||||
|
await assert.rejects(enqueue(s.db, { userId: bare.id, projectId: pBare, type }), { status: 403, message: LINK_REQUIRED_MESSAGE }, type);
|
||||||
|
}
|
||||||
|
assert.equal((await enqueue(s.db, { userId: bare.id, projectId: pBare, type: 'send', params: { count: 1 } })).existing, false, 'un envoi n\'utilise pas Claude');
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(bare.id);
|
||||||
|
assert.equal((await enqueue(s.db, { userId: linked.id, projectId: pLinked, type: 'analyze' })).existing, false);
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(linked.id);
|
||||||
|
|
||||||
|
// worker : un job IA déjà en base d'un compte non relié ne s'exécute pas
|
||||||
|
const ran = [];
|
||||||
|
const w = new Worker(s.db, Object.fromEntries([...AI_JOBS, 'send'].map((t) => [t, async () => { ran.push(t); return {}; }])), { thermalMax: 999, log: { error() {} } });
|
||||||
|
for (const type of [...AI_JOBS, 'send']) await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, ?, 'queued', ?)").run(bare.id, pBare, type, now());
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
assert.deepEqual(ran, ['send']);
|
||||||
|
assert.equal(await jobRefusal(s.db, { user_id: bare.id, type: 'analyze' }), LINK_REQUIRED_MESSAGE);
|
||||||
|
assert.equal(await jobRefusal(s.db, { user_id: bare.id, type: 'send' }), null);
|
||||||
|
|
||||||
|
// wrapper d'exécution : dernier garde-fou, avant tout lancement de processus
|
||||||
|
const claude = makeClaude({ ...s.app, cfg: { ...s.app.cfg, claudeBin: '/inexistant/claude' } });
|
||||||
|
await assert.rejects(claude(bare.id, { prompt: 'x' }), { status: 403, message: LINK_REQUIRED_MESSAGE });
|
||||||
|
await assert.rejects(claude(999999, { prompt: 'x' }), { status: 403, message: 'Compte supprimé' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('liaison invalide ou compte suspendu : aucun job IA', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal(await aiRefusal(s.db, u.id), null);
|
||||||
|
await s.db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(u.id);
|
||||||
|
assert.equal(await aiRefusal(s.db, u.id), 'Compte suspendu');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Mon compte : Tester — succès, refus (liaison invalidée, onboarding de retour), réseau (liaison inchangée)', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
apiStatus = 200;
|
||||||
|
let j = await (await u.post('/link/test', {})).json();
|
||||||
|
assert.deepEqual({ ok: j.ok }, { ok: true });
|
||||||
|
const t1 = (await getLinkState(s.db, u.id)).lastTestAt;
|
||||||
|
assert.ok(t1);
|
||||||
|
|
||||||
|
apiThrows = true;
|
||||||
|
j = await (await u.post('/link/test', {})).json();
|
||||||
|
apiThrows = false;
|
||||||
|
assert.equal(j.ok, false);
|
||||||
|
assert.match(j.message, /réseau/);
|
||||||
|
assert.equal((await getLinkState(s.db, u.id)).valid, true, 'une panne réseau n\'invalide pas la liaison');
|
||||||
|
|
||||||
|
apiStatus = 401;
|
||||||
|
j = await (await u.post('/link/test', {})).json();
|
||||||
|
apiStatus = 200;
|
||||||
|
assert.equal(j.ok, false);
|
||||||
|
const state = await getLinkState(s.db, u.id);
|
||||||
|
assert.equal(state.valid, false);
|
||||||
|
assert.equal((await u.get('/', { headers: { accept: 'text/html' } })).headers.get('location'), '/link', 'liaison invalide : retour à l\'onboarding');
|
||||||
|
const account = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(account, /À revalider/);
|
||||||
|
// Re-relier avec une clé valide rétablit l'accès
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: KEY_B })).status, 200);
|
||||||
|
assert.equal((await getLinkState(s.db, u.id)).last4, 'QQ34');
|
||||||
|
assert.equal(await aiRefusal(s.db, u.id), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Mon compte : état de la liaison, boutons Tester, Changer de mode, Délier', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
const page = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(page, /Clé API Anthropic/);
|
||||||
|
assert.match(page, /Valide/);
|
||||||
|
assert.match(page, /action="\/link\/test"/);
|
||||||
|
assert.match(page, /href="\/link\?change=1"/);
|
||||||
|
assert.match(page, /action="\/link\/unlink"/);
|
||||||
|
// changer de mode : la page de liaison reste accessible et le nouvel accès remplace l'ancien
|
||||||
|
s.app.validateToken = async () => {};
|
||||||
|
try { assert.equal((await u.post('/link/subscription', { token: TOKEN, accept: true })).status, 200); } finally { delete s.app.validateToken; }
|
||||||
|
const link = JSON.parse((await row(u.id)).claude_link_json);
|
||||||
|
assert.equal(link.mode, 'subscription_token');
|
||||||
|
assert.equal(link.last4, undefined, 'plus de trace de la clé API');
|
||||||
|
assert.ok(!(await dump()).includes(KEY_A));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('délier : secret effacé, jobs IA en file annulés, autres jobs et autres comptes intacts, onboarding de retour', async () => {
|
||||||
|
const a = await s.newUser({ admin: false });
|
||||||
|
const b = await s.newUser({ admin: false });
|
||||||
|
await a.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
await b.post('/link/api-key', { apiKey: KEY_B });
|
||||||
|
const pa = await project(a), pb = await project(b);
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'analyze' });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'prospect' });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'send', params: { count: 1 } });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'analyze' });
|
||||||
|
await setSetting(s.db, a.id, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||||
|
|
||||||
|
const r = await a.post('/link/unlink', {});
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal((await r.json()).cancelled, 2);
|
||||||
|
assert.equal((await row(a.id)).claude_link_json, null);
|
||||||
|
assert.ok(!(await dump()).includes(KEY_A), 'le secret chiffré est supprimé');
|
||||||
|
const status = async (u, type) => (await s.db.prepare('SELECT status FROM jobs WHERE user_id = ? AND type = ?').get(u.id, type)).status;
|
||||||
|
assert.equal(await status(a, 'analyze'), 'cancelled');
|
||||||
|
assert.equal(await status(a, 'prospect'), 'cancelled');
|
||||||
|
assert.equal(await status(a, 'send'), 'queued', 'un envoi n\'utilise pas Claude');
|
||||||
|
assert.equal(await status(b, 'analyze'), 'queued', 'les jobs d\'un autre compte ne bougent pas');
|
||||||
|
assert.equal((await getLinkState(s.db, b.id)).mode, 'api_key');
|
||||||
|
assert.equal(await getSetting(s.db, a.id, 'claude_rate_limit_json'), null, 'le quota de l\'ancien accès ne subsiste pas');
|
||||||
|
assert.equal((await a.get('/', { headers: { accept: 'text/html' } })).headers.get('location'), '/link');
|
||||||
|
assert.equal(await aiRefusal(s.db, a.id), LINK_REQUIRED_MESSAGE);
|
||||||
|
// Mon compte reste accessible et propose de relier
|
||||||
|
assert.match(await (await a.get('/account', { headers: { accept: 'text/html' } })).text(), /Relier Claude/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('délier un job IA en cours : il est interrompu', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
const p = await project(u);
|
||||||
|
let aborted = false;
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run(); // jobs des tests précédents
|
||||||
|
const w = new Worker(s.db, {
|
||||||
|
analyze: (ctx) => new Promise((resolve) => { ctx.signal.addEventListener('abort', () => { aborted = true; resolve({}); }); }),
|
||||||
|
}, { thermalMax: 999, log: { error() {} }, isAiJob: (t) => AI_JOBS.has(t) });
|
||||||
|
s.app.worker = w;
|
||||||
|
try {
|
||||||
|
await enqueue(s.db, { userId: u.id, projectId: p, type: 'analyze' });
|
||||||
|
const tick = w.tick();
|
||||||
|
for (let i = 0; i < 50 && !w.currentJob; i++) await new Promise((r) => setTimeout(r, 20));
|
||||||
|
assert.equal((await u.post('/link/unlink', {})).status, 200);
|
||||||
|
await tick;
|
||||||
|
assert.equal(aborted, true);
|
||||||
|
assert.equal((await s.db.prepare('SELECT status FROM jobs WHERE user_id = ?').get(u.id)).status, 'cancelled');
|
||||||
|
} finally { delete s.app.worker; await w.stop(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('suppression du compte : liaison et trace de consentement effacées', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
s.app.validateToken = async () => {};
|
||||||
|
try { await u.post('/link/subscription', { token: TOKEN, accept: true }); } finally { delete s.app.validateToken; }
|
||||||
|
assert.ok(await getSetting(s.db, u.id, 'claude_cli_consent_json'));
|
||||||
|
const r = await u.post('/account/delete', { confirm: u.email });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(await row(u.id), undefined);
|
||||||
|
assert.equal(await getSetting(s.db, u.id, 'claude_cli_consent_json'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rien d\'un secret dans les journaux du serveur sur toute la durée de ces tests', () => {
|
||||||
|
for (const secret of [KEY_A, KEY_B, TOKEN]) assert.ok(!logs.some((l) => l.includes(secret)), secret.slice(0, 12));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('la température du serveur n\'est pas exposée aux comptes non admin', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal((await (await u.get('/api/system')).json()).temp, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('serveur complet (worker démarré par createApp) : job d\'un compte relié traité, job d\'un compte non relié refusé', async () => {
|
||||||
|
const full = await startApp({ worker: true, cfg: { claudeBin: makeClaudeBin(binDir, { name: 'claude-full' }) } });
|
||||||
|
try {
|
||||||
|
const mk = async (owner, url) => Number((await full.db.prepare('INSERT INTO projects(user_id, name, git_url, profile_json, target_json, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
|
.run(owner.id, 'P', url, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||||
|
const linked = await full.newUser({ admin: true });
|
||||||
|
const bare = await full.newUser({ admin: false });
|
||||||
|
const pl = await mk(linked, 'https://git.test/a.git');
|
||||||
|
const pb = await mk(bare, 'https://git.test/u.git');
|
||||||
|
const jl = (await enqueue(full.db, { userId: linked.id, projectId: pl, type: 'template' })).id;
|
||||||
|
const jb = Number((await full.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(bare.id, pb, now())).lastInsertRowid);
|
||||||
|
const status = async (id) => full.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(id);
|
||||||
|
for (let i = 0; i < 100 && ((await status(jl)).status === 'queued' || (await status(jb)).status === 'queued'); i++) await new Promise((r) => setTimeout(r, 100));
|
||||||
|
assert.equal((await status(jl)).status, 'done', (await status(jl)).error);
|
||||||
|
assert.deepEqual({ ...(await status(jb)) }, { status: 'error', error: LINK_REQUIRED_MESSAGE });
|
||||||
|
assert.equal((await full.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pb)).n, 0);
|
||||||
|
} finally { await full.close(); }
|
||||||
|
});
|
||||||
380
test/claude-run.test.js
Normal file
380
test/claude-run.test.js
Normal file
|
|
@ -0,0 +1,380 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import { now, getSetting, setSetting } from '../src/db.js';
|
||||||
|
import { encrypt } from '../src/crypto.js';
|
||||||
|
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
||||||
|
import { quotaState, budgetState, AI_JOBS, isQuotaSensitive } from '../src/services/budget.js';
|
||||||
|
import { makeClaude, makeHandlers } from '../src/handlers.js';
|
||||||
|
import { extractJson } from '../src/services/claude.js';
|
||||||
|
import { buildBwrapArgs, buildChildEnv, prepareLaunch, isInside, SANDBOX_HOME } from '../src/services/sandbox.js';
|
||||||
|
import { validateGitUrl, syncRepo, gitEnv, cloneArgs, fetchArgs, GIT_HARDENING, dirSize } from '../src/services/git.js';
|
||||||
|
import { loadConfig } from '../src/config.js';
|
||||||
|
import { userRepoRoot } from '../src/users.js';
|
||||||
|
import { startApp } from './helpers/server.js';
|
||||||
|
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||||
|
|
||||||
|
// Exécution isolée : le secret vient toujours du user_id du job, environnement du processus enfant assaini,
|
||||||
|
// argv bubblewrap, clones git durcis, quota et budget par utilisateur.
|
||||||
|
// Limite connue : bwrap n'est pas exécutable sur ce poste (Windows) ; sa ligne de commande est testée, pas son effet.
|
||||||
|
let s, tmp;
|
||||||
|
const KEY_A = `sk-ant-api03-${'A'.repeat(40)}ZZ12`;
|
||||||
|
const KEY_B = `sk-ant-api03-${'B'.repeat(40)}QQ34`;
|
||||||
|
const TOK_A = `sk-ant-oat01-HOT${'a'.repeat(40)}`;
|
||||||
|
const TOK_B = `sk-ant-oat01-${'b'.repeat(40)}`;
|
||||||
|
|
||||||
|
const apiKeyLink = (key) => ({ v: 1, mode: 'api_key', valid: true, last4: key.slice(-4), secret_enc: encrypt(s.app.cfg.secretKey, key) });
|
||||||
|
const tokenLink = (tok) => ({ v: 1, mode: 'subscription_token', valid: true, secret_enc: encrypt(s.app.cfg.secretKey, tok) });
|
||||||
|
const project = async (u, extra = {}) => Number((await s.db.prepare(`INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at)
|
||||||
|
VALUES(?, 'P', ?, ?, ?, 1, ?)`).run(u.id, `https://git.test/u${u.id}/p${Math.random()}.git`, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }),
|
||||||
|
JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||||
|
const ctxOf = (job) => ({ job, params: {}, signal: new AbortController().signal, progress: async () => {}, cancelled: async () => false, usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 } });
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
tmp = mkdtempSync(join(tmpdir(), 'aitools-run-'));
|
||||||
|
s = await startApp({ cfg: { claudeBin: resolve('test/fixtures/fake-claude.js') } });
|
||||||
|
// Pas de vrai clone : le dossier est simplement créé (et vérifié par le bac à sable via allowedRoot)
|
||||||
|
s.app.syncRepo = async (url, dir) => { mkdirSync(dir, { recursive: true }); return 'deadbeef'; };
|
||||||
|
});
|
||||||
|
after(async () => { await s.close(); rmSync(tmp, { recursive: true, force: true }); });
|
||||||
|
|
||||||
|
// ---------- Le secret vient du user_id du job ----------
|
||||||
|
|
||||||
|
test('un utilisateur ne lance jamais un job avec le secret d\'un autre (secret relu depuis le user_id du job)', async () => {
|
||||||
|
const log = join(tmp, 'keys.log');
|
||||||
|
s.app.cfg.claudeBin = makeClaudeBin(tmp, { logVars: ['ANTHROPIC_API_KEY'], logFile: log });
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) });
|
||||||
|
const pa = await project(a), pb = await project(b);
|
||||||
|
const w = new Worker(s.db, makeHandlers(s.app), { thermalMax: 999, log: { error() {} } });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'template' });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'template' });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
assert.deepEqual(readFileSync(log, 'utf8').trim().split('\n'), [KEY_A, KEY_B], 'chaque job a tourné avec la clé de SON utilisateur');
|
||||||
|
assert.equal((await latestJobs(s.db, pa)).template.status, 'done');
|
||||||
|
assert.equal((await latestJobs(s.db, pb)).template.status, 'done');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('id de projet ou de job manipulé : le job d\'A ne touche jamais au projet ni au secret de B', async () => {
|
||||||
|
s.app.cfg.claudeBin = '/inexistant/claude'; // si quoi que ce soit se lançait, l'erreur serait un ENOENT
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) });
|
||||||
|
const pb = await project(b);
|
||||||
|
const handlers = makeHandlers(s.app);
|
||||||
|
for (const type of ['analyze', 'template', 'followup_template', 'prospect', 'evolution']) {
|
||||||
|
await assert.rejects(handlers[type](ctxOf({ id: 1, user_id: a.id, project_id: pb, type })), { status: 404 }, type);
|
||||||
|
}
|
||||||
|
// Même chose via la file : un job inséré à la main avec le projet de B échoue sans exécution
|
||||||
|
await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(a.id, pb, now());
|
||||||
|
const w = new Worker(s.db, makeHandlers(s.app), { thermalMax: 999, log: { error() {} } });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
const row = await s.db.prepare("SELECT status, error FROM jobs WHERE user_id = ? AND project_id = ?").get(a.id, pb);
|
||||||
|
assert.equal(row.status, 'error');
|
||||||
|
assert.match(row.error, /Projet introuvable/);
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pb)).n, 0);
|
||||||
|
await assert.rejects(enqueue(s.db, { userId: a.id, projectId: pb, type: 'template' }), { status: 404 });
|
||||||
|
// Le wrapper n'accepte pas non plus un répertoire hors du dossier de l'utilisateur
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const claude = makeClaude(s.app);
|
||||||
|
await assert.rejects(claude(a.id, { prompt: 'x', cwd: join(userRepoRoot(s.app.cfg, b.id), String(pb)) }), /hors du dossier/);
|
||||||
|
await assert.rejects(claude(a.id, { prompt: 'x', cwd: s.app.cfg.dataDir }), /hors du dossier/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Environnement du processus enfant ----------
|
||||||
|
|
||||||
|
test('environnement enfant : liste blanche stricte, secret de l\'utilisateur concerné uniquement', () => {
|
||||||
|
const parent = {
|
||||||
|
PATH: '/usr/bin', LANG: 'fr_FR.UTF-8', SECRET_KEY: 'k'.repeat(64), DB_PASSWORD: 'dbpass', DB_HOST: 'h', GOOGLE_CLIENT_SECRET: 'g', APPLE_PRIVATE_KEY: 'p',
|
||||||
|
ANTHROPIC_API_KEY: 'sk-ant-du-serveur', CLAUDE_CODE_OAUTH_TOKEN: 'jeton-du-serveur', HOME: '/home/svc', NODE_ENV: 'production', ADMIN_EMAILS: 'a@b.fr',
|
||||||
|
};
|
||||||
|
const sb = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/home/svc' };
|
||||||
|
const l = prepareLaunch({ bin: 'claude', args: ['-p', 'x'], sandbox: sb, secretEnv: { ANTHROPIC_API_KEY: KEY_A } },
|
||||||
|
{ parentEnv: parent, hasBwrap: () => true, resolveBin: () => '/usr/local/bin/claude' });
|
||||||
|
const allowed = new Set(['PATH', 'LANG', 'HOME', 'ANTHROPIC_API_KEY', ...(process.platform === 'win32' ? ['SystemRoot', 'PATHEXT', 'TEMP', 'TMP', 'COMSPEC'] : [])]);
|
||||||
|
for (const k of Object.keys(l.env)) assert.ok(allowed.has(k), `variable inattendue : ${k}`);
|
||||||
|
assert.equal(l.env.ANTHROPIC_API_KEY, KEY_A, 'la clé de l\'utilisateur, pas celle du serveur');
|
||||||
|
assert.equal(l.env.HOME, SANDBOX_HOME, 'répertoire personnel jetable du bac à sable');
|
||||||
|
assert.equal(l.env.PATH, '/usr/bin');
|
||||||
|
assert.ok(!JSON.stringify(l.env).match(/dbpass|SECRET_KEY|serveur|a@b\.fr/));
|
||||||
|
// Sans secret (mode serveur) : aucune des variables d'identification, même héritées du serveur
|
||||||
|
const none = buildChildEnv(parent, { home: '/h' });
|
||||||
|
assert.equal(none.ANTHROPIC_API_KEY, undefined);
|
||||||
|
assert.equal(none.CLAUDE_CODE_OAUTH_TOKEN, undefined);
|
||||||
|
// Un nom de variable arbitraire n'est pas accepté comme « secret »
|
||||||
|
assert.throws(() => buildChildEnv(parent, { home: '/h', secretEnv: { SECRET_KEY: 'x' } }), /non autorisée/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('environnement enfant (processus réel) : aucun secret du serveur, la clé de l\'utilisateur seulement', async () => {
|
||||||
|
const polluted = { SECRET_KEY: 'SERVEUR-SECRET-KEY', DB_PASSWORD: 'SERVEUR-DB', GOOGLE_CLIENT_SECRET: 'SERVEUR-GOOGLE', APPLE_PRIVATE_KEY: 'SERVEUR-APPLE',
|
||||||
|
ANTHROPIC_API_KEY: 'SERVEUR-ANTHROPIC', CLAUDE_CODE_OAUTH_TOKEN: 'SERVEUR-OAUTH' };
|
||||||
|
const keep = {};
|
||||||
|
for (const k of Object.keys(polluted)) { keep[k] = process.env[k]; process.env[k] = polluted[k]; }
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
try {
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const r = await makeClaude(s.app)(a.id, { prompt: 'ENVDUMP', maxTurns: 1, tools: [] });
|
||||||
|
const { env } = extractJson(r.text);
|
||||||
|
// Présente dans l'environnement du CLI, mais masquée dans ce qu'il renvoie (le masquage est lui aussi vérifié)
|
||||||
|
assert.equal(env.ANTHROPIC_API_KEY, '***');
|
||||||
|
for (const k of Object.keys(polluted)) if (k !== 'ANTHROPIC_API_KEY') assert.equal(env[k], undefined, k);
|
||||||
|
assert.ok(!JSON.stringify(env).includes('SERVEUR-'));
|
||||||
|
// HOME jetable : pas celui du serveur
|
||||||
|
assert.notEqual(env.HOME, process.env.HOME);
|
||||||
|
// L'abonnement : seul CLAUDE_CODE_OAUTH_TOKEN, jamais ANTHROPIC_API_KEY
|
||||||
|
const t = await s.newUser({ admin: false, link: tokenLink(TOK_B) });
|
||||||
|
const r2 = await makeClaude(s.app)(t.id, { prompt: 'ENVDUMP', maxTurns: 1, tools: [] });
|
||||||
|
const env2 = extractJson(r2.text).env;
|
||||||
|
assert.equal(env2.CLAUDE_CODE_OAUTH_TOKEN, '***');
|
||||||
|
assert.equal(env2.ANTHROPIC_API_KEY, undefined);
|
||||||
|
} finally { for (const k of Object.keys(polluted)) { if (keep[k] === undefined) delete process.env[k]; else process.env[k] = keep[k]; } }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('le secret n\'apparaît ni dans les erreurs du CLI, ni dans le job en erreur', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
let err;
|
||||||
|
try { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } catch (e) { err = e; }
|
||||||
|
assert.ok(err, 'le CLI a échoué');
|
||||||
|
assert.match(err.message, /\*\*\*/);
|
||||||
|
assert.ok(!err.message.includes(KEY_A));
|
||||||
|
const p = await project(a);
|
||||||
|
const w = new Worker(s.db, { template: async () => { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } }, { thermalMax: 999, log: { error() {} } });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: p, type: 'template' });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
const row = await s.db.prepare('SELECT status, error FROM jobs WHERE project_id = ?').get(p);
|
||||||
|
assert.equal(row.status, 'error');
|
||||||
|
assert.ok(!row.error.includes(KEY_A));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- bubblewrap ----------
|
||||||
|
|
||||||
|
const pairIdx = (args, flag, ...vals) => args.findIndex((x, i) => x === flag && vals.every((v, j) => args[i + 1 + j] === v));
|
||||||
|
|
||||||
|
test('bwrap : ligne de commande — racine en lecture seule, tmpfs, un seul dossier utilisateur, espaces de noms', () => {
|
||||||
|
const work = resolve('/srv/aitools/repos/7/12');
|
||||||
|
const a = buildBwrapArgs({ workDir: work, command: ['/opt/claude/claude', '-p', 'x'], roBinds: ['/opt/claude'] });
|
||||||
|
for (const f of ['--die-with-parent', '--unshare-pid', '--unshare-ipc', '--unshare-uts', '--new-session']) assert.ok(a.includes(f), f);
|
||||||
|
assert.ok(!a.includes('--unshare-net') && !a.includes('--unshare-all'), 'le réseau est conservé');
|
||||||
|
assert.ok(pairIdx(a, '--tmpfs', '/tmp') >= 0, '/tmp vide');
|
||||||
|
assert.ok(pairIdx(a, '--tmpfs', SANDBOX_HOME) >= 0, 'HOME vide');
|
||||||
|
assert.ok(pairIdx(a, '--ro-bind', '/usr', '/usr') >= 0);
|
||||||
|
assert.ok(pairIdx(a, '--ro-bind', work, work) >= 0, 'clone de l\'utilisateur, en lecture seule');
|
||||||
|
assert.ok(pairIdx(a, '--ro-bind', '/opt/claude', '/opt/claude') >= 0);
|
||||||
|
assert.ok(pairIdx(a, '--chdir', work) >= 0);
|
||||||
|
assert.deepEqual(a.slice(a.indexOf('--') + 1), ['/opt/claude/claude', '-p', 'x']);
|
||||||
|
// Rien d'autre n'est monté : ni la racine entière, ni /home, /root, /var, ni la config Claude du serveur
|
||||||
|
const mounts = a.flatMap((x, i) => (['--bind', '--ro-bind', '--bind-try', '--ro-bind-try'].includes(x) ? [a[i + 1]] : []));
|
||||||
|
assert.deepEqual(mounts.sort(), ['/bin', '/etc', '/lib', '/lib64', '/opt/claude', '/run/systemd/resolve', '/sbin', '/usr', work].sort());
|
||||||
|
assert.ok(!a.includes('--bind') && !a.includes('--bind-try'), 'aucun montage en écriture hors mode serveur');
|
||||||
|
assert.ok(!a.join(' ').includes('.claude'));
|
||||||
|
assert.ok(!mounts.includes('/'));
|
||||||
|
// Sans projet : seul le HOME vide
|
||||||
|
const bare = buildBwrapArgs({ command: ['claude'] });
|
||||||
|
assert.ok(pairIdx(bare, '--chdir', SANDBOX_HOME) >= 0);
|
||||||
|
assert.throws(() => buildBwrapArgs({ workDir: 'relatif', command: ['x'] }), /absolu/);
|
||||||
|
assert.throws(() => buildBwrapArgs({ command: [] }), /vide/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bwrap : la configuration du CLI du serveur n\'est montée que pour le mode serveur', () => {
|
||||||
|
const sb = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/home/svc' };
|
||||||
|
const deps = { parentEnv: { PATH: '/usr/bin' }, hasBwrap: () => true, resolveBin: () => '/usr/bin/claude' };
|
||||||
|
const work = resolve('/srv/aitools/repos/1/1');
|
||||||
|
const user = prepareLaunch({ bin: 'claude', args: ['-p', 'x'], cwd: work, allowedRoot: resolve('/srv/aitools/repos/1'), sandbox: sb, secretEnv: { ANTHROPIC_API_KEY: KEY_A } }, deps);
|
||||||
|
assert.ok(!user.args.join(' ').includes('.claude'));
|
||||||
|
assert.ok(!user.args.some((x) => x === '/home/svc' || x.startsWith('/home/svc')));
|
||||||
|
const server = prepareLaunch({ bin: 'claude', args: ['-p', 'x'], cwd: work, allowedRoot: resolve('/srv/aitools/repos/1'), sandbox: sb, serverConfig: true }, deps);
|
||||||
|
assert.ok(pairIdx(server.args, '--bind-try', join('/home/svc', '.claude'), `${SANDBOX_HOME}/.claude`) >= 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bwrap : prepareLaunch — le secret n\'est jamais dans argv (visible dans ps), seulement dans l\'environnement', () => {
|
||||||
|
const sb = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/home/svc' };
|
||||||
|
const l = prepareLaunch({ bin: 'claude', args: ['-p', 'bonjour'], cwd: resolve('/srv/d/repos/3/9'), allowedRoot: resolve('/srv/d/repos/3'), sandbox: sb,
|
||||||
|
secretEnv: { CLAUDE_CODE_OAUTH_TOKEN: TOK_A } }, { parentEnv: { PATH: '/usr/bin' }, hasBwrap: () => true, resolveBin: () => '/usr/local/bin/claude-x' });
|
||||||
|
assert.equal(l.command, 'nice');
|
||||||
|
assert.deepEqual(l.args.slice(0, 4), ['-n', '10', 'bwrap', '--die-with-parent']);
|
||||||
|
assert.ok(!l.args.join(' ').includes(TOK_A));
|
||||||
|
assert.equal(l.env.CLAUDE_CODE_OAUTH_TOKEN, TOK_A);
|
||||||
|
assert.ok(l.args.includes('/usr/local/bin/claude-x'), 'chemin réel de l\'exécutable (lien symbolique résolu)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bwrap : répertoire hors du dossier de l\'utilisateur, bwrap absent, production sans bac à sable — exécution refusée', () => {
|
||||||
|
const base = { bin: 'claude', args: ['-p', 'x'] };
|
||||||
|
const ok = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/h' };
|
||||||
|
const deps = { parentEnv: { PATH: '/usr/bin' }, hasBwrap: () => true, resolveBin: () => '/usr/bin/claude' };
|
||||||
|
const root = resolve('/srv/d/repos/3');
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok, cwd: resolve('/srv/d/repos/4/1'), allowedRoot: root }, deps), /hors du dossier/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok, cwd: resolve('/srv/d/repos/3/../4/1'), allowedRoot: root }, deps), /hors du dossier/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok, cwd: resolve('/srv/d/repos/33'), allowedRoot: root }, deps), /hors du dossier/, 'préfixe de nom ≠ sous-dossier');
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok }, { ...deps, hasBwrap: () => false }), /bwrap/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: { ...ok, enabled: false } }, deps), /obligatoire en production/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok }, { ...deps, resolveBin: () => null }), /introuvable/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base }, deps), /bac à sable/);
|
||||||
|
// Développement + bwrap activé mais absent : on refuse plutôt que d'exécuter sans isolation
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: { ...ok, production: false } }, { ...deps, hasBwrap: () => false }), /bwrap/);
|
||||||
|
// Développement avec SANDBOX=off : exécution directe, HOME jetable nettoyé
|
||||||
|
const dev = prepareLaunch({ ...base, sandbox: { enabled: false, production: false, serverHome: '/h' } }, deps);
|
||||||
|
assert.equal(dev.sandboxed, false);
|
||||||
|
assert.notEqual(dev.env.HOME, '/h');
|
||||||
|
dev.cleanup();
|
||||||
|
assert.ok(isInside(root, join(root, '5')) && !isInside(root, resolve('/srv/d/repos')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('production : le wrapper refuse de lancer un job sans bwrap (même avec SANDBOX=off)', async () => {
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const real = s.app.cfg.sandbox;
|
||||||
|
try {
|
||||||
|
s.app.cfg.sandbox = { enabled: true, production: true, bwrapBin: join(tmp, 'bwrap-inexistant'), roBinds: [], serverHome: tmp };
|
||||||
|
await assert.rejects(makeClaude(s.app)(a.id, { prompt: 'x' }), /bwrap/);
|
||||||
|
s.app.cfg.sandbox = { enabled: false, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: tmp };
|
||||||
|
await assert.rejects(makeClaude(s.app)(a.id, { prompt: 'x' }), /obligatoire en production/);
|
||||||
|
} finally { s.app.cfg.sandbox = real; }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('configuration : NODE_ENV=production impose le bac à sable, SANDBOX=off seulement en développement, drapeau du mode abonnement', () => {
|
||||||
|
const keep = { ...process.env };
|
||||||
|
Object.assign(process.env, { SECRET_KEY: 'a'.repeat(64), APP_URL: 'https://x.test', GOOGLE_CLIENT_ID: 'i', GOOGLE_CLIENT_SECRET: 's', DB_HOST: 'h', DB_USER: 'u', DB_PASSWORD: 'p', DB_NAME: 'n' });
|
||||||
|
try {
|
||||||
|
const cfg = (env) => { for (const k of ['NODE_ENV', 'SANDBOX', 'CLAUDE_CLI_MODE_ENABLED']) delete process.env[k]; Object.assign(process.env, env); return loadConfig(); };
|
||||||
|
assert.equal(cfg({}).cliModeEnabled, true, 'activé par défaut');
|
||||||
|
for (const v of ['false', 'FALSE', '0', 'off', 'no']) assert.equal(cfg({ CLAUDE_CLI_MODE_ENABLED: v }).cliModeEnabled, false, v);
|
||||||
|
assert.equal(cfg({ CLAUDE_CLI_MODE_ENABLED: 'true' }).cliModeEnabled, true);
|
||||||
|
assert.deepEqual([cfg({}).sandbox.enabled, cfg({}).sandbox.production], [true, false]);
|
||||||
|
assert.equal(cfg({ SANDBOX: 'off' }).sandbox.enabled, false, 'développement : désactivable');
|
||||||
|
const prod = cfg({ NODE_ENV: 'production', SANDBOX: 'off' }).sandbox;
|
||||||
|
assert.deepEqual([prod.enabled, prod.production, prod.offIgnored], [true, true, true]);
|
||||||
|
assert.deepEqual(cfg({ SANDBOX_RO_BINDS: '/opt/node, /opt/claude' }).sandbox.roBinds, ['/opt/node', '/opt/claude']);
|
||||||
|
} finally { for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; Object.assign(process.env, keep); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Clones git ----------
|
||||||
|
|
||||||
|
test('git : https uniquement — file://, ext::, ssh, git://, http:// refusés avant tout lancement', async () => {
|
||||||
|
const dir = join(tmp, 'clone-refuse');
|
||||||
|
for (const url of ['file:///etc/passwd', 'ext::sh -c touch% /tmp/pwn', 'ssh://git@h.test/a/b.git', 'git://h.test/a/b.git', 'http://h.test/a/b.git', 'git@h.test:a/b.git', '/srv/local/repo', 'https://u:p@h.test/a/b.git']) {
|
||||||
|
assert.throws(() => validateGitUrl(url), /URL Git invalide|https|identifiants/, url);
|
||||||
|
await assert.rejects(syncRepo(url, dir, null), /Git :/, url);
|
||||||
|
}
|
||||||
|
assert.equal(validateGitUrl('https://git.tony-averty.dev/Tony/A.git', 'git.tony-averty.dev'), 'https://git.tony-averty.dev/Tony/A.git');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('git : environnement assaini, GIT_ALLOW_PROTOCOL=https, pas de hooks ni de sous-modules, token hors argv', () => {
|
||||||
|
const keep = process.env.SECRET_KEY;
|
||||||
|
process.env.SECRET_KEY = 'SERVEUR-SECRET';
|
||||||
|
try {
|
||||||
|
const env = gitEnv('tok-forgejo');
|
||||||
|
assert.equal(env.GIT_ALLOW_PROTOCOL, 'https');
|
||||||
|
assert.equal(env.GIT_TERMINAL_PROMPT, '0');
|
||||||
|
assert.equal(env.GIT_CONFIG_NOSYSTEM, '1');
|
||||||
|
assert.equal(env.GIT_CONFIG_VALUE_0, 'Authorization: token tok-forgejo');
|
||||||
|
assert.equal(env.SECRET_KEY, undefined);
|
||||||
|
assert.ok(!Object.keys(env).some((k) => /^(DB_|GOOGLE_|APPLE_)/.test(k)));
|
||||||
|
assert.equal(gitEnv(null).GIT_CONFIG_COUNT, undefined);
|
||||||
|
} finally { if (keep === undefined) delete process.env.SECRET_KEY; else process.env.SECRET_KEY = keep; }
|
||||||
|
const joined = GIT_HARDENING.join(' ');
|
||||||
|
assert.match(joined, /protocol\.allow=never/);
|
||||||
|
assert.match(joined, /protocol\.https\.allow=always/);
|
||||||
|
assert.match(joined, /core\.hooksPath=/);
|
||||||
|
assert.match(joined, /submodule\.recurse=false/);
|
||||||
|
for (const args of [cloneArgs('https://h.test/a/b.git', '/d'), fetchArgs()]) {
|
||||||
|
assert.ok(args.includes('--no-recurse-submodules'));
|
||||||
|
assert.ok(args.includes('--depth'));
|
||||||
|
assert.ok(!args.join(' ').includes('tok-forgejo'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('git réel : avec ce durcissement, un dépôt local (file) ne peut pas être cloné', () => {
|
||||||
|
const src = join(tmp, 'src-repo');
|
||||||
|
execFileSync('git', ['init', '-q', '-b', 'main', src]);
|
||||||
|
writeFileSync(join(src, 'a.txt'), 'x');
|
||||||
|
execFileSync('git', ['-C', src, 'add', '.']);
|
||||||
|
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'c']);
|
||||||
|
assert.throws(() => execFileSync('git', cloneArgs(`file://${src}`, join(tmp, 'dest')), { env: gitEnv(null), stdio: 'pipe' }), (e) => /not allowed|protocol/i.test(String(e.stderr)));
|
||||||
|
assert.throws(() => execFileSync('git', cloneArgs(src, join(tmp, 'dest2')), { env: gitEnv(null), stdio: 'pipe' }), (e) => /not allowed|protocol/i.test(String(e.stderr)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('git : taille d\'un dossier mesurée avec coupe-circuit', () => {
|
||||||
|
const d = join(tmp, 'sz');
|
||||||
|
mkdirSync(join(d, 'sub'), { recursive: true });
|
||||||
|
writeFileSync(join(d, 'a'), Buffer.alloc(1000));
|
||||||
|
writeFileSync(join(d, 'sub', 'b'), Buffer.alloc(2000));
|
||||||
|
assert.equal(dirSize(d), 3000);
|
||||||
|
assert.ok(dirSize(d, 500) > 500, 'dépasse la limite : mesure interrompue');
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Quota, budget, notifications par utilisateur ----------
|
||||||
|
|
||||||
|
test('quota : chaque utilisateur voit le sien, celui du CLI de A n\'apparaît jamais chez B', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const a = await s.newUser({ admin: false, link: tokenLink(TOK_A) }); // jeton « HOT » : le faux CLI remonte 90 % sur la session
|
||||||
|
const b = await s.newUser({ admin: false, link: tokenLink(TOK_B) }); // 33 %
|
||||||
|
const pa = await project(a), pb = await project(b);
|
||||||
|
const w = new Worker(s.db, makeHandlers(s.app), {
|
||||||
|
thermalMax: 999, log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t), budget: (uid) => budgetState(s.db, uid),
|
||||||
|
});
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'template' });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'template' });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
|
||||||
|
const rl = async (u) => (await (await u.get('/api/system')).json()).claudeRateLimit;
|
||||||
|
assert.equal((await rl(a)).fiveHour.utilization, 0.9);
|
||||||
|
assert.equal((await rl(b)).fiveHour.utilization, 0.33);
|
||||||
|
assert.equal((await quotaState(s.db, a.id)).blocked, true);
|
||||||
|
assert.equal((await quotaState(s.db, b.id)).blocked, false);
|
||||||
|
|
||||||
|
// A est serré : son analyse attend ; celle de B part, et le template de A (non sensible) aussi
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run();
|
||||||
|
const done = [];
|
||||||
|
const w2 = new Worker(s.db, { analyze: async (ctx) => { done.push(ctx.job.user_id); return {}; } }, {
|
||||||
|
thermalMax: 999, log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t),
|
||||||
|
});
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'analyze' });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'analyze' });
|
||||||
|
while (await w2.tick()) { /* vide la file */ }
|
||||||
|
assert.deepEqual(done, [b.id], 'seul le job de B a tourné');
|
||||||
|
assert.equal((await s.db.prepare("SELECT status FROM jobs WHERE user_id = ? AND type = 'analyze'").get(a.id)).status, 'queued');
|
||||||
|
assert.match(JSON.parse((await s.db.prepare("SELECT progress_json FROM jobs WHERE user_id = ? AND type = 'analyze'").get(a.id)).progress_json).message, /En attente/);
|
||||||
|
await w2.idle();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('budget et usage IA : par utilisateur', async () => {
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) });
|
||||||
|
await setSetting(s.db, a.id, 'budget_day_usd', '1');
|
||||||
|
await s.db.prepare("INSERT INTO jobs(user_id, type, status, created_at, finished_at, cost_usd) VALUES(?, 'analyze', 'done', ?, ?, 2.5)").run(a.id, now(), now());
|
||||||
|
assert.equal((await budgetState(s.db, a.id)).blocked, true);
|
||||||
|
assert.equal((await budgetState(s.db, b.id)).blocked, false);
|
||||||
|
assert.equal((await (await b.get('/api/system')).json()).usage.day.cost, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode clé API : pas de barre de quota d\'abonnement, rien n\'est enregistré', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const r = await makeClaude(s.app)(a.id, { prompt: 'bonjour', maxTurns: 1, tools: [] });
|
||||||
|
assert.ok(r.rateLimit, 'le faux CLI remonte bien un quota');
|
||||||
|
assert.equal(await getSetting(s.db, a.id, 'claude_rate_limit_json'), null, 'non enregistré en mode clé API');
|
||||||
|
// Même une valeur résiduelle n'est pas exposée
|
||||||
|
await setSetting(s.db, a.id, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.99 } }));
|
||||||
|
const sys = await (await a.get('/api/system')).json();
|
||||||
|
assert.equal(sys.claudeRateLimit, null);
|
||||||
|
assert.equal(sys.linkMode, 'api_key');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('alertes de quota : envoyées au webhook de l\'utilisateur concerné seulement', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const sent = [];
|
||||||
|
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
||||||
|
const a = await s.newUser({ admin: false, link: tokenLink(TOK_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: tokenLink(TOK_A) });
|
||||||
|
const hookA = 'https://discord.com/api/webhooks/123456789012345678/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
|
||||||
|
const hookB = 'https://discord.com/api/webhooks/123456789012345678/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
|
||||||
|
await setSetting(s.db, a.id, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hookA));
|
||||||
|
await setSetting(s.db, b.id, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hookB));
|
||||||
|
await makeClaude(s.app)(a.id, { prompt: 'bonjour', maxTurns: 1, tools: [] });
|
||||||
|
assert.equal(sent.length, 1);
|
||||||
|
assert.equal(sent[0].url, hookA);
|
||||||
|
assert.equal(await getSetting(s.db, b.id, 'claude_quota_notified_json'), null, 'B n\'a rien reçu ni mémorisé');
|
||||||
|
delete s.app.fetch;
|
||||||
|
});
|
||||||
12
test/fixtures/fake-claude.js
vendored
12
test/fixtures/fake-claude.js
vendored
|
|
@ -4,8 +4,16 @@ const prompt = process.argv[process.argv.indexOf('-p') + 1] || '';
|
||||||
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
|
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
|
||||||
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
|
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
|
||||||
if (prompt.includes('CRASH')) process.exit(3);
|
if (prompt.includes('CRASH')) process.exit(3);
|
||||||
|
// Le secret de l'utilisateur fuit dans stderr : l'application ne doit jamais le répercuter
|
||||||
|
if (prompt.includes('LEAK')) { process.stderr.write('echec avec ' + (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || '') + ' fin'); process.exit(3); }
|
||||||
|
// Jeton d'abonnement refusé par Claude
|
||||||
|
if ((process.env.CLAUDE_CODE_OAUTH_TOKEN || '').includes('REVOKED')) {
|
||||||
|
out({ type: 'result', subtype: 'success', is_error: true, result: 'Invalid bearer token · Please run /login', total_cost_usd: 0, num_turns: 0, usage: {} });
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' };
|
const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' };
|
||||||
const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```']
|
const lines = prompt.includes('ENVDUMP') ? ['```json\n' + JSON.stringify({ env: process.env, cwd: process.cwd() }) + '\n```']
|
||||||
|
: prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```']
|
||||||
: prompt.includes('mail de RELANCE') ? ['{"body":"Petite relance : toujours partant, {{entreprise}} ?"}']
|
: prompt.includes('mail de RELANCE') ? ['{"body":"Petite relance : toujours partant, {{entreprise}} ?"}']
|
||||||
: prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}']
|
: prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}']
|
||||||
: prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique']
|
: prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique']
|
||||||
|
|
@ -18,7 +26,7 @@ for (const t of lines) out({ type: 'assistant', message: { content: [{ type: 'te
|
||||||
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel.
|
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel.
|
||||||
// Surchargeable par les tests qui veulent simuler un quota serré (FAKE_FIVE_HOUR / FAKE_SEVEN_DAY).
|
// Surchargeable par les tests qui veulent simuler un quota serré (FAKE_FIVE_HOUR / FAKE_SEVEN_DAY).
|
||||||
out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: {
|
out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: {
|
||||||
five_hour: { utilization: Number(process.env.FAKE_FIVE_HOUR ?? 0.33), resetsAt: 1_700_000_000 },
|
five_hour: { utilization: Number(process.env.FAKE_FIVE_HOUR ?? ((process.env.CLAUDE_CODE_OAUTH_TOKEN || '').includes('HOT') ? 0.9 : 0.33)), resetsAt: 1_700_000_000 },
|
||||||
seven_day: { utilization: Number(process.env.FAKE_SEVEN_DAY ?? 0.5), resetsAt: 1_700_300_000 },
|
seven_day: { utilization: Number(process.env.FAKE_SEVEN_DAY ?? 0.5), resetsAt: 1_700_300_000 },
|
||||||
} } });
|
} } });
|
||||||
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ async function setup() {
|
||||||
const db = await testDb();
|
const db = await testDb();
|
||||||
const sentMails = [];
|
const sentMails = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), sandbox: { enabled: false, production: false }, secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
||||||
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
|
import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
|
|
@ -15,6 +15,7 @@ import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||||
import { validateGitUrl } from '../src/services/git.js';
|
import { validateGitUrl } from '../src/services/git.js';
|
||||||
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
||||||
import { addUser } from './helpers/users.js';
|
import { addUser } from './helpers/users.js';
|
||||||
|
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||||
|
|
||||||
async function setup() {
|
async function setup() {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
||||||
|
|
@ -28,7 +29,13 @@ async function setup() {
|
||||||
const sentMails = [];
|
const sentMails = [];
|
||||||
const app = {
|
const app = {
|
||||||
db,
|
db,
|
||||||
cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), sandbox: { enabled: false, production: false }, secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
|
// syncRepo refuse file:// (clones d'URL fournies par l'utilisateur : https seulement) : le test clone le dépôt local à la place
|
||||||
|
syncRepo: async (url, dir) => {
|
||||||
|
if (existsSync(join(dir, '.git'))) execFileSync('git', ['-C', dir, 'pull', '-q']);
|
||||||
|
else execFileSync('git', ['clone', '-q', '--depth', '1', url, dir]);
|
||||||
|
return execFileSync('git', ['-C', dir, 'rev-parse', 'HEAD']).toString().trim();
|
||||||
|
},
|
||||||
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
||||||
};
|
};
|
||||||
const userId = await addUser(db);
|
const userId = await addUser(db);
|
||||||
|
|
@ -199,8 +206,7 @@ test('sans objet B : tout part en A', async () => {
|
||||||
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
||||||
const s = await setup();
|
const s = await setup();
|
||||||
const spyFile = join(s.tmp, 'models.log');
|
const spyFile = join(s.tmp, 'models.log');
|
||||||
s.app.cfg.claudeBin = resolve('test/fixtures/spy-claude.js');
|
s.app.cfg.claudeBin = makeClaudeBin(s.tmp, { fixture: 'spy-claude.js', env: { MODEL_SPY_FILE: spyFile } });
|
||||||
process.env.MODEL_SPY_FILE = spyFile;
|
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze');
|
const a = await run(s, 'analyze');
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
|
|
@ -208,7 +214,7 @@ test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur d
|
||||||
const a2 = await run(s, 'analyze');
|
const a2 = await run(s, 'analyze');
|
||||||
assert.equal(a2.status, 'done', a2.error);
|
assert.equal(a2.status, 'done', a2.error);
|
||||||
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
||||||
} finally { delete process.env.MODEL_SPY_FILE; rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
||||||
|
|
@ -222,7 +228,7 @@ test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () =>
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
assert.equal(sent.length, 0, 'sous le seuil : pas d\'alerte');
|
assert.equal(sent.length, 0, 'sous le seuil : pas d\'alerte');
|
||||||
|
|
||||||
process.env.FAKE_FIVE_HOUR = '0.84';
|
s.app.cfg.claudeBin = makeClaudeBin(s.tmp, { env: { FAKE_FIVE_HOUR: '0.84' } });
|
||||||
const a2 = await run(s, 'analyze');
|
const a2 = await run(s, 'analyze');
|
||||||
assert.equal(a2.status, 'done', a2.error);
|
assert.equal(a2.status, 'done', a2.error);
|
||||||
assert.equal(sent.length, 1);
|
assert.equal(sent.length, 1);
|
||||||
|
|
@ -233,5 +239,5 @@ test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () =>
|
||||||
const a3 = await run(s, 'analyze');
|
const a3 = await run(s, 'analyze');
|
||||||
assert.equal(a3.status, 'done', a3.error);
|
assert.equal(a3.status, 'done', a3.error);
|
||||||
assert.equal(sent.length, 1);
|
assert.equal(sent.length, 1);
|
||||||
} finally { delete process.env.FAKE_FIVE_HOUR; rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
|
||||||
19
test/helpers/claude-bin.js
Normal file
19
test/helpers/claude-bin.js
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
// Faux exécutable `claude` pour un test : script sh qui fixe des variables d'environnement puis lance une fixture.
|
||||||
|
// Nécessaire parce que l'environnement du processus enfant est assaini (liste blanche) : un test ne peut plus
|
||||||
|
// piloter la fixture en modifiant process.env.
|
||||||
|
import { chmodSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
|
||||||
|
const posix = (p) => p.split('\\').join('/');
|
||||||
|
const q = (s) => `'${String(s).split("'").join("'\\''")}'`;
|
||||||
|
|
||||||
|
/** @returns {string} chemin du script ; `fixture` : nom dans test/fixtures, `env` : variables à fixer */
|
||||||
|
export function makeClaudeBin(dir, { fixture = 'fake-claude.js', env = {}, name = 'claude-test', logVars = [], logFile } = {}) {
|
||||||
|
const file = join(dir, name);
|
||||||
|
const vars = Object.entries(env).map(([k, v]) => `${k}=${q(v)}`).join(' ');
|
||||||
|
// logVars : variables reçues par le processus, ajoutées (une ligne par appel) à logFile avant de lancer la fixture
|
||||||
|
const log = logVars.length ? `echo "${logVars.map((v) => '${' + v + '}').join(' ')}" >> ${q(posix(logFile))}\n` : '';
|
||||||
|
writeFileSync(file, `#!/bin/sh\n${log}${vars} exec ${q(posix(process.execPath))} ${q(posix(resolve('test/fixtures', fixture)))} "$@"\n`);
|
||||||
|
chmodSync(file, 0o755);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
@ -14,7 +14,8 @@ export async function startApp({ cfg = {}, worker = false } = {}) {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-srv-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-srv-'));
|
||||||
const config = {
|
const config = {
|
||||||
appUrl: APP_URL, google: { clientId: 'gid', clientSecret: 'gsecret' }, apple: null, adminEmails: [],
|
appUrl: APP_URL, google: { clientId: 'gid', clientSecret: 'gsecret' }, apple: null, adminEmails: [],
|
||||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, ...cfg,
|
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, cliModeEnabled: true,
|
||||||
|
sandbox: { enabled: false, production: false, roBinds: [], serverHome: tmp }, ...cfg,
|
||||||
};
|
};
|
||||||
const app = await createApp(config, { db: await testDb(), worker });
|
const app = await createApp(config, { db: await testDb(), worker });
|
||||||
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,15 @@
|
||||||
// Comptes de test
|
// Comptes de test
|
||||||
let seq = 0;
|
let seq = 0;
|
||||||
|
|
||||||
/** Crée un compte et renvoie son id. Admin et actif par défaut (les tests historiques lancent des jobs IA). */
|
/**
|
||||||
export async function addUser(db, { email, admin = true, status = 'active', provider = 'google', sub, name = null } = {}) {
|
* Crée un compte et renvoie son id. Admin et actif par défaut, avec la liaison « Claude du serveur » (les tests historiques
|
||||||
|
* lancent des jobs IA). `link` : null = aucune liaison, ou un objet claude_link_json complet.
|
||||||
|
*/
|
||||||
|
export async function addUser(db, { email, admin = true, status = 'active', provider = 'google', sub, name = null, link } = {}) {
|
||||||
seq++;
|
seq++;
|
||||||
const r = await db.prepare(`INSERT INTO users(email, name, provider, provider_sub, status, is_admin, plan, created_at)
|
const linkJson = link === undefined ? (admin ? { v: 1, mode: 'server', valid: true, linked_at: 1_700_000_000, validated_at: 1_700_000_000 } : null) : link;
|
||||||
VALUES(?, ?, ?, ?, ?, ?, 'free', ?)`).run(email || `user${seq}@test.fr`, name, provider, sub || `sub-${seq}`, status, admin ? 1 : 0, 1_700_000_000);
|
const r = await db.prepare(`INSERT INTO users(email, name, provider, provider_sub, status, is_admin, plan, created_at, claude_link_json)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, 'free', ?, ?)`).run(email || `user${seq}@test.fr`, name, provider, sub || `sub-${seq}`, status, admin ? 1 : 0, 1_700_000_000, linkJson ? JSON.stringify(linkJson) : null);
|
||||||
return Number(r.lastInsertRowid);
|
return Number(r.lastInsertRowid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ before(async () => {
|
||||||
tmp = mkdtempSync(join(tmpdir(), 'aitools-http-'));
|
tmp = mkdtempSync(join(tmpdir(), 'aitools-http-'));
|
||||||
const cfg = {
|
const cfg = {
|
||||||
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, apple: null, adminEmails: ['me@gmail.com'],
|
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, apple: null, adminEmails: ['me@gmail.com'],
|
||||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75,
|
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, sandbox: { enabled: false, production: false },
|
||||||
};
|
};
|
||||||
app = await createApp(cfg, { db: await testDb(), worker: false });
|
app = await createApp(cfg, { db: await testDb(), worker: false });
|
||||||
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,11 @@ import { addUser } from './helpers/users.js';
|
||||||
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
||||||
|
|
||||||
const bin = resolve('test/fixtures/fake-claude.js');
|
const bin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const sandbox = { enabled: false, production: false };
|
||||||
|
|
||||||
test('runClaude parse le flux et la conso', async () => {
|
test('runClaude parse le flux et la conso', async () => {
|
||||||
const seen = [];
|
const seen = [];
|
||||||
const r = await runClaude({ bin, prompt: 'hello', model: 'haiku', maxTurns: 3, tools: ['Read', 'Grep'], onText: (t) => seen.push(t) });
|
const r = await runClaude({ bin, sandbox, prompt: 'hello', model: 'haiku', maxTurns: 3, tools: ['Read', 'Grep'], onText: (t) => seen.push(t) });
|
||||||
assert.equal(r.ok, true);
|
assert.equal(r.ok, true);
|
||||||
assert.equal(r.costUsd, 0.0123);
|
assert.equal(r.costUsd, 0.0123);
|
||||||
assert.equal(r.tokensIn, 150);
|
assert.equal(r.tokensIn, 150);
|
||||||
|
|
@ -26,7 +27,7 @@ test('runClaude parse le flux et la conso', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('runClaude remonte une erreur si le process meurt', async () => {
|
test('runClaude remonte une erreur si le process meurt', async () => {
|
||||||
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
|
await assert.rejects(runClaude({ bin, sandbox, prompt: 'CRASH' }), /sans résultat/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rateLimitWindows normalise la session (5h) et la semaine, quel que soit le format reçu', () => {
|
test('rateLimitWindows normalise la session (5h) et la semaine, quel que soit le format reçu', () => {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue