Files
homebrewery-oidc/tests/fork/assets.test.js
T
dev-bot BotandClaude Sonnet 5.5 1ff86709b8
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (pull_request) Successful in 2m14s
CI / Storage (mongo) (pull_request) Successful in 1m42s
CI / Storage (postgres) (pull_request) Successful in 1m53s
fix(assets): Review PR #26 – Upload unter Brew-Lock, inject per Ref, metadataEditor zurückgenommen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 01:24:26 +00:00

359 lines
18 KiB
JavaScript

// Integration Bild-Upload (ADR 0004): echtes `git` gegen lokalen `git http-backend`, Storage im Speicher.
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { execFileSync } from 'child_process';
import express from 'express';
import supertest from 'supertest';
import api from '../../server/homebrew.api.js';
import contentNegotiation from '../../server/middleware/content-negotiation.js';
import { splitTextStyleAndMetadata } from '../../shared/helpers.js';
import { readGitConfig } from '../../server/fork/git/config.js';
import { createGitService } from '../../server/fork/git/brewSync.js';
import { createGitRouter } from '../../server/fork/git/routes.js';
import { createAssetsBackend, createAssetsDeliveryRouter } from '../../server/fork/assets/index.js';
import packageJSON from '../../package.json' with { type: 'json' };
import { startGitHttpServer } from './git-http-test-server.js';
import { createMemoryStorage } from './git-memory-storage.js';
import { PNG, GIF, JPEG, WEBP, SVG, pngVariant } from './image-fixtures.js';
const silent = process.env.GIT_TEST_LOG ? console : { warn: ()=>{}, error: ()=>{}, log: ()=>{} };
const version = { 'Homebrewery-Version': packageJSON.version };
const asAccount = (a)=>({ 'x-account': JSON.stringify(a) });
const KEY = crypto.randomBytes(32).toString('base64');
const sha256 = (b)=>crypto.createHash('sha256').update(b).digest('hex');
let remote; let storage; let svc; let request; let workdir; let alice; let bob; let assets;
const ALICE = ()=>({ username: 'alice', uid: alice.id });
const repoDir = (url)=>remote.dirOf(new URL(url).pathname.slice(1));
const blobAt = (dir, p)=>execFileSync('git', ['-C', dir, 'cat-file', 'blob', `refs/heads/main:${p}`], { maxBuffer: 50 * 1024 * 1024 });
const build = (env = {}, { delivery = true } = {})=>{
const cfg = { ...readGitConfig({ HB_GIT_TOKEN_KEY: KEY, HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_WORKDIR: workdir }),
allowHttp : true, allowPrivate : true, openTimeoutMs : 1000, timeoutMs : 5000 };
svc = createGitService({ cfg, getStorage: ()=>storage, api, splitTextStyleAndMetadata, logger: silent });
assets = createAssetsBackend({ gitSvc: svc, getStorage: ()=>storage, env, logger: silent });
const app = express();
if(delivery) app.use(createAssetsDeliveryRouter({ getStorage: ()=>storage, logger: silent }));
app.use(contentNegotiation);
app.use(express.json());
app.use((req, res, next)=>{ if(req.headers['x-account']) req.account = JSON.parse(req.headers['x-account']); next(); });
app.use(assets.router);
app.use(createGitRouter(svc, { logger: silent }));
request = supertest(app);
};
// Verknüpften Brew anlegen (Datei brews/b.md im lokalen Remote)
const linkedBrew = async ({ authors = ['alice'], connExtra = {} } = {})=>{
const { url } = remote.createRepo(`r${Math.random().toString(36).slice(2)}.git`);
const c = await request.post('/api/git/connections').set(version).set(asAccount(ALICE()))
.send({ label: 'T', repoUrl: url, authUsername: remote.username, token: remote.token, ...connExtra });
expect(c.status).toBe(201);
const brew = await storage.brews.create({ title: 'B', text: 'Hallo', authors });
await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: c.body.id, path: 'brews/b.md' }).expect(200);
return { brew, dir: repoDir(url), conn: c.body, url };
};
const upload = (editId, buf, { type = 'image/png', name = 'Karte.png', account = ALICE() } = {})=>{
let r = request.post(`/api/git/brews/${editId}/assets`).set(version).set('Content-Type', type).set('X-HB-Filename', encodeURIComponent(name));
if(account) r = r.set(asAccount(account));
return r.send(buf);
};
beforeAll(async ()=>{
remote = await startGitHttpServer();
workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-asset-work-'));
});
afterAll(async ()=>{
await remote.close();
fs.rmSync(workdir, { recursive: true, force: true });
});
beforeEach(async ()=>{
storage = createMemoryStorage();
alice = await storage.users.create({ username: 'alice', displayName: 'Alice A.' });
bob = await storage.users.create({ username: 'bob' });
build();
});
describe('Upload', ()=>{
test('legt das Bild im Repo ab, speichert den Snapshot und liefert URL und Markdown', async ()=>{
const { brew, dir } = await linkedBrew();
const res = await upload(brew.editId, PNG);
const hash = sha256(PNG);
expect(res.status).toBe(201);
expect(res.body).toMatchObject({
url : `/git-assets/${brew.shareId}/${hash}.png`,
path : `assets/karte-${hash.slice(0, 12)}.png`,
sha256 : hash,
size : PNG.length,
contentType : 'image/png',
markdown : `![Karte](/git-assets/${brew.shareId}/${hash}.png)`
});
expect(blobAt(dir, res.body.path).equals(PNG)).toBe(true);
expect(remote.log(dir, 'main')[0]).toBe(`Alice A.|Homebrewery|Add asset ${res.body.path} via Homebrewery`);
const stored = await storage.brewAssets.findByBrewAndHash(brew.id, hash, { withData: true });
expect(stored).toMatchObject({ repoPath: res.body.path, commitSha: remote.head(dir, 'main'), contentType: 'image/png' });
expect(stored.data.equals(PNG)).toBe(true);
});
test('Upload ändert last_blob_sha nicht: ein folgender Brew-Save sieht keinen Konflikt', async ()=>{
const { brew } = await linkedBrew();
const before = await storage.brewGitLinks.findByBrewId(brew.id);
await upload(brew.editId, PNG).expect(201);
expect(await storage.brewGitLinks.findByBrewId(brew.id)).toEqual(before);
const res = { status(c) { res.code = c; return res; }, json(b) { res.body = b; return res; } };
const current = await storage.brews.findByEditId(brew.editId);
const ctx = await svc.beforeBrewSave({ brew: { ...current, text: 'Neu' }, req: { query: {}, account: ALICE() }, res });
expect(res.code).toBeUndefined();
expect(ctx.git.commit).toMatch(/^[0-9a-f]{40}$/);
ctx.release();
});
test.each([['png', PNG, 'image/png', 'png'], ['gif', GIF, 'image/gif', 'gif'], ['jpeg', JPEG, 'image/jpeg', 'jpg'], ['webp', WEBP, 'image/webp', 'webp']])('%s wird erkannt und mit passender Endung abgelegt', async (t, buf, mime, ext)=>{
const { brew, dir } = await linkedBrew();
const res = await upload(brew.editId, buf, { type: mime, name: `foto.${ext}` });
expect(res.status).toBe(201);
expect(res.body.path).toMatch(new RegExp(`^assets/foto-[0-9a-f]{12}\\.${ext}$`));
expect(blobAt(dir, res.body.path).equals(buf)).toBe(true);
});
test('gleicher Inhalt: 200 mit bestehendem Asset, kein weiterer Commit', async ()=>{
const { brew, dir } = await linkedBrew();
const first = await upload(brew.editId, PNG).expect(201);
const commits = remote.log(dir, 'main').length;
const second = await upload(brew.editId, PNG, { name: 'ganz-anderer-name.png' });
expect(second.status).toBe(200);
expect(second.body.path).toBe(first.body.path);
expect(second.body.url).toBe(first.body.url);
expect(remote.log(dir, 'main')).toHaveLength(commits);
expect(await storage.brewAssets.listByBrew(brew.id)).toHaveLength(1);
});
test('Datei liegt im Repo schon mit gleichem Blob: kein Commit, Snapshot wird trotzdem angelegt', async ()=>{
const { brew, dir } = await linkedBrew();
const hash = sha256(PNG);
const p = `assets/karte-${hash.slice(0, 12)}.png`;
remote.commitFile(dir, 'main', p, PNG);
const commits = remote.log(dir, 'main').length;
const res = await upload(brew.editId, PNG);
expect(res.status).toBe(201);
expect(remote.log(dir, 'main')).toHaveLength(commits);
expect(await storage.brewAssets.findByBrewAndHash(brew.id, hash)).not.toBeNull();
});
test('assets_dir der Verbindung wird verwendet', async ()=>{
const { brew, dir } = await linkedBrew({ connExtra: { assetsDir: 'media/img' } });
const res = await upload(brew.editId, PNG);
expect(res.body.path).toMatch(/^media\/img\/karte-/);
expect(blobAt(dir, res.body.path).equals(PNG)).toBe(true);
});
test('Non-Fast-Forward durch Push eines Dritten: Retry, Bild landet trotzdem', async ()=>{
const { brew, dir } = await linkedBrew();
const res = await upload(brew.editId, pngVariant(1));
await upload(brew.editId, pngVariant(2)).expect(201);
remote.commitFile(dir, 'main', 'README.md', 'extern');
const third = await upload(brew.editId, pngVariant(3));
expect(third.status).toBe(201);
expect(blobAt(dir, res.body.path)).toBeTruthy();
expect(remote.readFile(dir, 'main', 'README.md')).toBe('extern');
expect(remote.log(dir, 'main').filter((l)=>l.includes('Add asset'))).toHaveLength(3);
});
});
describe('Prüfungen und Fehler', ()=>{
test('nicht verknüpfter Brew: 400 A05', async ()=>{
const brew = await storage.brews.create({ title: 'X', text: 'x', authors: ['alice'] });
const res = await upload(brew.editId, PNG);
expect([res.status, res.body.HBErrorCode]).toEqual([400, 'A05']);
expect(await storage.brewAssets.listByBrew(brew.id)).toEqual([]);
});
test('zu groß: 413 A01 mit verständlicher Meldung, nichts im Repo', async ()=>{
build({ HB_ASSET_MAX_BYTES: String(PNG.length - 1) });
const { brew, dir } = await linkedBrew();
const res = await upload(brew.editId, PNG);
expect([res.status, res.body.HBErrorCode]).toEqual([413, 'A01']);
expect(res.body.message).toMatch(/zu groß/);
expect(()=>blobAt(dir, 'assets/x')).toThrow();
expect(remote.log(dir, 'main')).toHaveLength(1);
});
test('Typ stimmt nicht zum Header oder ist nicht erlaubt: 415 A02, auch SVG und Text mit Bild-Header', async ()=>{
const { brew } = await linkedBrew();
const cases = [
[PNG, 'image/jpeg'], // Header lügt
[SVG, 'image/svg+xml'], // SVG ausgeschlossen
[SVG, 'image/png'], // SVG als PNG getarnt
[Buffer.from('<?php ?>'), 'image/png'],
[PNG, 'application/octet-stream'],
[PNG.subarray(0, 30), 'image/png'] // abgeschnitten
];
for (const [buf, type] of cases) {
const res = await upload(brew.editId, buf, { type });
expect([res.status, res.body.HBErrorCode]).toEqual([415, 'A02']);
}
expect(await storage.brewAssets.listByBrew(brew.id)).toEqual([]);
});
test('HB_ASSET_TYPES schränkt ein: GIF abgelehnt, PNG erlaubt', async ()=>{
build({ HB_ASSET_TYPES: 'png' });
const { brew } = await linkedBrew();
const gif = await upload(brew.editId, GIF, { type: 'image/gif', name: 'a.gif' });
expect([gif.status, gif.body.HBErrorCode]).toEqual([415, 'A02']);
expect(gif.body.message).toMatch(/PNG/);
await upload(brew.editId, PNG).expect(201);
});
test('Summe pro Brew: 413 A03, doppelter Inhalt zählt nicht doppelt', async ()=>{
build({ HB_ASSET_MAX_BYTES_PER_BREW: String(PNG.length * 2 + 1) });
const { brew, dir } = await linkedBrew();
await upload(brew.editId, pngVariant(1)).expect(201);
await upload(brew.editId, pngVariant(1)).expect(200);
await upload(brew.editId, pngVariant(2)).expect(201);
const res = await upload(brew.editId, pngVariant(3));
expect([res.status, res.body.HBErrorCode]).toEqual([413, 'A03']);
expect(remote.log(dir, 'main').filter((l)=>l.includes('Add asset'))).toHaveLength(2);
});
test('zwei parallele Uploads am Brew-Limit: einer 201, einer 413 A03 (kein Race)', async ()=>{
build({ HB_ASSET_MAX_BYTES_PER_BREW: String(pngVariant(1).length + 1) });
const { brew, dir } = await linkedBrew();
const [a, b] = await Promise.all([upload(brew.editId, pngVariant(1)), upload(brew.editId, pngVariant(2))]);
expect([a.status, b.status].sort()).toEqual([201, 413]);
expect([a, b].find((r)=>r.status === 413).body.HBErrorCode).toBe('A03');
expect(await storage.brewAssets.listByBrew(brew.id)).toHaveLength(1);
expect(remote.log(dir, 'main').filter((l)=>l.includes('Add asset'))).toHaveLength(1);
});
test('leerer Body: 400 A06', async ()=>{
const { brew } = await linkedBrew();
const res = await upload(brew.editId, Buffer.alloc(0));
expect([res.status, res.body.HBErrorCode]).toEqual([400, 'A06']);
});
test('gesperrter Brew: 423 A04', async ()=>{
const { brew } = await linkedBrew();
await storage.brews.update({ ...brew, lock: { code: 1, editMessage: 'x', shareMessage: 'y' } });
const res = await upload(brew.editId, PNG);
expect([res.status, res.body.HBErrorCode]).toEqual([423, 'A04']);
});
test('Rechte wie Speichern: Fremde 401, ohne Login 401, Mitautor darf', async ()=>{
const { brew } = await linkedBrew({ authors: ['alice', 'carol'] });
expect((await upload(brew.editId, PNG, { account: { username: 'dave' } })).status).toBe(401);
expect((await upload(brew.editId, PNG, { account: null })).status).toBe(401);
expect((await upload('gibtsnicht', PNG)).status).toBe(404);
expect((await upload(brew.editId, PNG, { account: { username: 'carol' } })).status).toBe(201);
});
test('Client-Version wird geprüft (412)', async ()=>{
const { brew } = await linkedBrew();
const res = await request.post(`/api/git/brews/${brew.editId}/assets`).set(asAccount(ALICE())).set('Content-Type', 'image/png').send(PNG);
expect(res.status).toBe(412);
});
test('deaktiviert: HB_ASSETS_ENABLED=false und ohne Git-Backend → 503 A07, Konfiguration meldet enabled=false', async ()=>{
const { brew } = await linkedBrew();
build({ HB_ASSETS_ENABLED: 'false' });
const res = await upload(brew.editId, PNG);
expect([res.status, res.body.HBErrorCode]).toEqual([503, 'A07']);
expect((await request.get('/api/git/assets/config')).body.enabled).toBe(false);
build();
expect((await request.get('/api/git/assets/config')).body).toEqual({ enabled: true, maxBytes: 5242880, maxBytesPerBrew: 52428800, types: ['png', 'jpeg', 'gif', 'webp'] });
});
test('Git-Fehler: falscher Token → 502 G02 ohne Snapshot, Token nie in der Antwort', async ()=>{
const { brew, conn } = await linkedBrew();
await request.patch(`/api/git/connections/${conn.id}`).set(version).set(asAccount(ALICE())).send({ token: 'falscher-token-xyz' });
const res = await upload(brew.editId, PNG);
expect([res.status, res.body.HBErrorCode]).toEqual([502, 'G02']);
expect(JSON.stringify(res.body)).not.toContain('falscher-token-xyz');
expect(await storage.brewAssets.listByBrew(brew.id)).toEqual([]);
});
test('Remote hängt: 504 G04, kein Snapshot', async ()=>{
const { brew } = await linkedBrew();
build({}, {});
svc.cfg.timeoutMs = 300;
remote.setHang(true);
try {
const res = await upload(brew.editId, PNG);
expect([res.status, res.body.HBErrorCode]).toEqual([504, 'G04']);
} finally { remote.setHang(false); }
expect(await storage.brewAssets.listByBrew(brew.id)).toEqual([]);
});
});
describe('Auslieferung (ADR 0004 §4)', ()=>{
test('korrekte Header, ohne Login, auch mit Accept: image/* (Content-Negotiation)', async ()=>{
const { brew } = await linkedBrew();
const up = await upload(brew.editId, PNG).expect(201);
const res = await request.get(up.body.url).set('Accept', 'image/avif,image/webp,image/*,*/*;q=0.8').buffer(true).parse((r, cb)=>{ const c = []; r.on('data', (d)=>c.push(d)); r.on('end', ()=>cb(null, Buffer.concat(c))); });
expect(res.status).toBe(200);
expect(res.body.equals(PNG)).toBe(true);
expect(res.headers).toMatchObject({
'content-type' : 'image/png',
'content-length' : String(PNG.length),
'cache-control' : 'public, max-age=31536000, immutable',
'etag' : `"${sha256(PNG)}"`,
'x-content-type-options' : 'nosniff',
'content-security-policy' : 'default-src \'none\'; sandbox',
'cross-origin-resource-policy' : 'same-site'
});
expect(res.headers['set-cookie']).toBeUndefined();
});
test('If-None-Match → 304', async ()=>{
const { brew } = await linkedBrew();
const up = await upload(brew.editId, PNG).expect(201);
const res = await request.get(up.body.url).set('If-None-Match', `"${sha256(PNG)}"`);
expect(res.status).toBe(304);
});
test('unabhängig vom Git-Remote: Auslieferung auch ohne Token, ohne Repo und ohne Git-Backend', async ()=>{
const { brew, conn, url } = await linkedBrew();
const up = await upload(brew.editId, JPEG, { type: 'image/jpeg', name: 'a.jpg' }).expect(201);
await request.patch(`/api/git/connections/${conn.id}`).set(version).set(asAccount(ALICE())).send({ token: 'kaputt' });
fs.rmSync(repoDir(url), { recursive: true, force: true });
const res = await request.get(up.body.url);
expect(res.status).toBe(200);
expect(res.headers['content-type']).toBe('image/jpeg');
// eigener Router, nur mit Storage
const only = supertest(express().use(createAssetsDeliveryRouter({ getStorage: ()=>storage, logger: silent })));
expect((await only.get(up.body.url)).status).toBe(200);
});
test('404: falsche shareId, anderer Brew, falsche Endung, ungültiger Hash, editId statt shareId', async ()=>{
const a = await linkedBrew();
const b = await linkedBrew();
const up = await upload(a.brew.editId, PNG).expect(201);
const hash = sha256(PNG);
expect((await request.get(`/git-assets/unbekannt/${hash}.png`)).status).toBe(404);
expect((await request.get(`/git-assets/${b.brew.shareId}/${hash}.png`)).status).toBe(404); // Asset gehört zu a
expect((await request.get(`/git-assets/${a.brew.shareId}/${hash}.jpg`)).status).toBe(404);
expect((await request.get(`/git-assets/${a.brew.shareId}/${hash}.svg`)).status).toBe(404);
expect((await request.get(`/git-assets/${a.brew.shareId}/${hash.toUpperCase()}.png`)).status).toBe(404);
expect((await request.get(`/git-assets/${a.brew.shareId}/zzz.png`)).status).toBe(404);
expect((await request.get(`/git-assets/${a.brew.editId}/${hash}.png`)).status).toBe(404);
expect((await request.get(up.body.url)).status).toBe(200);
});
test('gesperrter Brew: 403 mit Fehlercode 51 wie /share', async ()=>{
const { brew } = await linkedBrew();
const up = await upload(brew.editId, PNG).expect(201);
await storage.brews.update({ ...brew, lock: { code: 1, editMessage: 'x', shareMessage: 'Gesperrt' } });
const res = await request.get(up.body.url);
expect([res.status, res.body.HBErrorCode]).toEqual([403, '51']);
});
test('Brew löschen entfernt die Assets', async ()=>{
const { brew } = await linkedBrew();
const up = await upload(brew.editId, PNG).expect(201);
await storage.brews.deleteById(brew.id);
expect((await request.get(up.body.url)).status).toBe(404);
expect(await storage.brewAssets.listByBrew(brew.id)).toEqual([]);
});
});