feat(git): Git-Backend über HTTPS + PAT (ADR 0003, FLW-86) (#19)
Repositories gitConnections/brewGitLinks (Mongo/PG), Krypto, SSRF-Policy mit net.BlockList, git-Client ohne Arbeitskopie, Sync/Konflikte, /api/git/*, Client (Verbindungen, Git-Status, Konfliktdialog), Autosave 60 s für Git-Brews (F6), Tests und Doku. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Dev (Paperclip) <dev-bot@noreply.git.morlana.online>
This commit was merged in pull request #19.
This commit is contained in:
1 parent
06b7ad2c77
commit
448c67912f
44 files changed
+3081
-14
No files matched your search
@@ -0,0 +1,159 @@
|
||||
// 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: Brew und Link weg, Datei bleibt (F9)
|
||||
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')).toContain('Vierte Fassung');
|
||||
expect(await storage.getStorage().brewGitLinks.findByBrewId(created.body.id)).toBeNull();
|
||||
});
|
||||
|
||||
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']);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user