Files
homebrewery-oidc/tests/fork/git-backend.db.test.js
T
dev-bot Bot 5e07ef6e8d
Image / Image bauen und pushen (push) Successful in 1m1s
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (push) Successful in 2m58s
CI / Storage (mongo) (push) Successful in 2m26s
CI / Storage (postgres) (push) Successful in 1m47s
feat(git): Git-Brew löschen entfernt die Datei per Commit (F9) (#20) (#24)
Co-authored-by: Dev (Paperclip) <dev-bot@noreply.git.morlana.online>
2026-11-26 02:04:30 +00:00

233 lines
13 KiB
JavaScript

// Git-Backend gegen die echte App und echte Datenbank (ADR 0003): Speichern über PUT /api/update/:id,
// Konflikt G01, gitOverwrite, Pull, Teilen ohne Git-Zugriff. Läuft je Backend, das konfiguriert ist:
// HB_TEST_POSTGRES_URL bzw. HB_TEST_MONGODB_URI (wie api-smoke.test.js).
import os from 'os';
import fs from 'fs';
import path from 'path';
import { randomBytes } from 'crypto';
import supertest from 'supertest';
import jwt from 'jsonwebtoken';
import pg from 'pg';
import mongoose from 'mongoose';
import { md5 } from 'hash-wasm';
import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
import createApp from '../../server/app.js';
import storage from '../../server/storage/index.js';
import packageJSON from '../../package.json' with { type: 'json' };
import { startGitHttpServer } from './git-http-test-server.js';
const backends = [
{ driver: 'postgres', url: process.env.HB_TEST_POSTGRES_URL },
{ driver: 'mongo', url: process.env.HB_TEST_MONGODB_URI }
];
const version = { 'Homebrewery-Version': packageJSON.version };
const SECRET = 's'.repeat(40);
for (const { driver, url } of backends) {
const suite = url ? describe : describe.skip;
if(!url) console.warn(`Git-Backend-DB-Test (${driver}): Datenbank-URL fehlt, übersprungen.`);
suite(`Git-Backend gegen ${driver}`, ()=>{
let request; let cleanup; let remote; let workdir; let cookie; let user; let envBackup; let connectSpy;
beforeAll(async ()=>{
envBackup = { ...process.env };
workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-work-'));
Object.assign(process.env, {
HB_AUTH_PROVIDERS : 'oidc', HB_OIDC_ISSUER : 'https://idp.example.test', HB_OIDC_CLIENT_ID : 'hb', HB_OIDC_CLIENT_SECRET : 'x',
HB_PUBLIC_URL : 'http://localhost:8000', HB_SESSION_SECRET : SECRET,
HB_GIT_TOKEN_KEY : randomBytes(32).toString('base64'), HB_GIT_ALLOW_HTTP : 'true', HB_GIT_ALLOW_PRIVATE : 'true', HB_GIT_WORKDIR : workdir
});
remote = await startGitHttpServer();
const name = `test_${randomBytes(4).toString('hex')}`;
const values = { hb_db_driver: driver, node_env: 'test', local_environments: ['local'] };
if(driver === 'postgres') {
const admin = new pg.Client({ connectionString: url });
await admin.connect();
await admin.query(`CREATE SCHEMA ${name}`);
values.hb_postgres_url = `${url}${url.includes('?') ? '&' : '?'}options=-c%20search_path%3D${name}`;
cleanup = async ()=>{ await storage.disconnect(); await admin.query(`DROP SCHEMA ${name} CASCADE`); await admin.end(); };
} else {
values.mongodb_uri = url;
cleanup = async ()=>{ await mongoose.connection.dropDatabase(); await storage.disconnect(); };
}
const connect = mongoose.connect.bind(mongoose);
connectSpy = jest.spyOn(mongoose, 'connect').mockImplementation((u, o)=>connect(u, { ...o, dbName: name, runtimeAdapters: { os } }));
await storage.connect({ get: (key)=>values[key] });
if(driver === 'mongo') {
const { model } = await import('../../server/homebrew.model.js');
await model.collection.createIndex({ shareId: 1 }, { unique: true });
await model.collection.createIndex({ editId: 1 }, { unique: true });
const git = storage.getStorage();
await git.users.Model.init(); await git.gitConnections.Model.init(); await git.brewGitLinks.Model.init();
}
user = await storage.getStorage().users.create({ username: 'alice-git', displayName: 'Alice A.' });
cookie = `hb_session=${jwt.sign({ v: 1, uid: user.id, username: 'alice-git', iss: 'https://idp.example.test', sub: 's1' }, SECRET, { algorithm: 'HS256', expiresIn: 3600 })}`;
request = supertest.agent(await createApp()).set('X-Forwarded-Proto', 'https');
});
afterAll(async ()=>{
await cleanup?.();
connectSpy?.mockRestore();
await remote?.close();
fs.rmSync(workdir, { recursive: true, force: true });
process.env = envBackup;
});
const api = (method, url)=>request[method](url).set(version).set('Cookie', cookie);
const loadBrew = async (editId)=>{
const b = await storage.getStorage().brews.findByEditId(editId);
return b;
};
// Wie der Editor: Patches gegen den zuletzt geladenen (entpackten) Text
const save = async (editId, newText, query = '')=>{
const lookup = await request.get(`/admin/lookup/${editId}`).set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`);
const loaded = lookup.body;
const oldText = loaded.text.normalize('NFC');
return api('put', `/api/update/${editId}${query}`).send({
...loaded, text : newText, hash : await md5(oldText),
patches : stringifyPatches(makePatches(encodeURI(oldText), encodeURI(newText)))
});
};
test('Verbindung anlegen, Brew in Git anlegen, speichern, Konflikt, Überschreiben, Pull, Teilen ohne Git', async ()=>{
const { url: repoUrl, dir } = remote.createRepo('db.git');
const conn = await api('post', '/api/git/connections').send({ label: 'Lokal', repoUrl, authUsername: remote.username, token: remote.token });
expect(conn.status).toBe(201);
expect(JSON.stringify(conn.body)).not.toContain(remote.token);
const created = await api('post', '/api/git/brews').send({ connectionId: conn.body.id, path: 'brews/db.md', brew: { title: 'DB Brew', text: 'Erste Fassung', renderer: 'V3' } });
expect(created.status).toBe(200);
const { editId, shareId } = created.body;
if(process.env.GIT_TEST_LOG) console.log('CREATED', JSON.stringify(created.body), JSON.stringify(await storage.getStorage().brews.findByEditId(editId)));
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Erste Fassung');
const status = await api('get', `/api/git/brews/${editId}`);
expect(status.body).toMatchObject({ linked: true, path: 'brews/db.md', branch: 'main', isConnectionOwner: true });
// Speichern → Commit
const s1 = await save(editId, 'Zweite Fassung');
expect(s1.status).toBe(200);
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Zweite Fassung');
expect(remote.log(dir, 'main')).toHaveLength(2);
expect((await loadBrew(editId)).text).toContain('Zweite Fassung');
expect((await api('get', `/api/git/brews/${editId}`)).body.lastCommitSha).toBe(remote.head(dir, 'main'));
// Teilen: Share-Routen brauchen keinen Git-Zugriff (Server hängt)
remote.setHang(true);
const shared = await request.get(`/source/${shareId}`);
remote.setHang(false);
expect(shared.status).toBe(200);
expect(shared.text).toContain('Zweite Fassung');
// Fremder Commit → 409 G01
remote.commitFile(dir, 'main', 'brews/db.md', '```metadata\ntitle: Extern\n```\n\nExterne Fassung\n');
const conflict = await save(editId, 'Dritte Fassung');
expect(conflict.status).toBe(409);
expect(conflict.body).toMatchObject({ HBErrorCode: 'G01' });
expect(conflict.body.remoteBlobSha).toMatch(/^[0-9a-f]{40}$/);
expect((await loadBrew(editId)).text).toContain('Zweite Fassung'); // DB unverändert
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Externe Fassung');
// Meine Version behalten → Commit auf dem neuen Stand
const over = await save(editId, 'Dritte Fassung', `?gitOverwrite=${conflict.body.remoteBlobSha}`);
expect(over.status).toBe(200);
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Dritte Fassung');
expect(remote.log(dir, 'main')).toHaveLength(4);
// Externer Commit, dann Pull → Snapshot folgt
remote.commitFile(dir, 'main', 'brews/db.md', '```metadata\ntitle: Extern 2\n```\n\nVierte Fassung\n');
const pulled = await api('post', `/api/git/brews/${editId}/pull`);
expect(pulled.status).toBe(200);
const after = await loadBrew(editId);
expect(after.title).toBe('Extern 2');
expect(after.text).toContain('Vierte Fassung');
// Löschen (F9): Datei wird per Commit mitgelöscht, danach Brew und Link weg
const removed = await api('get', `/api/remove/${editId}`);
expect(removed.status).toBe(204);
expect(await loadBrew(editId)).toBeNull();
expect(()=>remote.readFile(dir, 'main', 'brews/db.md')).toThrow();
expect(remote.log(dir, 'main')[0]).toBe('Alice A.|Homebrewery|Delete brews/db.md via Homebrewery');
expect(await storage.getStorage().brewGitLinks.findByBrewId(created.body.id)).toBeNull();
});
test('Teilen: alle Leser-Routen ohne Anmeldung und ohne Git, Snapshot-Zeit steigt, normale Brews unberührt', async ()=>{
const { url: repoUrl } = remote.createRepo('share.git');
const conn = await api('post', '/api/git/connections').send({ label: 'Privat', repoUrl, authUsername: remote.username, token: remote.token });
const created = await api('post', '/api/git/brews').send({ connectionId: conn.body.id, path: 'brews/share.md', brew: { title: 'Geteilt', text: '```css\n.snap { color: red; }\n```\n\nSnapshot Eins', renderer: 'V3' } });
expect(created.status).toBe(200);
const { editId, shareId } = created.body;
const plain = await api('post', '/api').send({ title: 'Normal', text: 'Ohne Git', renderer: 'V3' });
expect(plain.status).toBe(200);
const readerRoutes = (id)=>[`/share/${id}`, `/api/fetch/${id}`, `/metadata/${id}`, `/source/${id}`, `/download/${id}`, `/css/${id}`];
const readAll = async (id)=>{
const out = {};
for (const route of readerRoutes(id)) {
const res = await request.get(route); // bewusst ohne Cookie: Leser ohne Konto
expect([route, res.status]).toEqual([route, 200]);
out[route] = res;
const body = `${res.text ?? ''}${JSON.stringify(res.body ?? {})}`;
expect(body).not.toContain(remote.token);
expect(body).not.toContain(repoUrl);
expect(body).not.toContain('brews/share.md');
}
return out;
};
remote.setHang(true); // Git nicht erreichbar → Share darf nicht davon abhängen
let before;
try { before = await readAll(shareId); } finally { remote.setHang(false); }
expect(before[`/source/${shareId}`].text).toContain('Snapshot Eins');
expect(before[`/download/${shareId}`].text).toContain('Snapshot Eins');
const t1 = new Date(JSON.parse(before[`/metadata/${shareId}`].text ?? JSON.stringify(before[`/metadata/${shareId}`].body)).updatedAt);
// Jedes erfolgreiche Speichern aktualisiert den Snapshot und seinen Zeitpunkt
await new Promise((r)=>setTimeout(r, 20));
expect((await save(editId, 'Snapshot Zwei')).status).toBe(200);
remote.setHang(true);
let after;
try { after = await readAll(shareId); } finally { remote.setHang(false); }
expect(after[`/source/${shareId}`].text).toContain('Snapshot Zwei');
const t2 = new Date(after[`/metadata/${shareId}`].body.updatedAt);
expect(t2.getTime()).toBeGreaterThan(t1.getTime());
const st = await api('get', `/api/git/brews/${editId}`);
expect(new Date(st.body.snapshotAt).getTime()).toBe(t2.getTime());
// Normaler Brew: gleiche Routen, kein Git-Feld
const normal = await request.get(`/api/fetch/${plain.body.shareId}`);
expect(normal.status).toBe(200);
expect(normal.body.brew.text).toContain('Ohne Git');
expect((await request.get(`/source/${plain.body.shareId}`)).text).toContain('Ohne Git');
expect((await api('get', `/api/git/brews/${plain.body.editId}`)).body).toEqual({ linked: false });
});
test('Löschen: fremder Commit → 409 G01, Brew und Datei bleiben; Mitautor-Fall: Besitzer geht, Verknüpfung weg, Datei bleibt', async ()=>{
const { url: repoUrl, dir } = remote.createRepo('db-del.git');
const conn = await api('post', '/api/git/connections').send({ label: 'Lokal', repoUrl, authUsername: remote.username, token: remote.token });
const created = await api('post', '/api/git/brews').send({ connectionId: conn.body.id, path: 'brews/del.md', brew: { title: 'Del', text: 'Text' } });
const { editId } = created.body;
remote.commitFile(dir, 'main', 'brews/del.md', 'extern');
const conflict = await api('get', `/api/remove/${editId}`);
expect([conflict.status, conflict.body.HBErrorCode, conflict.body.operation]).toEqual([409, 'G01', 'delete']);
expect(await loadBrew(editId)).not.toBeNull();
expect(remote.readFile(dir, 'main', 'brews/del.md')).toBe('extern');
const b = await loadBrew(editId);
await storage.getStorage().brews.update({ ...b, authors: ['alice-git', 'mitautor'] });
const head = remote.head(dir, 'main');
expect((await api('get', `/api/remove/${editId}`)).status).toBe(204);
expect((await loadBrew(editId)).authors).toEqual(['mitautor']);
expect(await storage.getStorage().brewGitLinks.findByBrewId(created.body.id)).toBeNull();
expect(remote.head(dir, 'main')).toBe(head);
expect(remote.readFile(dir, 'main', 'brews/del.md')).toBe('extern');
});
test('Konten ohne uid (nicht angemeldet) bekommen 403 G07', async ()=>{
const res = await request.get('/api/git/connections').set(version);
expect([res.status, res.body.HBErrorCode]).toEqual([403, 'G07']);
});
});
}