Spaces:
Paused
Paused
feat: /iserv/freigabe releases unchecked files (APPROVE_TOKEN, 10 min, once)
Browse files- iserv-filter/app.py +4 -3
- iserv-filter/taskfilter.py +28 -10
- src/api/iserv-filtered.js +40 -4
- tests/iserv-release.test.mjs +37 -0
iserv-filter/app.py
CHANGED
|
@@ -101,10 +101,11 @@ async def filter_fetched(request: Request):
|
|
| 101 |
if int(request.headers.get("content-length") or 0) > MAX_BODY:
|
| 102 |
return _error("too_large", 413)
|
| 103 |
body = await request.body()
|
| 104 |
-
return await run_in_threadpool(_filter_body, body, request.query_params.get("dateien") == "1"
|
|
|
|
| 105 |
|
| 106 |
|
| 107 |
-
def _filter_body(body: bytes, files=False):
|
| 108 |
if len(body) > MAX_BODY:
|
| 109 |
return _error("too_large", 413)
|
| 110 |
try:
|
|
@@ -116,7 +117,7 @@ def _filter_body(body: bytes, files=False):
|
|
| 116 |
with _lock:
|
| 117 |
try:
|
| 118 |
stats = Counter()
|
| 119 |
-
result = [filter_task(t, stats, files) for t in from_browser(items)]
|
| 120 |
except Exception as e: # never log the message or traceback: they may quote task text
|
| 121 |
log.error("Interner Fehler: %s", type(e).__name__)
|
| 122 |
return _error("internal", 500)
|
|
|
|
| 101 |
if int(request.headers.get("content-length") or 0) > MAX_BODY:
|
| 102 |
return _error("too_large", 413)
|
| 103 |
body = await request.body()
|
| 104 |
+
return await run_in_threadpool(_filter_body, body, request.query_params.get("dateien") == "1",
|
| 105 |
+
set(request.query_params.get("freigabe", "").split(",")))
|
| 106 |
|
| 107 |
|
| 108 |
+
def _filter_body(body: bytes, files=False, release=()):
|
| 109 |
if len(body) > MAX_BODY:
|
| 110 |
return _error("too_large", 413)
|
| 111 |
try:
|
|
|
|
| 117 |
with _lock:
|
| 118 |
try:
|
| 119 |
stats = Counter()
|
| 120 |
+
result = [filter_task(t, stats, files, release) for t in from_browser(items)]
|
| 121 |
except Exception as e: # never log the message or traceback: they may quote task text
|
| 122 |
log.error("Interner Fehler: %s", type(e).__name__)
|
| 123 |
return _error("internal", 500)
|
iserv-filter/taskfilter.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""filter_task: the one place that decides what leaves the server. Explicit whitelist, free text always filtered."""
|
| 2 |
import base64
|
| 3 |
import io
|
|
|
|
| 4 |
import zipfile
|
| 5 |
from collections import Counter
|
| 6 |
|
|
@@ -122,9 +123,23 @@ def _file_out(ext, data, text):
|
|
| 122 |
return {"mime": _MIME[ext], "base64": base64.b64encode(data).decode()}
|
| 123 |
|
| 124 |
|
| 125 |
-
def
|
| 126 |
-
"""
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
if att.get("skipped"):
|
| 129 |
return {"hinweis": "weiterer Anhang nicht abgerufen"}
|
| 130 |
name = att.get("name") or ""
|
|
@@ -137,24 +152,27 @@ def describe_attachment(att, stats=None, files=False):
|
|
| 137 |
if att.get("data") is None:
|
| 138 |
return {**out, "hinweis": "Datei größer als 10 MB, nicht abgerufen"}
|
| 139 |
if ext not in _EXTRACT:
|
| 140 |
-
|
|
|
|
| 141 |
try:
|
| 142 |
text = _tidy(_EXTRACT[ext](att["data"]))
|
| 143 |
except Exception: # corrupt/encrypted file; the message may quote its content
|
| 144 |
text = ""
|
| 145 |
if not text:
|
| 146 |
-
|
|
|
|
| 147 |
if files:
|
| 148 |
datei = _file_out(ext, att["data"], text)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
| 152 |
if len(text) > MAX_TEXT: # cut at a space so no name is split in half
|
| 153 |
text, out["gekuerzt"] = text[:MAX_TEXT].rsplit(None, 1)[0], True
|
| 154 |
return {**out, "text": filter_text(text, stats)}
|
| 155 |
|
| 156 |
|
| 157 |
-
def filter_task(task, stats: Counter | None = None, files=False):
|
| 158 |
"""Whitelist: anything not named here (creator, groups, feedback, ...) cannot appear in the output."""
|
| 159 |
return {
|
| 160 |
"id": int(task["id"]),
|
|
@@ -164,5 +182,5 @@ def filter_task(task, stats: Counter | None = None, files=False):
|
|
| 164 |
"start": task.get("start"),
|
| 165 |
"abgabe": task.get("due"),
|
| 166 |
"status": None if "done" not in task else "erledigt" if task["done"] else "offen", # None: source cannot tell
|
| 167 |
-
"anhaenge": [describe_attachment(a, stats, files) for a in task.get("attachments", [])],
|
| 168 |
}
|
|
|
|
| 1 |
"""filter_task: the one place that decides what leaves the server. Explicit whitelist, free text always filtered."""
|
| 2 |
import base64
|
| 3 |
import io
|
| 4 |
+
import mimetypes
|
| 5 |
import zipfile
|
| 6 |
from collections import Counter
|
| 7 |
|
|
|
|
| 123 |
return {"mime": _MIME[ext], "base64": base64.b64encode(data).decode()}
|
| 124 |
|
| 125 |
|
| 126 |
+
def _unchecked(out, att, fid, release):
|
| 127 |
+
"""A file Muse may not see by itself: it gets an id to ask the user for. Only an id the user released
|
| 128 |
+
(via the backend's /iserv/freigabe) hands out the original, as it is: it was not checked for names."""
|
| 129 |
+
out["datei_hinweis"] = FILE_WITHHELD
|
| 130 |
+
out["datei"] = None
|
| 131 |
+
if fid in release:
|
| 132 |
+
out["datei"] = {"mime": mimetypes.guess_type(att.get("name") or "")[0] or "application/octet-stream",
|
| 133 |
+
"base64": base64.b64encode(att["data"]).decode()}
|
| 134 |
+
out["datei_hinweis"] = "Original auf Freigabe herausgegeben, nicht auf Namen geprüft"
|
| 135 |
+
else:
|
| 136 |
+
out["freigabe"] = fid
|
| 137 |
+
return out
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def describe_attachment(att, stats=None, files=False, fid=None, release=()):
|
| 141 |
+
"""{name, typ, groesse, text | hinweis}; with files also datei (original file) or datei_hinweis + freigabe id.
|
| 142 |
+
The file bytes leave this function only through _file_out and _unchecked."""
|
| 143 |
if att.get("skipped"):
|
| 144 |
return {"hinweis": "weiterer Anhang nicht abgerufen"}
|
| 145 |
name = att.get("name") or ""
|
|
|
|
| 152 |
if att.get("data") is None:
|
| 153 |
return {**out, "hinweis": "Datei größer als 10 MB, nicht abgerufen"}
|
| 154 |
if ext not in _EXTRACT:
|
| 155 |
+
out["hinweis"] = NOT_READABLE
|
| 156 |
+
return _unchecked(out, att, fid, release) if files else out
|
| 157 |
try:
|
| 158 |
text = _tidy(_EXTRACT[ext](att["data"]))
|
| 159 |
except Exception: # corrupt/encrypted file; the message may quote its content
|
| 160 |
text = ""
|
| 161 |
if not text:
|
| 162 |
+
out["hinweis"] = NOT_READABLE
|
| 163 |
+
return _unchecked(out, att, fid, release) if files else out
|
| 164 |
if files:
|
| 165 |
datei = _file_out(ext, att["data"], text)
|
| 166 |
+
if datei:
|
| 167 |
+
out["datei"] = datei
|
| 168 |
+
else:
|
| 169 |
+
_unchecked(out, att, fid, release)
|
| 170 |
if len(text) > MAX_TEXT: # cut at a space so no name is split in half
|
| 171 |
text, out["gekuerzt"] = text[:MAX_TEXT].rsplit(None, 1)[0], True
|
| 172 |
return {**out, "text": filter_text(text, stats)}
|
| 173 |
|
| 174 |
|
| 175 |
+
def filter_task(task, stats: Counter | None = None, files=False, release=()):
|
| 176 |
"""Whitelist: anything not named here (creator, groups, feedback, ...) cannot appear in the output."""
|
| 177 |
return {
|
| 178 |
"id": int(task["id"]),
|
|
|
|
| 182 |
"start": task.get("start"),
|
| 183 |
"abgabe": task.get("due"),
|
| 184 |
"status": None if "done" not in task else "erledigt" if task["done"] else "offen", # None: source cannot tell
|
| 185 |
+
"anhaenge": [describe_attachment(a, stats, files, f"{int(task['id'])}-{i}", release) for i, a in enumerate(task.get("attachments", []))],
|
| 186 |
}
|
src/api/iserv-filtered.js
CHANGED
|
@@ -3,12 +3,31 @@
|
|
| 3 |
// (iserv.js) reads them, the filter service (iserv-filter/, Python, 127.0.0.1 only, own unix user without the IServ
|
| 4 |
// secrets) cleans them, only its answer leaves. Nothing is stored, cached or logged.
|
| 5 |
//
|
| 6 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import { timingSafeEqual } from 'node:crypto';
|
|
|
|
| 8 |
import { fetchIServTasks } from './iserv.js';
|
| 9 |
|
| 10 |
const FILTER_URL = process.env.ISERV_FILTER_URL || 'http://127.0.0.1:7862/filter';
|
| 11 |
let running = Promise.resolve(); // one IServ session at a time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
function tokenOk(req) {
|
| 14 |
const expected = Buffer.from(process.env.API_BEARER_TOKEN || '');
|
|
@@ -16,7 +35,7 @@ function tokenOk(req) {
|
|
| 16 |
return offered.some((o) => o && Buffer.byteLength(o) === expected.length && timingSafeEqual(Buffer.from(o), expected));
|
| 17 |
}
|
| 18 |
|
| 19 |
-
async function cleanTasks(includeDone, withFiles) {
|
| 20 |
const { ISERV_BASE_URL: url, ISERV_USERNAME: user, ISERV_PASSWORD: pass } = process.env;
|
| 21 |
if (!url || !user || !pass || !url.startsWith('https://')) return { status: 503, body: { error: 'config' } };
|
| 22 |
let raw;
|
|
@@ -27,7 +46,7 @@ async function cleanTasks(includeDone, withFiles) {
|
|
| 27 |
return { status: 502, body: { error: 'unreachable' } }; // the message may quote the school domain
|
| 28 |
}
|
| 29 |
try {
|
| 30 |
-
const res = await fetch(withFiles ? `${FILTER_URL}?dateien=1` : FILTER_URL, {
|
| 31 |
method: 'POST',
|
| 32 |
headers: { 'Content-Type': 'application/json', 'X-App-Token': process.env.API_BEARER_TOKEN },
|
| 33 |
body: JSON.stringify(raw),
|
|
@@ -41,11 +60,28 @@ async function cleanTasks(includeDone, withFiles) {
|
|
| 41 |
|
| 42 |
export function registerIServFiltered(app) {
|
| 43 |
app.get('/iserv/health', (req, res) => res.json({ status: 'ok' }));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
app.get('/iserv/tasks', async (req, res) => {
|
| 45 |
res.set('Cache-Control', 'no-store');
|
| 46 |
if ((process.env.API_BEARER_TOKEN || '').length < 16) return res.status(503).json({ error: 'config' }); // fail closed
|
| 47 |
if (!tokenOk(req)) return res.status(401).json({ error: 'unauthorized' });
|
| 48 |
-
const run = () =>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
const job = running.then(run, run);
|
| 50 |
running = job.catch(() => {});
|
| 51 |
const { status, body } = await job;
|
|
|
|
| 3 |
// (iserv.js) reads them, the filter service (iserv-filter/, Python, 127.0.0.1 only, own unix user without the IServ
|
| 4 |
// secrets) cleans them, only its answer leaves. Nothing is stored, cached or logged.
|
| 5 |
//
|
| 6 |
+
// Files that could not be checked for names (scans, images, audio, files with names) come out only after the user
|
| 7 |
+
// released them on /iserv/freigabe with APPROVE_TOKEN, which Muse does not have. A release is kept in memory for
|
| 8 |
+
// 10 minutes and used once.
|
| 9 |
+
//
|
| 10 |
+
// Secrets: ISERV_BASE_URL (https://host), ISERV_USERNAME, ISERV_PASSWORD, API_BEARER_TOKEN, APPROVE_TOKEN (each at
|
| 11 |
+
// least 16 characters, the last two different).
|
| 12 |
import { timingSafeEqual } from 'node:crypto';
|
| 13 |
+
import express from 'express';
|
| 14 |
import { fetchIServTasks } from './iserv.js';
|
| 15 |
|
| 16 |
const FILTER_URL = process.env.ISERV_FILTER_URL || 'http://127.0.0.1:7862/filter';
|
| 17 |
let running = Promise.resolve(); // one IServ session at a time
|
| 18 |
+
const RELEASE_MS = 10 * 60_000;
|
| 19 |
+
const releases = new Map(); // "<task id>-<file number>" -> expiry time; memory only
|
| 20 |
+
const FORM = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">
|
| 21 |
+
<title>Freigabe</title><body style="font-family:sans-serif;max-width:30rem;margin:2rem auto;padding:0 1rem">
|
| 22 |
+
<h1>Datei freigeben</h1><p>Die Datei wurde nicht auf Namen geprüft. Muse sieht sie nur nach deiner Freigabe (10 Minuten, einmal).</p>
|
| 23 |
+
<form method="post"><p><label>Freigabe-IDs, z. B. 12-0, 12-1<br><input name="ids" required style="width:100%"></label></p>
|
| 24 |
+
<p><label>Freigabe-Code<br><input name="code" type="password" required style="width:100%"></label></p><button>Freigeben</button></form>`;
|
| 25 |
+
|
| 26 |
+
function sameSecret(offered, expected) {
|
| 27 |
+
const a = Buffer.from(String(offered || ''));
|
| 28 |
+
const b = Buffer.from(expected || '');
|
| 29 |
+
return b.length >= 16 && a.length === b.length && timingSafeEqual(a, b);
|
| 30 |
+
}
|
| 31 |
|
| 32 |
function tokenOk(req) {
|
| 33 |
const expected = Buffer.from(process.env.API_BEARER_TOKEN || '');
|
|
|
|
| 35 |
return offered.some((o) => o && Buffer.byteLength(o) === expected.length && timingSafeEqual(Buffer.from(o), expected));
|
| 36 |
}
|
| 37 |
|
| 38 |
+
async function cleanTasks(includeDone, withFiles, released) {
|
| 39 |
const { ISERV_BASE_URL: url, ISERV_USERNAME: user, ISERV_PASSWORD: pass } = process.env;
|
| 40 |
if (!url || !user || !pass || !url.startsWith('https://')) return { status: 503, body: { error: 'config' } };
|
| 41 |
let raw;
|
|
|
|
| 46 |
return { status: 502, body: { error: 'unreachable' } }; // the message may quote the school domain
|
| 47 |
}
|
| 48 |
try {
|
| 49 |
+
const res = await fetch(withFiles ? `${FILTER_URL}?dateien=1&freigabe=${released.join(',')}` : FILTER_URL, {
|
| 50 |
method: 'POST',
|
| 51 |
headers: { 'Content-Type': 'application/json', 'X-App-Token': process.env.API_BEARER_TOKEN },
|
| 52 |
body: JSON.stringify(raw),
|
|
|
|
| 60 |
|
| 61 |
export function registerIServFiltered(app) {
|
| 62 |
app.get('/iserv/health', (req, res) => res.json({ status: 'ok' }));
|
| 63 |
+
app.get('/iserv/freigabe', (req, res) => res.set('Cache-Control', 'no-store').type('html').send(FORM));
|
| 64 |
+
app.post('/iserv/freigabe', express.urlencoded({ extended: false, limit: '4kb' }), async (req, res) => {
|
| 65 |
+
res.set('Cache-Control', 'no-store').type('html');
|
| 66 |
+
const approve = process.env.APPROVE_TOKEN;
|
| 67 |
+
if (approve === process.env.API_BEARER_TOKEN || !sameSecret(req.body?.code, approve)) {
|
| 68 |
+
await new Promise((r) => setTimeout(r, 1000)); // slows guessing
|
| 69 |
+
return res.status(401).send('Nicht freigegeben.');
|
| 70 |
+
}
|
| 71 |
+
const ids = String(req.body.ids || '').split(/[\s,;]+/).filter((i) => /^\d{1,12}-\d{1,3}$/.test(i));
|
| 72 |
+
ids.forEach((id) => releases.set(id, Date.now() + RELEASE_MS));
|
| 73 |
+
res.send(`<meta charset="utf-8"><p>Freigegeben (10 Minuten, einmal): ${ids.join(', ') || 'nichts'}</p>`);
|
| 74 |
+
});
|
| 75 |
app.get('/iserv/tasks', async (req, res) => {
|
| 76 |
res.set('Cache-Control', 'no-store');
|
| 77 |
if ((process.env.API_BEARER_TOKEN || '').length < 16) return res.status(503).json({ error: 'config' }); // fail closed
|
| 78 |
if (!tokenOk(req)) return res.status(401).json({ error: 'unauthorized' });
|
| 79 |
+
const run = () => {
|
| 80 |
+
const now = Date.now();
|
| 81 |
+
const released = [...releases].filter(([, until]) => until > now).map(([id]) => id);
|
| 82 |
+
releases.clear(); // used once, whether or not the request succeeds
|
| 83 |
+
return cleanTasks(req.query.alle === '1', req.query.dateien === '1', released);
|
| 84 |
+
};
|
| 85 |
const job = running.then(run, run);
|
| 86 |
running = job.catch(() => {});
|
| 87 |
const { status, body } = await job;
|
tests/iserv-release.test.mjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import test from 'node:test';
|
| 2 |
+
import assert from 'node:assert/strict';
|
| 3 |
+
import express from 'express';
|
| 4 |
+
import { registerIServFiltered } from '../src/api/iserv-filtered.js';
|
| 5 |
+
|
| 6 |
+
process.env.API_BEARER_TOKEN = 'a'.repeat(20);
|
| 7 |
+
process.env.APPROVE_TOKEN = 'b'.repeat(20);
|
| 8 |
+
const app = express();
|
| 9 |
+
registerIServFiltered(app);
|
| 10 |
+
const server = app.listen(0);
|
| 11 |
+
const base = `http://127.0.0.1:${server.address().port}`;
|
| 12 |
+
const post = (code, ids) => fetch(`${base}/iserv/freigabe`, {
|
| 13 |
+
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
| 14 |
+
body: new URLSearchParams({ code, ids }),
|
| 15 |
+
});
|
| 16 |
+
|
| 17 |
+
test('form is served, wrong code and the API token are refused', async () => {
|
| 18 |
+
assert.match(await (await fetch(`${base}/iserv/freigabe`)).text(), /Freigabe-Code/);
|
| 19 |
+
assert.equal((await post('x'.repeat(20), '1-0')).status, 401);
|
| 20 |
+
assert.equal((await post(process.env.API_BEARER_TOKEN, '1-0')).status, 401);
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
test('right code accepts only well-formed ids and echoes nothing else', async () => {
|
| 24 |
+
const r = await post(process.env.APPROVE_TOKEN, '12-0, <script>, 7-1');
|
| 25 |
+
const t = await r.text();
|
| 26 |
+
assert.equal(r.status, 200);
|
| 27 |
+
assert.match(t, /12-0, 7-1/);
|
| 28 |
+
assert.doesNotMatch(t, /script/);
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
test('no approve token configured: nothing can be released', async () => {
|
| 32 |
+
const saved = process.env.APPROVE_TOKEN;
|
| 33 |
+
delete process.env.APPROVE_TOKEN;
|
| 34 |
+
assert.equal((await post('', '1-0')).status, 401);
|
| 35 |
+
process.env.APPROVE_TOKEN = saved;
|
| 36 |
+
server.close();
|
| 37 |
+
});
|