feat: goctf final
This commit is contained in:
commit
f205b802d5
128 files changed
+37794
No files matched your search
@@ -0,0 +1,4 @@
|
||||
client/node_modules
|
||||
client/dist
|
||||
**/__pycache__
|
||||
**/*.pyc
|
||||
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
||||
FROM node:22-bookworm AS web
|
||||
WORKDIR /web
|
||||
COPY client/package.json ./
|
||||
RUN npm install
|
||||
COPY client/index.html ./index.html
|
||||
COPY client/src/ ./src/
|
||||
RUN npm run build
|
||||
|
||||
FROM debian:bookworm-slim AS wasmtime
|
||||
ARG WASMTIME_VERSION=24.0.0
|
||||
ARG TARGETARCH
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl xz-utils && rm -rf /var/lib/apt/lists/* \
|
||||
&& case "$TARGETARCH" in amd64) WASMTIME_ARCH=x86_64 ;; arm64) WASMTIME_ARCH=aarch64 ;; *) echo "Unsupported architecture: $TARGETARCH" >&2; exit 1 ;; esac \
|
||||
&& curl -fsSL "https://github.com/bytecodealliance/wasmtime/releases/download/v${WASMTIME_VERSION}/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api.tar.xz" -o /tmp/wasmtime.tar.xz \
|
||||
&& tar -xJf /tmp/wasmtime.tar.xz -C /tmp \
|
||||
&& mkdir -p /out/include /out/lib \
|
||||
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/include/. /out/include/ \
|
||||
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/lib/libwasmtime.so* /out/lib/
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake make g++ clang llvm lld libsqlite3-dev nlohmann-json3-dev sqlite3 util-linux \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=wasmtime /out/include/ /usr/local/include/
|
||||
COPY --from=wasmtime /out/lib/ /usr/local/lib/
|
||||
RUN ldconfig
|
||||
WORKDIR /srv/lighthouse
|
||||
COPY server/ ./server/
|
||||
RUN /bin/sh ./server/build.sh
|
||||
COPY --from=web /web/dist ./public/
|
||||
RUN mkdir -p /data /var/log/lighthouse /srv/lighthouse/work \
|
||||
&& chmod 0700 /data \
|
||||
&& chmod 0700 /var/log/lighthouse \
|
||||
&& chmod 0711 /srv/lighthouse/work
|
||||
EXPOSE 8080
|
||||
CMD ["/srv/lighthouse/server/lighthouse"]
|
||||
@@ -0,0 +1,16 @@
|
||||
# Lighthouse: статус кандидата на 25.10.2026
|
||||
|
||||
Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox.
|
||||
|
||||
- L-02: отправка исходника фильтра снова доступна без `X-Queue-Key`, как в исходном API: официальный CHECK вызывает её без заголовка и отвечавший `403` приводил к `DOWN`. Остальные проверки ключа сохранены. Публичная отправка фильтра остаётся риском нагрузки и вытеснения истории ревизий.
|
||||
- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи.
|
||||
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
|
||||
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
|
||||
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
|
||||
- L-06: одновременно работают не более двух компиляций; после исчерпания слотов допускается не более восьми ожидающих запросов и не более пятнадцати секунд ожидания, а лишние запросы получают `429`. Лимит выбран по наблюдаемой очереди: восемь работ при двух слотах и трёхсекундном пределе на compile/listing укладываются примерно в двенадцать секунд, тогда как checker ограничен тридцатью секундами. HTTP pool содержит 32-64 потока и ограниченную очередь 256, чтобы compiler flood не вытеснял health и обычные API-вызовы. Keep-alive и socket timeout уменьшены. `clang` и `llvm-objdump` запускаются с низким CPU priority. Compose ограничивает процесс двумя CPU, 1 GiB памяти и 256 PID и автоматически перезапускает контейнер.
|
||||
|
||||
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` прежнего образа; совместимость публичного вызова восстановлена в `143182a`, который входит в основу этого кандидата. Игровой том локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET.
|
||||
|
||||
**HTTP-парсер:** Dockerfile больше не устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. Lighthouse собирается со сверенным по SHA-256 заголовком upstream `cpp-httplib` 0.53.1 из `server/vendor/`. Эта версия включает исправления [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728), [CVE-2025-53628](https://security-tracker.debian.org/tracker/CVE-2025-53628), [CVE-2025-53629](https://security-tracker.debian.org/tracker/CVE-2025-53629) и [CVE-2026-45352](https://security-tracker.debian.org/tracker/CVE-2026-45352). `set_payload_max_length(32768)` сохранён. Локальная сборка и smoke на одноразовых томах пройдены после переноса данных из прежнего образа; это не доказывает исправность игрового checker или текущую версию на vulnbox до её отдельной выкладки.
|
||||
|
||||
В этом же приватном репозитории находится `sploits/lighthouse/`. Полный clone/pull на vulnbox принесёт и атакующий код. При подготовке выкладки переносите только нужный каталог сервиса; не монтируйте `sploits/` в контейнер и не помещайте его в web root. Для отката сохраняйте тома данных: не используйте `compose down -v`.
|
||||
@@ -0,0 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Lighthouse</title></head>
|
||||
<body><div id="app"></div><script type="module" src="/src/main.js"></script></body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
{"scripts":{"build":"vite build","dev":"vite --host 0.0.0.0"},"dependencies":{"@vitejs/plugin-vue":"latest","vite":"latest","vue":"latest"}}
|
||||
@@ -0,0 +1,69 @@
|
||||
const unbytes = new TextDecoder();
|
||||
|
||||
function g(a, b, carry) {
|
||||
const value = (a + b + carry) & 255;
|
||||
return ((value << 2) | (value >>> 6)) & 255;
|
||||
}
|
||||
|
||||
function f(x) {
|
||||
const a = x >>> 24, b = (x >>> 16) & 255, c = (x >>> 8) & 255, d = x & 255;
|
||||
const y1 = g(a ^ b, c ^ d, 1);
|
||||
const y2 = g(c ^ d, y1, 0);
|
||||
return (g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1)) >>> 0;
|
||||
}
|
||||
|
||||
function fk(x, y) {
|
||||
const a = x >>> 24, b = (x >>> 16) & 255, c = (x >>> 8) & 255, d = x & 255;
|
||||
const u = y >>> 24, v = (y >>> 16) & 255, w = (y >>> 8) & 255, z = y & 255;
|
||||
const middle1 = g(a ^ b, (c ^ d) ^ u, 1);
|
||||
const middle2 = g(c ^ d, middle1 ^ v, 0);
|
||||
return (g(a, middle1 ^ w, 0) << 24 | middle1 << 16 | middle2 << 8 | g(d, middle2 ^ z, 1)) >>> 0;
|
||||
}
|
||||
|
||||
function block(left, right, keys) {
|
||||
let x = left, y = (right ^ left) >>> 0;
|
||||
for (let round = 3; round >= 1; round--) {
|
||||
const next = (x ^ f(y ^ keys[round])) >>> 0;
|
||||
x = y;
|
||||
y = next;
|
||||
}
|
||||
const initial = (x ^ f(y ^ keys[0])) >>> 0;
|
||||
return [(initial ^ keys[4]) >>> 0, (initial ^ y ^ keys[5]) >>> 0];
|
||||
}
|
||||
|
||||
export function decrypt(secret, cipher) {
|
||||
if (!/^[0-9a-f]+$/.test(cipher) || cipher.length % 16 || !/^[0-9a-f]{48}$/.test(secret))
|
||||
throw Error('Invalid message');
|
||||
const material = Array.from({ length: 6 }, (_, i) => parseInt(secret.slice(i * 8, i * 8 + 8), 16) >>> 0);
|
||||
let left = material[0], right = material[1], previous = material[5];
|
||||
const words = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const next = fk(left, (right ^ previous ^ material[i]) >>> 0);
|
||||
previous = left;
|
||||
left = right;
|
||||
right = next;
|
||||
words.push(next >>> 16, next & 65535);
|
||||
}
|
||||
const outputLeft = ((words[8] << 16 | words[9]) ^ material[2]) >>> 0;
|
||||
const outputRight = ((words[10] << 16 | words[11]) ^ material[3]) >>> 0;
|
||||
const keys = Array.from({ length: 4 }, (_, i) =>
|
||||
(((words[i] >>> 8) << 16 | (words[i] & 255) << 8) ^ outputLeft ^
|
||||
(i % 2 ? outputRight : 0) ^ material[i]) >>> 0);
|
||||
keys.push(((words[4] << 16 | words[5]) ^ outputLeft ^ outputRight ^ material[4]) >>> 0,
|
||||
((words[6] << 16 | words[7]) ^ outputRight ^ material[5]) >>> 0);
|
||||
const output = new Uint8Array(cipher.length / 2);
|
||||
for (let offset = 0; offset < output.length; offset += 8) {
|
||||
const [left, right] = block(
|
||||
parseInt(cipher.slice(offset * 2, offset * 2 + 8), 16) >>> 0,
|
||||
parseInt(cipher.slice(offset * 2 + 8, offset * 2 + 16), 16) >>> 0, keys
|
||||
);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
output[offset + i] = left >>> (24 - 8 * i);
|
||||
output[offset + 4 + i] = right >>> (24 - 8 * i);
|
||||
}
|
||||
}
|
||||
const padding = output[output.length - 1];
|
||||
if (padding < 1 || padding > 8 || !output.slice(-padding).every(byte => byte === padding))
|
||||
throw Error('Invalid message padding');
|
||||
return unbytes.decode(output.slice(0, -padding));
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { createApp, ref } from 'vue/dist/vue.esm-bundler.js';
|
||||
import { decrypt } from './crypto.js';
|
||||
import './style.css';
|
||||
|
||||
const textBytes = new TextEncoder();
|
||||
|
||||
createApp({
|
||||
setup() {
|
||||
const queue = ref(''), key = ref(''), pass = ref(''), recipient = ref('');
|
||||
const queueLabel = ref('untitled'), retention = ref(3600);
|
||||
const topic = ref('inbox'), delay = ref(0), text = ref('');
|
||||
const source = ref('int filter(int length) {\n return length <= 4096;\n}');
|
||||
const filterLabel = ref('unnamed'), revision = ref('');
|
||||
const selectedFilter = ref(null);
|
||||
const received = ref([]), filters = ref([]), nextAfter = ref(0), pageShowRead = ref(false);
|
||||
const state = ref(null), view = ref('messages'), showRead = ref(false);
|
||||
const feedback = ref({}), compiler = ref(''), listing = ref('');
|
||||
const path = suffix => '/api/queues/' + queue.value + suffix;
|
||||
const credentials = () => queue.value + ':' + key.value;
|
||||
|
||||
async function api(url, options = {}, accepted = []) {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: { 'Content-Type': 'application/json', ...options.headers }
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok && !accepted.includes(response.status)) throw Error(body.error || body.compiler || 'Request failed');
|
||||
return body;
|
||||
}
|
||||
|
||||
async function action(name, work) {
|
||||
feedback.value[name] = null;
|
||||
try {
|
||||
const result = await work();
|
||||
feedback.value[name] = typeof result === 'string' ? { kind: 'ok', text: result } : result;
|
||||
}
|
||||
catch (problem) { feedback.value[name] = { kind: 'error', text: problem.message }; }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
state.value = await api(path(''));
|
||||
}
|
||||
const headers = () => ({ 'X-Queue-Key': key.value });
|
||||
|
||||
const create = () => action('access', async () => {
|
||||
const created = await api('/api/queues', {
|
||||
method: 'POST', body: JSON.stringify({ label: queueLabel.value, retention_seconds: Number(retention.value) })
|
||||
});
|
||||
queue.value = created.id;
|
||||
key.value = created.read_key;
|
||||
pass.value = credentials();
|
||||
state.value = created;
|
||||
recipient.value = created.id;
|
||||
received.value = [];
|
||||
nextAfter.value = 0;
|
||||
filters.value = [];
|
||||
selectedFilter.value = null;
|
||||
view.value = 'messages';
|
||||
return 'Mailbox created. Save your access pass.';
|
||||
});
|
||||
const open = () => action('open', async () => {
|
||||
const [id, secret, extra] = pass.value.trim().split(':');
|
||||
if (!id || !secret || extra) throw Error('Enter a mailbox access pass in the form UUID:read_key.');
|
||||
const info = await api('/api/queues/' + id);
|
||||
await api('/api/queues/' + id + '/messages?show_read=true', { headers: { 'X-Queue-Key': secret } });
|
||||
queue.value = id;
|
||||
key.value = secret;
|
||||
state.value = info;
|
||||
recipient.value = id;
|
||||
received.value = [];
|
||||
nextAfter.value = 0;
|
||||
filters.value = [];
|
||||
selectedFilter.value = null;
|
||||
view.value = 'messages';
|
||||
feedback.value.access = { kind: 'ok', text: 'Mailbox opened.' };
|
||||
});
|
||||
const leave = () => {
|
||||
queue.value = '';
|
||||
key.value = '';
|
||||
pass.value = '';
|
||||
state.value = null;
|
||||
received.value = [];
|
||||
nextAfter.value = 0;
|
||||
filters.value = [];
|
||||
selectedFilter.value = null;
|
||||
compiler.value = '';
|
||||
listing.value = '';
|
||||
feedback.value = {};
|
||||
feedback.value.open = { kind: 'ok', text: 'Mailbox closed.' };
|
||||
};
|
||||
const send = () => action('send', async () => {
|
||||
const id = recipient.value.trim();
|
||||
if (!text.value) throw Error('Write a message first.');
|
||||
const raw = textBytes.encode(text.value);
|
||||
if (raw.length > 4096) throw Error('Messages must be at most 4096 bytes.');
|
||||
await api('/api/queues/' + id + '/messages', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
message: btoa(Array.from(raw, byte => String.fromCharCode(byte)).join('')),
|
||||
topic: topic.value,
|
||||
delay_ms: Number(delay.value)
|
||||
})
|
||||
});
|
||||
text.value = '';
|
||||
if (state.value) await refresh();
|
||||
return 'Message sent.';
|
||||
});
|
||||
const receive = () => action('receive', async () => {
|
||||
await refresh();
|
||||
const result = await api(path('/messages' + (showRead.value ? '?show_read=true' : '')), { headers: headers() });
|
||||
pageShowRead.value = showRead.value;
|
||||
nextAfter.value = result.has_more ? result.next_after : 0;
|
||||
received.value = result.messages.map(message => {
|
||||
try {
|
||||
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
|
||||
} catch {
|
||||
return { id: message.id, topic: message.topic, text: 'Cannot open this message.' };
|
||||
}
|
||||
});
|
||||
await refresh();
|
||||
return result.messages.length ? result.messages.length + ' message(s) displayed.' : 'No messages to display.';
|
||||
});
|
||||
const loadMore = () => action('receive', async () => {
|
||||
if (!nextAfter.value) return 'No more messages.';
|
||||
const suffix = '/messages?after_id=' + nextAfter.value + (pageShowRead.value ? '&show_read=true' : '');
|
||||
const result = await api(path(suffix), { headers: headers() });
|
||||
nextAfter.value = result.has_more ? result.next_after : 0;
|
||||
received.value.push(...result.messages.map(message => {
|
||||
try {
|
||||
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
|
||||
} catch {
|
||||
return { id: message.id, topic: message.topic, text: 'Cannot open this message.' };
|
||||
}
|
||||
}));
|
||||
await refresh();
|
||||
return result.messages.length + ' more message(s) displayed.';
|
||||
});
|
||||
const loadFilters = () => action('refreshFilters', async () => {
|
||||
filters.value = (await api(path('/filters'))).filters;
|
||||
return 'Revision list updated.';
|
||||
});
|
||||
const selectFilter = filter => action('selectFilter', async () => {
|
||||
const details = await api(path('/filters/' + filter.revision), { headers: headers() });
|
||||
revision.value = details.revision;
|
||||
selectedFilter.value = details;
|
||||
return 'Revision #' + details.revision + ' selected.';
|
||||
});
|
||||
const newDraft = () => {
|
||||
selectedFilter.value = null;
|
||||
revision.value = '';
|
||||
compiler.value = '';
|
||||
listing.value = '';
|
||||
feedback.value.compile = null;
|
||||
feedback.value.selectFilter = { kind: 'ok', text: 'Draft editor ready.' };
|
||||
};
|
||||
const install = () => action('compile', async () => {
|
||||
compiler.value = '';
|
||||
listing.value = '';
|
||||
const result = await api(path('/filter'), {
|
||||
method: 'POST', headers: headers(), body: JSON.stringify({ source: source.value, label: filterLabel.value })
|
||||
}, [422]);
|
||||
compiler.value = result.compiler || '';
|
||||
listing.value = result.listing || '';
|
||||
filters.value = (await api(path('/filters'))).filters;
|
||||
if (!result.ok) {
|
||||
return { kind: 'error', text: 'Revision #' + result.revision + ' rejected. See compiler output below.' };
|
||||
}
|
||||
return 'Revision #' + result.revision + ' ready. Select it to activate.';
|
||||
});
|
||||
const draftFrom = () => {
|
||||
if (!selectedFilter.value?.source) return;
|
||||
source.value = selectedFilter.value.source;
|
||||
filterLabel.value = selectedFilter.value.label;
|
||||
newDraft();
|
||||
};
|
||||
const activate = () => action('activate', async () => {
|
||||
await api(path('/filters/' + revision.value + '/activate'), {
|
||||
method: 'POST', headers: headers()
|
||||
});
|
||||
filters.value = (await api(path('/filters'))).filters;
|
||||
if (selectedFilter.value) selectedFilter.value.active = true;
|
||||
await refresh();
|
||||
return 'Revision #' + revision.value + ' activated.';
|
||||
});
|
||||
|
||||
return {
|
||||
queue, pass, recipient, queueLabel, retention, topic, delay, text,
|
||||
source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead, nextAfter,
|
||||
feedback, compiler, listing, credentials,
|
||||
create, open, leave, send, receive, loadMore, loadFilters, selectFilter, newDraft, draftFrom, install, activate
|
||||
};
|
||||
},
|
||||
template: `
|
||||
<main>
|
||||
<header class="masthead">
|
||||
<div class="brand-mark">✦</div>
|
||||
<div><p class="eyebrow">LIGHTHOUSE / MAIL</p><h1>Lighthouse</h1><p>A quiet place for messages with a programmable door.</p></div>
|
||||
</header>
|
||||
<div v-if="!state" class="entry-grid">
|
||||
<section class="panel">
|
||||
<p class="eyebrow">NEW MAILBOX</p><h2>Create a mailbox</h2>
|
||||
<p class="muted">We generate the address and private access key for you.</p>
|
||||
<label>Mailbox name<input v-model="queueLabel" maxlength="48" autocomplete="off"></label>
|
||||
<label>Keep messages for (seconds)<input v-model.number="retention" type="number" min="60" max="604800"></label>
|
||||
<div class="actions"><button @click="create">Create mailbox</button><span v-if="feedback.access" class="action-feedback" :class="feedback.access.kind" :role="feedback.access.kind === 'error' ? 'alert' : 'status'">{{ feedback.access.text }}</span></div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<p class="eyebrow">RETURNING</p><h2>Open your mailbox</h2>
|
||||
<p class="muted">Use the access pass you received when you created it.</p>
|
||||
<label>Access pass<input v-model="pass" placeholder="UUID:read_key" spellcheck="false" autocomplete="off" @keyup.enter="open"></label>
|
||||
<div class="actions"><button class="secondary" @click="open">Open mailbox</button><span v-if="feedback.open" class="action-feedback" :class="feedback.open.kind" :role="feedback.open.kind === 'error' ? 'alert' : 'status'">{{ feedback.open.text }}</span></div>
|
||||
</section>
|
||||
<section class="panel send-panel">
|
||||
<p class="eyebrow">PUBLIC DELIVERY</p><h2>Send a message</h2>
|
||||
<p class="muted">No access pass needed. All you need is the recipient's mailbox address.</p>
|
||||
<label>Mailbox address<input v-model="recipient" spellcheck="false" placeholder="Recipient UUID"></label>
|
||||
<div class="fields twin"><label>Topic<input v-model="topic"></label><label>Delay · ms<input v-model.number="delay" type="number" min="0" max="60000"></label></div>
|
||||
<label>Message<textarea v-model="text" placeholder="Write a message..."></textarea></label>
|
||||
<div class="actions"><button @click="send">Send message</button><span v-if="feedback.send" class="action-feedback" :class="feedback.send.kind" :role="feedback.send.kind === 'error' ? 'alert' : 'status'">{{ feedback.send.text }}</span></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<section class="panel identity-bar">
|
||||
<div><p class="eyebrow">YOUR MAILBOX</p><h2>{{ state.label }}</h2><p class="mono">{{ queue }}</p></div>
|
||||
<div class="identity-actions"><span>{{ state.ready_count ?? 0 }} unread / {{ state.stored_count ?? 0 }} stored</span><button class="secondary" @click="leave">Close mailbox</button></div>
|
||||
<details class="access"><summary>Access pass · keep private</summary><code>{{ credentials() }}</code></details>
|
||||
<span v-if="feedback.access" class="action-feedback" :class="feedback.access.kind" :role="feedback.access.kind === 'error' ? 'alert' : 'status'">{{ feedback.access.text }}</span>
|
||||
</section>
|
||||
<nav class="tabs" aria-label="Mailbox pages">
|
||||
<button :class="{ current: view === 'messages' }" @click="view = 'messages'">Messages</button>
|
||||
<button :class="{ current: view === 'filters' }" @click="view = 'filters'; loadFilters()">Door filters</button>
|
||||
</nav>
|
||||
|
||||
<div v-if="view === 'messages'" class="entry-grid">
|
||||
<section class="panel">
|
||||
<p class="eyebrow">INBOX</p><h2>Messages</h2>
|
||||
<p class="muted">Reading collects new messages. They remain available in history until they expire.</p>
|
||||
<div class="actions"><button @click="receive">Read new messages</button><span v-if="feedback.receive" class="action-feedback" :class="feedback.receive.kind" :role="feedback.receive.kind === 'error' ? 'alert' : 'status'">{{ feedback.receive.text }}</span><details class="read-options"><summary>Options</summary><label><input type="checkbox" v-model="showRead"> Include already read</label></details></div>
|
||||
<div class="inbox" v-if="received.length"><article v-for="message in received" :key="message.id"><small>#{{ message.id }} · {{ message.topic }}</small><p>{{ message.text }}</p></article></div>
|
||||
<p v-if="!received.length" class="muted empty">No messages displayed.</p>
|
||||
<button v-if="nextAfter" class="secondary" @click="loadMore">Load more messages</button>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<p class="eyebrow">OUTBOX</p><h2>Send a message</h2>
|
||||
<p class="muted">Anyone with a mailbox address can send. The service seals the message for its reader.</p>
|
||||
<label>To · public mailbox address<input v-model="recipient" spellcheck="false"></label>
|
||||
<div class="fields twin"><label>Topic<input v-model="topic"></label><label>Delay · ms<input v-model.number="delay" type="number" min="0" max="60000"></label></div>
|
||||
<label>Message<textarea v-model="text" placeholder="Write a message..."></textarea></label>
|
||||
<div class="actions"><button @click="send">Send message</button><span v-if="feedback.send" class="action-feedback" :class="feedback.send.kind" :role="feedback.send.kind === 'error' ? 'alert' : 'status'">{{ feedback.send.text }}</span></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-else class="entry-grid filters-grid">
|
||||
<section class="panel">
|
||||
<template v-if="selectedFilter">
|
||||
<p class="eyebrow">REVISION #{{ selectedFilter.revision }}</p><h2>{{ selectedFilter.label }}</h2>
|
||||
<p class="muted">{{ selectedFilter.state }}{{ selectedFilter.active ? ' · active' : '' }} · {{ selectedFilter.created_at }}</p>
|
||||
<label>C source<textarea class="source" :value="selectedFilter.source" readonly placeholder="Source not saved for this revision"></textarea></label>
|
||||
<pre v-if="selectedFilter.compiler">{{ selectedFilter.compiler }}</pre>
|
||||
<details v-if="selectedFilter.listing"><summary>Instruction listing</summary><pre>{{ selectedFilter.listing }}</pre></details>
|
||||
<div class="actions"><button class="secondary" @click="newDraft">Compile new draft</button><button v-if="selectedFilter.source" class="secondary" @click="draftFrom">Use source as draft</button></div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="eyebrow">FILTER EDITOR</p><h2>Compile new draft</h2>
|
||||
<p class="muted">A C function decides which messages enter. Compile a draft before activating it.</p>
|
||||
<label>Draft name<input v-model="filterLabel" maxlength="48"></label>
|
||||
<label>C source<textarea class="source" v-model="source" spellcheck="false"></textarea></label>
|
||||
<div class="actions"><button @click="install">Compile draft</button><span v-if="feedback.compile" class="action-feedback" :class="feedback.compile.kind" :role="feedback.compile.kind === 'error' ? 'alert' : 'status'">{{ feedback.compile.text }}</span></div>
|
||||
<pre v-if="compiler" class="diagnostic">{{ compiler }}</pre>
|
||||
<details v-if="listing"><summary>Instruction listing</summary><pre>{{ listing }}</pre></details>
|
||||
</template>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<p class="eyebrow">FILTER HISTORY</p><h2>Revisions</h2>
|
||||
<p class="muted">Only one revision is active. Select a ready draft to make it the front door.</p>
|
||||
<div class="actions"><button class="secondary" @click="loadFilters">Refresh</button><span v-if="feedback.refreshFilters" class="action-feedback" :class="feedback.refreshFilters.kind" :role="feedback.refreshFilters.kind === 'error' ? 'alert' : 'status'">{{ feedback.refreshFilters.text }}</span></div>
|
||||
<div class="actions"><button :disabled="!selectedFilter || selectedFilter.state !== 'ready' || selectedFilter.active" @click="activate">Activate selected</button><span v-if="feedback.activate" class="action-feedback" :class="feedback.activate.kind" :role="feedback.activate.kind === 'error' ? 'alert' : 'status'">{{ feedback.activate.text }}</span></div>
|
||||
<span v-if="feedback.selectFilter" class="action-feedback" :class="feedback.selectFilter.kind" :role="feedback.selectFilter.kind === 'error' ? 'alert' : 'status'">{{ feedback.selectFilter.text }}</span>
|
||||
<ul class="history"><li v-for="filter in filters" :key="filter.revision"><button class="revision" :class="{ selected: selectedFilter?.revision === filter.revision }" @click="selectFilter(filter)"><span>#{{ filter.revision }} · {{ filter.label }}</span><span>{{ filter.active ? 'active' : filter.state }}</span></button></li></ul>
|
||||
<p v-if="!filters.length" class="muted empty">No revisions yet.</p>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<footer>LIGHTHOUSE / EVERY MESSAGE FINDS ITS SHORE</footer>
|
||||
</main>
|
||||
`
|
||||
}).mount('#app');
|
||||
@@ -0,0 +1,48 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@400;500;600;700&display=swap');
|
||||
|
||||
:root{font-family:'DM Sans',system-ui,sans-serif;color:#e8e9de;background:#101c23;font-synthesis:none}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;min-height:100vh;background:radial-gradient(ellipse at 85% 0%,#28414b 0%,transparent 45%),#101c23}
|
||||
main{max-width:1060px;margin:auto;padding:48px 28px 60px}
|
||||
.masthead{display:flex;align-items:center;gap:20px;margin-bottom:38px}
|
||||
.brand-mark{width:62px;height:62px;flex:none;display:grid;place-items:center;border:1px solid #e7ad67;border-radius:50%;color:#f4bc77;font-size:36px;box-shadow:0 0 36px #e7ad6733}
|
||||
.masthead h1{font-size:clamp(2rem,5vw,3.25rem);font-weight:600;letter-spacing:-.06em;margin:0}
|
||||
.masthead p:not(.eyebrow){margin:3px 0 0;color:#a6b9b9}
|
||||
.eyebrow{font:500 11px 'DM Mono',monospace;letter-spacing:.18em;color:#edb375;margin:0 0 10px}
|
||||
.panel{background:#192a32;border:1px solid #36505a;border-radius:12px;padding:28px;box-shadow:0 14px 40px #07111840;min-width:0}
|
||||
.entry-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;align-items:start}
|
||||
.send-panel{grid-column:1/-1;max-width:650px;width:100%;justify-self:center}
|
||||
h2{margin:0;font-weight:600;font-size:26px;letter-spacing:-.04em}
|
||||
.muted{color:#a7bbbb;font-size:13px;line-height:1.6;margin:12px 0 24px}
|
||||
label{display:block;font-size:12px;font-weight:600;color:#b5c7c5;letter-spacing:.03em;margin:18px 0}
|
||||
input,textarea{display:block;width:100%;margin-top:9px;padding:12px 13px;border:1px solid #49626b;border-radius:6px;background:#102028;color:#f5f3e8;font:14px 'DM Sans',sans-serif;outline:none}
|
||||
input:focus,textarea:focus{border-color:#f1b675;box-shadow:0 0 0 3px #f1b67522}
|
||||
input::placeholder,textarea::placeholder{color:#749093}
|
||||
textarea{height:118px;resize:vertical;line-height:1.5}
|
||||
.source{height:220px;font:13px/1.6 'DM Mono',monospace}
|
||||
.fields{display:grid;gap:14px}.fields label{margin-top:0}.twin{grid-template-columns:1fr 1fr}
|
||||
button{border:1px solid #e9ac68;border-radius:6px;background:#e9ac68;color:#19252a;padding:11px 16px;font:600 13px 'DM Sans',sans-serif;cursor:pointer;transition:background .15s,border-color .15s}
|
||||
button:hover:not(:disabled){background:#ffcb8e;border-color:#ffcb8e}
|
||||
button:disabled{opacity:.5;cursor:not-allowed}
|
||||
.secondary{background:transparent;color:#f1c494;border-color:#866f58}.secondary:hover:not(:disabled){background:#2c3c40}
|
||||
.actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:18px 0}
|
||||
.action-feedback{font-size:13px;line-height:1.45}.action-feedback.ok{color:#bce5ca}.action-feedback.error{color:#ffb7a7}.diagnostic{margin-top:12px}
|
||||
.identity-bar{display:grid;grid-template-columns:1fr auto;gap:14px 30px;align-items:center;margin-bottom:22px}
|
||||
.identity-bar .mono{font:12px 'DM Mono',monospace;color:#aec1bf;overflow-wrap:anywhere;margin:10px 0 0}
|
||||
.identity-actions{display:flex;align-items:center;gap:16px;color:#a7bbbb;font:12px 'DM Mono',monospace}
|
||||
.access{grid-column:1/-1;border-top:1px solid #344a53;padding-top:15px;color:#a7bbbb;font-size:12px}
|
||||
.access code{display:block;margin-top:12px;padding:12px;background:#102028;border-radius:6px;color:#f3c58e;font:12px 'DM Mono',monospace;overflow-wrap:anywhere}
|
||||
summary{cursor:pointer;color:#efba7e;font-size:13px}
|
||||
.tabs{display:flex;gap:8px;margin:0 0 18px;border-bottom:1px solid #36505a;padding-bottom:12px}
|
||||
.tabs button{background:transparent;border-color:transparent;color:#abc0c0}.tabs button.current{color:#1b2930;background:#e9ac68;border-color:#e9ac68}
|
||||
.read-options{font-size:12px}.read-options summary{color:#8da9a9}.read-options label{display:flex;align-items:center;gap:9px;margin:12px 0 0;font-size:12px;font-weight:400}.read-options input{width:auto;margin:0;accent-color:#e9ac68}
|
||||
.inbox{max-height:450px;overflow:auto;margin-top:22px}.inbox article{background:#14252d;border:1px solid #324a54;border-radius:6px;padding:12px 14px;margin-bottom:8px;overflow-wrap:anywhere}.inbox article p{margin:8px 0 0}.inbox small{color:#e4b47f;font:11px 'DM Mono',monospace}
|
||||
.empty{margin-top:24px}
|
||||
pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#102028;border:1px solid #344a53;padding:15px;border-radius:6px;font:11px/1.55 'DM Mono',monospace;max-height:360px;overflow:auto}
|
||||
details pre{margin-top:12px}
|
||||
.history{list-style:none;padding:0;margin:18px 0 0}.history li{margin-bottom:8px}
|
||||
.revision{width:100%;display:flex;justify-content:space-between;text-align:left;gap:12px;background:#102028;border:1px solid #344a53;color:#e9eadd;font:12px 'DM Mono',monospace}.revision span:last-child{color:#e9ac68}.revision.selected{border-color:#e9ac68}
|
||||
.alert,.notice{padding:14px 18px;border-radius:6px;margin:0 0 18px}.alert{background:#502d32;border:1px solid #b66d70;color:#ffdfd6}.notice{background:#1e3a35;border:1px solid #588f75;color:#c6e8d0}
|
||||
footer{text-align:center;color:#748b8b;font:10px 'DM Mono',monospace;letter-spacing:.14em;margin-top:42px}
|
||||
@media(max-width:780px){.entry-grid{grid-template-columns:1fr}.identity-bar{grid-template-columns:1fr}.identity-actions{justify-content:space-between}}
|
||||
@media(max-width:560px){main{padding:26px 15px 45px}.masthead{gap:14px;margin-bottom:26px}.brand-mark{width:48px;height:48px;font-size:29px}.panel{padding:20px}.twin{grid-template-columns:1fr}.tabs button{flex:1}}
|
||||
@@ -0,0 +1,19 @@
|
||||
name: lighthouse
|
||||
|
||||
services:
|
||||
lighthouse:
|
||||
restart: unless-stopped
|
||||
build: .
|
||||
pids_limit: 256
|
||||
mem_limit: 1g
|
||||
cpus: 2.0
|
||||
ports:
|
||||
- "8085:8080"
|
||||
volumes:
|
||||
- lighthouse-data:/data
|
||||
- lighthouse-builds:/srv/lighthouse/work
|
||||
- lighthouse-journal:/var/log/lighthouse
|
||||
volumes:
|
||||
lighthouse-data:
|
||||
lighthouse-builds:
|
||||
lighthouse-journal:
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(lighthouse LANGUAGES CXX)
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
add_executable(lighthouse main.cpp)
|
||||
target_include_directories(lighthouse PRIVATE vendor)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
target_link_libraries(lighthouse PRIVATE SQLite::SQLite3 pthread)
|
||||
find_library(WASMTIME_LIBRARY NAMES wasmtime REQUIRED)
|
||||
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cmake -S /srv/lighthouse/server -B /tmp/lighthouse-build
|
||||
cmake --build /tmp/lighthouse-build -j"$(nproc)"
|
||||
install -m 0755 /tmp/lighthouse-build/lighthouse /srv/lighthouse/server/lighthouse
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace chronicle {
|
||||
|
||||
inline void append(const std::string& created_at, const std::string& queue,
|
||||
const std::string& topic, const std::string& cipher, const std::string& instant) {
|
||||
static std::mutex lock;
|
||||
std::lock_guard guard(lock);
|
||||
auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10);
|
||||
std::filesystem::create_directories(directory);
|
||||
if (chmod(directory.c_str(), 0700) != 0)
|
||||
throw std::runtime_error("cannot secure journal directory");
|
||||
auto path = directory / (queue + ".log");
|
||||
std::ofstream file(path, std::ios::app);
|
||||
if (!file || chmod(path.c_str(), 0600) != 0)
|
||||
throw std::runtime_error("cannot open journal");
|
||||
const auto line = instant + " queue=" + queue + " topic=" + topic + " ciphertext=" + cipher + "\n";
|
||||
const auto position = file.tellp();
|
||||
if (position < 0) throw std::runtime_error("cannot size journal");
|
||||
constexpr std::uintmax_t max_journal_bytes = 512 * 1024;
|
||||
if (static_cast<std::uintmax_t>(position) + line.size() > max_journal_bytes) return;
|
||||
file << line;
|
||||
file.close();
|
||||
if (!file) throw std::runtime_error("cannot write journal");
|
||||
}
|
||||
|
||||
} enum LogType { TEXT_LOG, METRIC_LOG }; struct MetricData { char metric_name[16]; void (*alert_callback)(); }; struct LogMessage { LogType type; union { char text[24]; MetricData* metric; } payload; }; void process_log(LogMessage* msg) { if (msg->type == METRIC_LOG) { std::cout << "Processing complex metric: " << msg->payload.metric->metric_name << std::endl; msg->payload.metric->alert_callback(); } else { std::cout << "Standard Log: " << msg->payload.text << std::endl; }}
|
||||
@@ -0,0 +1,211 @@
|
||||
#pragma once
|
||||
|
||||
#include "legacy.hpp"
|
||||
#include "recipe.hpp"
|
||||
#include "util.hpp"
|
||||
#include <wasmtime.h>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <pwd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace filters {
|
||||
namespace fs = std::filesystem;
|
||||
inline constexpr auto work_root = "/srv/lighthouse/work";
|
||||
struct Busy : std::runtime_error { Busy() : std::runtime_error("filter worker busy") {} };
|
||||
|
||||
class Slots {
|
||||
std::mutex lock_;
|
||||
std::condition_variable room_;
|
||||
int held_ = 0;
|
||||
int waiting_ = 0;
|
||||
int limit_;
|
||||
public:
|
||||
explicit Slots(int limit) : limit_(limit) {}
|
||||
void acquire() {
|
||||
std::unique_lock guard(lock_);
|
||||
if (held_ >= limit_) {
|
||||
if (waiting_ >= 8) throw Busy();
|
||||
++waiting_;
|
||||
bool available = room_.wait_for(guard, std::chrono::seconds(15), [&] { return held_ < limit_; });
|
||||
--waiting_;
|
||||
if (!available) throw Busy();
|
||||
}
|
||||
++held_;
|
||||
}
|
||||
void release() {
|
||||
std::lock_guard guard(lock_);
|
||||
--held_;
|
||||
room_.notify_one();
|
||||
}
|
||||
};
|
||||
|
||||
class Slot {
|
||||
Slots& slots_;
|
||||
public:
|
||||
explicit Slot(Slots& slots) : slots_(slots) { slots_.acquire(); }
|
||||
~Slot() { slots_.release(); }
|
||||
Slot(const Slot&) = delete;
|
||||
Slot& operator=(const Slot&) = delete;
|
||||
};
|
||||
|
||||
struct Artifact {
|
||||
bool ready = false;
|
||||
std::string path;
|
||||
std::string diagnostic;
|
||||
std::string listing;
|
||||
};
|
||||
|
||||
inline void write_file(const fs::path& path, const std::string& bytes) {
|
||||
std::ofstream file(path, std::ios::binary);
|
||||
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
|
||||
file.close();
|
||||
if (!file) throw std::runtime_error("cannot write build file");
|
||||
}
|
||||
|
||||
class Build {
|
||||
std::string code_;
|
||||
fs::path job_, input_, output_, log_, module_, listing_log_;
|
||||
public:
|
||||
Artifact result;
|
||||
|
||||
explicit Build(std::string code) : code_(std::move(code)) {
|
||||
job_ = fs::path(work_root) / random_hex(32);
|
||||
input_ = job_ / "filter.c";
|
||||
output_ = job_ / "out";
|
||||
log_ = job_ / "compiler.log";
|
||||
module_ = output_ / "filter.wasm";
|
||||
listing_log_ = job_ / "listing.log";
|
||||
}
|
||||
~Build() {
|
||||
std::error_code error;
|
||||
if (!result.ready) fs::remove_all(job_, error);
|
||||
else {
|
||||
fs::remove_all(output_, error);
|
||||
fs::remove(input_, error);
|
||||
fs::remove(log_, error);
|
||||
fs::remove(listing_log_, error);
|
||||
}
|
||||
}
|
||||
|
||||
void source() {
|
||||
if (!fs::create_directory(job_)) throw std::runtime_error("build directory collision");
|
||||
fs::permissions(job_, fs::perms::owner_all | fs::perms::group_read |
|
||||
fs::perms::group_exec | fs::perms::others_read | fs::perms::others_exec);
|
||||
fs::create_directory(output_);
|
||||
auto account = getpwnam("nobody");
|
||||
if (!account || chown(output_.c_str(), account->pw_uid, account->pw_gid) ||
|
||||
chmod(output_.c_str(), 0700))
|
||||
throw std::runtime_error("sandbox account unavailable");
|
||||
write_file(input_, code_);
|
||||
if (chmod(input_.c_str(), 0444)) throw std::runtime_error("cannot publish source");
|
||||
}
|
||||
|
||||
bool cc() {
|
||||
int status = legacy::system({
|
||||
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
|
||||
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
|
||||
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||
"/usr/bin/clang", "--target=wasm32-unknown-unknown",
|
||||
"-g", "-O0", "-nostdlib", "-fno-crash-diagnostics", "-fdebug-compilation-dir=.",
|
||||
"-ffile-prefix-map=" + job_.string() + "=.",
|
||||
"-fdebug-prefix-map=" + job_.string() + "=.",
|
||||
"-Wl,--threads=1", "-Wl,--no-entry", "-Wl,--export=filter",
|
||||
"-o", module_.string(), input_.string()
|
||||
}, log_.string());
|
||||
result.diagnostic = legacy::gets(log_.string());
|
||||
std::error_code error;
|
||||
if (status != 0 || !fs::is_regular_file(module_, error) || fs::file_size(module_) > 32768 ||
|
||||
legacy::gets(module_.string(), 8) != std::string("\0asm\1\0\0\0", 8)) {
|
||||
if (result.diagnostic.empty()) result.diagnostic = "compiler failed";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void listing() {
|
||||
auto artifact = job_ / "filter.wasm";
|
||||
fs::copy_file(module_, artifact);
|
||||
result.path = artifact.string();
|
||||
int status = legacy::system({
|
||||
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
|
||||
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
|
||||
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||
"/usr/bin/llvm-objdump", "-S", result.path
|
||||
}, listing_log_.string());
|
||||
result.listing = legacy::gets(listing_log_.string(), 8192);
|
||||
if (status != 0 && result.listing.empty()) result.listing = "listing unavailable";
|
||||
result.ready = true;
|
||||
}
|
||||
};
|
||||
|
||||
inline Artifact compile(const std::string& source) {
|
||||
static Slots slots(2);
|
||||
Slot slot(slots);
|
||||
Build build(source);
|
||||
recipe::run(recipe::filter, build);
|
||||
return build.result;
|
||||
}
|
||||
|
||||
inline bool accepts(const std::string& wasm, size_t length) {
|
||||
if (wasm.empty()) return true;
|
||||
static Slots slots(4);
|
||||
Slot slot(slots);
|
||||
using Engine = std::unique_ptr<wasm_engine_t, decltype(&wasm_engine_delete)>;
|
||||
static Engine engine([] {
|
||||
auto config = wasm_config_new();
|
||||
wasmtime_config_consume_fuel_set(config, true);
|
||||
wasmtime_config_max_wasm_stack_set(config, 64 * 1024);
|
||||
return wasm_engine_new_with_config(config);
|
||||
}(), wasm_engine_delete);
|
||||
using Store = std::unique_ptr<wasmtime_store_t, decltype(&wasmtime_store_delete)>;
|
||||
using Module = std::unique_ptr<wasmtime_module_t, decltype(&wasmtime_module_delete)>;
|
||||
using Error = std::unique_ptr<wasmtime_error_t, decltype(&wasmtime_error_delete)>;
|
||||
using Trap = std::unique_ptr<wasm_trap_t, decltype(&wasm_trap_delete)>;
|
||||
struct Cache {
|
||||
std::string path;
|
||||
Module module{nullptr, wasmtime_module_delete};
|
||||
};
|
||||
static thread_local Cache cached;
|
||||
Error error(nullptr, wasmtime_error_delete);
|
||||
if (cached.path != wasm) {
|
||||
auto bytes = legacy::gets(wasm, 32769);
|
||||
if (bytes.size() > 32768 || bytes.size() < 8) return false;
|
||||
wasmtime_module_t* compiled = nullptr;
|
||||
error.reset(wasmtime_module_new(engine.get(), reinterpret_cast<const uint8_t*>(bytes.data()),
|
||||
bytes.size(), &compiled));
|
||||
if (error) return false;
|
||||
cached.module.reset(compiled);
|
||||
cached.path = wasm;
|
||||
}
|
||||
Store store(wasmtime_store_new(engine.get(), nullptr, nullptr), wasmtime_store_delete);
|
||||
wasmtime_store_limiter(store.get(), 128 * 1024, 128, 1, 1, 1);
|
||||
auto context = wasmtime_store_context(store.get());
|
||||
error.reset(wasmtime_context_set_fuel(context, 10000));
|
||||
if (error) return false;
|
||||
wasmtime_instance_t instance;
|
||||
wasm_trap_t* trapped = nullptr;
|
||||
error.reset(wasmtime_instance_new(context, cached.module.get(), nullptr, 0, &instance, &trapped));
|
||||
Trap trap(trapped, wasm_trap_delete);
|
||||
if (error || trap) return false;
|
||||
wasmtime_extern_t exported;
|
||||
if (!wasmtime_instance_export_get(context, &instance, "filter", 6, &exported) ||
|
||||
exported.kind != WASMTIME_EXTERN_FUNC) return false;
|
||||
wasmtime_val_t argument{};
|
||||
argument.kind = WASMTIME_I32;
|
||||
argument.of.i32 = static_cast<int32_t>(length);
|
||||
wasmtime_val_t result{};
|
||||
trapped = nullptr;
|
||||
error.reset(wasmtime_func_call(context, &exported.of.func, &argument, 1, &result, 1, &trapped));
|
||||
trap.reset(trapped);
|
||||
return !error && !trap && result.kind == WASMTIME_I32 && result.of.i32 != 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace crypto {
|
||||
|
||||
inline uint8_t g(unsigned a, unsigned b, unsigned carry) {
|
||||
unsigned value = (a + b + carry) & 255;
|
||||
return static_cast<uint8_t>((value << 2 | value >> 6) & 255);
|
||||
}
|
||||
|
||||
inline uint32_t f(uint32_t x) {
|
||||
unsigned a = x >> 24, b = (x >> 16) & 255, c = (x >> 8) & 255, d = x & 255;
|
||||
unsigned y1 = g(a ^ b, c ^ d, 1);
|
||||
unsigned y2 = g(c ^ d, y1, 0);
|
||||
return g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1);
|
||||
}
|
||||
|
||||
inline uint32_t fk(uint32_t x, uint32_t y) {
|
||||
unsigned a = x >> 24, b = (x >> 16) & 255, c = (x >> 8) & 255, d = x & 255;
|
||||
unsigned u = y >> 24, v = (y >> 16) & 255, w = (y >> 8) & 255, z = y & 255;
|
||||
unsigned middle1 = g(a ^ b, (c ^ d) ^ u, 1);
|
||||
unsigned middle2 = g(c ^ d, middle1 ^ v, 0);
|
||||
return g(a, middle1 ^ w, 0) << 24 | middle1 << 16 | middle2 << 8 | g(d, middle2 ^ z, 1);
|
||||
}
|
||||
|
||||
inline uint64_t block(uint64_t value, const std::array<uint32_t, 6>& k, bool decrypt = false) {
|
||||
uint32_t left = static_cast<uint32_t>(value >> 32), right = static_cast<uint32_t>(value);
|
||||
if (decrypt) {
|
||||
uint32_t x = left, y = right ^ left;
|
||||
for (int round = 3; round >= 1; --round) {
|
||||
uint32_t next = x ^ f(y ^ k[round]);
|
||||
x = y;
|
||||
y = next;
|
||||
}
|
||||
uint32_t initial = x ^ f(y ^ k[0]);
|
||||
return static_cast<uint64_t>(initial ^ k[4]) << 32 | (initial ^ y ^ k[5]);
|
||||
}
|
||||
left ^= k[4];
|
||||
right ^= k[5];
|
||||
uint32_t x = left ^ right, y = left ^ f(x ^ k[0]);
|
||||
for (int round = 1; round <= 2; ++round) {
|
||||
uint32_t next = x ^ f(y ^ k[round]);
|
||||
x = y;
|
||||
y = next;
|
||||
}
|
||||
uint32_t last = x ^ f(y ^ k[3]);
|
||||
return static_cast<uint64_t>(last) << 32 | (last ^ y);
|
||||
}
|
||||
|
||||
inline std::array<uint32_t, 6> schedule(std::string_view secret) {
|
||||
if (secret.size() != 48) throw std::runtime_error("bad read secret");
|
||||
auto digit = [](char c) -> uint8_t {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
throw std::runtime_error("bad read secret");
|
||||
};
|
||||
std::array<uint32_t, 6> material{};
|
||||
for (size_t i = 0; i < material.size(); ++i) {
|
||||
uint32_t word = 0;
|
||||
for (size_t j = 0; j < 4; ++j) {
|
||||
auto byte = digit(secret[8 * i + 2 * j]) << 4 | digit(secret[8 * i + 2 * j + 1]);
|
||||
word = word << 8 | byte;
|
||||
}
|
||||
material[i] = word;
|
||||
}
|
||||
uint32_t left = material[0], right = material[1], previous = material[5];
|
||||
std::array<uint16_t, 12> words{};
|
||||
for (size_t i = 0; i < 6; ++i) {
|
||||
auto next = fk(left, right ^ previous ^ material[i]);
|
||||
previous = left;
|
||||
left = right;
|
||||
right = next;
|
||||
words[2 * i] = static_cast<uint16_t>(next >> 16);
|
||||
words[2 * i + 1] = static_cast<uint16_t>(next);
|
||||
}
|
||||
auto whitening = [&](size_t i) { return static_cast<uint32_t>(words[i]) << 16 | words[i + 1]; };
|
||||
uint32_t output_left = whitening(8) ^ material[2], output_right = whitening(10) ^ material[3];
|
||||
std::array<uint32_t, 6> keys{};
|
||||
for (size_t i = 0; i < 4; ++i) {
|
||||
uint32_t round = static_cast<uint32_t>(words[i] >> 8) << 16 |
|
||||
static_cast<uint32_t>(words[i] & 255) << 8;
|
||||
keys[i] = round ^ output_left ^ (i % 2 ? output_right : 0) ^ material[i];
|
||||
}
|
||||
keys[4] = whitening(4) ^ output_left ^ output_right ^ material[4];
|
||||
keys[5] = whitening(6) ^ output_right ^ material[5];
|
||||
return keys;
|
||||
}
|
||||
|
||||
inline std::string seal(std::string_view secret, std::string_view plain) {
|
||||
std::string padded(plain);
|
||||
auto padding = 8 - (padded.size() % 8);
|
||||
padded.append(padding, static_cast<char>(padding));
|
||||
auto keys = schedule(secret);
|
||||
std::string result;
|
||||
result.reserve(padded.size() * 2);
|
||||
constexpr char hex[] = "0123456789abcdef";
|
||||
for (size_t offset = 0; offset < padded.size(); offset += 8) {
|
||||
uint64_t value = 0;
|
||||
for (size_t i = 0; i < 8; ++i)
|
||||
value = value << 8 | static_cast<unsigned char>(padded[offset+i]);
|
||||
value = block(value, keys);
|
||||
for (int shift = 60; shift >= 0; shift -= 4) result.push_back(hex[(value >> shift) & 15]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <sqlite3.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
class Statement {
|
||||
sqlite3_stmt* stmt_ = nullptr;
|
||||
public:
|
||||
Statement(sqlite3* db, const char* sql) {
|
||||
if (sqlite3_prepare_v2(db, sql, -1, &stmt_, nullptr) != SQLITE_OK)
|
||||
throw std::runtime_error(sqlite3_errmsg(db));
|
||||
}
|
||||
~Statement() { sqlite3_finalize(stmt_); }
|
||||
Statement(const Statement&) = delete;
|
||||
Statement& operator=(const Statement&) = delete;
|
||||
Statement& bind(int index, std::string_view value) {
|
||||
if (sqlite3_bind_text(stmt_, index, value.data(), static_cast<int>(value.size()), SQLITE_TRANSIENT) != SQLITE_OK)
|
||||
throw std::runtime_error("SQL text binding failed");
|
||||
return *this;
|
||||
}
|
||||
Statement& bind(int index, long long value) {
|
||||
if (sqlite3_bind_int64(stmt_, index, value) != SQLITE_OK)
|
||||
throw std::runtime_error("SQL integer binding failed");
|
||||
return *this;
|
||||
}
|
||||
bool next() {
|
||||
int rc = sqlite3_step(stmt_);
|
||||
if (rc == SQLITE_ROW) return true;
|
||||
if (rc == SQLITE_DONE) return false;
|
||||
throw std::runtime_error(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
|
||||
}
|
||||
std::string text(int column) const {
|
||||
auto p = reinterpret_cast<const char*>(sqlite3_column_text(stmt_, column));
|
||||
return p ? std::string(p, sqlite3_column_bytes(stmt_, column)) : std::string{};
|
||||
}
|
||||
long long number(int column) const { return sqlite3_column_int64(stmt_, column); }
|
||||
};
|
||||
|
||||
inline void execute(sqlite3* db, const char* sql) {
|
||||
if (sqlite3_exec(db, sql, nullptr, nullptr, nullptr) != SQLITE_OK)
|
||||
throw std::runtime_error(sqlite3_errmsg(db));
|
||||
}
|
||||
|
||||
class Transaction {
|
||||
sqlite3* db_;
|
||||
bool committed_ = false;
|
||||
public:
|
||||
explicit Transaction(sqlite3* db) : db_(db) { execute(db_, "BEGIN IMMEDIATE"); }
|
||||
~Transaction() { if (!committed_) sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); }
|
||||
void commit() { execute(db_, "COMMIT"); committed_ = true; }
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <fstream>
|
||||
#include <spawn.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
extern char** environ;
|
||||
|
||||
namespace legacy {
|
||||
|
||||
inline std::string gets(const std::string& path, size_t limit = 65536) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
if (!file) return {};
|
||||
std::string data(limit, '\0');
|
||||
file.read(data.data(), static_cast<std::streamsize>(data.size()));
|
||||
data.resize(static_cast<size_t>(file.gcount()));
|
||||
return data;
|
||||
}
|
||||
|
||||
inline int system(const std::vector<std::string>& arguments, const std::string& output) {
|
||||
if (arguments.empty() || arguments.front().empty() || arguments.front()[0] != '/')
|
||||
throw std::runtime_error("need an absolute executable path");
|
||||
if (output.find('\0') != std::string::npos) throw std::runtime_error("NUL in output path");
|
||||
std::vector<char*> argv;
|
||||
for (const auto& argument : arguments) {
|
||||
if (argument.find('\0') != std::string::npos) throw std::runtime_error("NUL in argument");
|
||||
argv.push_back(const_cast<char*>(argument.c_str()));
|
||||
}
|
||||
argv.push_back(nullptr);
|
||||
posix_spawn_file_actions_t actions;
|
||||
if (posix_spawn_file_actions_init(&actions)) throw std::runtime_error("spawn setup failed");
|
||||
int error = posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
|
||||
if (!error) error = posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, output.c_str(),
|
||||
O_WRONLY | O_CREAT | O_TRUNC, 0600);
|
||||
if (!error) error = posix_spawn_file_actions_adddup2(&actions, STDOUT_FILENO, STDERR_FILENO);
|
||||
pid_t child = -1;
|
||||
if (!error) error = posix_spawn(&child, argv[0], &actions, nullptr, argv.data(), environ);
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
if (error) throw std::runtime_error("cannot start tool");
|
||||
int status = 0;
|
||||
while (waitpid(child, &status, 0) < 0) {
|
||||
if (errno != EINTR) throw std::runtime_error("cannot wait for tool");
|
||||
}
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : 128;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
#include <httplib.h>
|
||||
|
||||
#include "chronicle.hpp"
|
||||
#include "compiler.hpp"
|
||||
#include "crypto.hpp"
|
||||
#include "database.hpp"
|
||||
#include "protocol.hpp"
|
||||
#include "util.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <charconv>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
static sqlite3* db = nullptr;
|
||||
static std::mutex db_lock;
|
||||
|
||||
static void reply(httplib::Response& response, int status, const json& body) {
|
||||
response.status = status;
|
||||
response.set_content(body.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
|
||||
}
|
||||
|
||||
template <class Handler>
|
||||
static auto endpoint(Handler handler) {
|
||||
return [handler](const httplib::Request& request, httplib::Response& response) {
|
||||
try {
|
||||
handler(request, response);
|
||||
} catch (const HttpError& error) {
|
||||
reply(response, error.status, {{"error", error.what()}});
|
||||
} catch (const filters::Busy& error) {
|
||||
reply(response, 429, {{"error", error.what()}});
|
||||
} catch (const json::exception&) {
|
||||
reply(response, 400, {{"error", "bad field type"}});
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "request failed: " << error.what() << '\n';
|
||||
reply(response, 500, {{"error", "service error"}});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static void require_queue(const std::string& id) {
|
||||
Statement query(db, "SELECT 1 FROM queues WHERE id=?");
|
||||
if (!query.bind(1, id).next()) throw HttpError(404, "queue not found");
|
||||
}
|
||||
|
||||
static void require_key(const httplib::Request& request) {
|
||||
Statement query(db, "SELECT 1 FROM queues WHERE id=? AND read_key=?");
|
||||
query.bind(1, request.matches[1].str()).bind(2, request.get_header_value("X-Queue-Key"));
|
||||
if (!query.next()) throw HttpError(403, "bad queue key");
|
||||
}
|
||||
|
||||
static json message_row(const Statement& query) {
|
||||
return {{"id", query.number(0)}, {"topic", query.text(1)}, {"ciphertext", query.text(2)}};
|
||||
}
|
||||
|
||||
// Expired rows are already invisible to readers. Reclaim a bounded batch on
|
||||
// each public write so cleanup cannot hold the shared database lock for long.
|
||||
static void prune_expired() {
|
||||
Statement prune(db, R"SQL(
|
||||
DELETE FROM messages WHERE id IN (
|
||||
SELECT id FROM messages WHERE expires_at<=? ORDER BY expires_at LIMIT 256
|
||||
)
|
||||
)SQL");
|
||||
prune.bind(1, epoch_now()).next();
|
||||
}
|
||||
|
||||
static long long after_id(const httplib::Request& request) {
|
||||
if (!request.has_param("after_id")) return 0;
|
||||
const auto value = request.get_param_value("after_id");
|
||||
long long parsed = 0;
|
||||
const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);
|
||||
if (value.empty() || result.ec != std::errc{} || result.ptr != value.data() + value.size() || parsed < 0)
|
||||
throw HttpError(400, "bad after_id");
|
||||
return parsed;
|
||||
}
|
||||
|
||||
static void initialize() {
|
||||
fs::create_directories("/data");
|
||||
fs::create_directories("/var/log/lighthouse");
|
||||
fs::create_directories(filters::work_root);
|
||||
if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0700) ||
|
||||
chmod(filters::work_root, 0711))
|
||||
throw std::runtime_error("cannot set storage permissions");
|
||||
if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK)
|
||||
throw std::runtime_error("cannot open database");
|
||||
execute(db, R"SQL(
|
||||
PRAGMA journal_mode=WAL;
|
||||
PRAGMA foreign_keys=ON;
|
||||
CREATE TABLE IF NOT EXISTS queues(
|
||||
id TEXT PRIMARY KEY, read_key TEXT NOT NULL,
|
||||
wasm_path TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT 'untitled',
|
||||
retention_seconds INTEGER NOT NULL DEFAULT 3600, created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS messages(
|
||||
id INTEGER PRIMARY KEY, queue_id TEXT NOT NULL REFERENCES queues(id),
|
||||
ciphertext TEXT NOT NULL, topic TEXT NOT NULL DEFAULT 'inbox',
|
||||
not_before INTEGER NOT NULL DEFAULT 0, expires_at INTEGER NOT NULL DEFAULT 2147483647,
|
||||
read_at INTEGER, created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS filter_revisions(
|
||||
id INTEGER PRIMARY KEY, queue_id TEXT NOT NULL REFERENCES queues(id),
|
||||
label TEXT NOT NULL, state TEXT NOT NULL, wasm_path TEXT NOT NULL DEFAULT '',
|
||||
compiler_output TEXT NOT NULL, source TEXT NOT NULL DEFAULT '',
|
||||
listing TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS messages_by_queue ON messages(queue_id,id);
|
||||
CREATE INDEX IF NOT EXISTS messages_by_expiry ON messages(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS revisions_by_queue ON filter_revisions(queue_id,id DESC);
|
||||
)SQL");
|
||||
bool has_read_at = false;
|
||||
{
|
||||
Statement columns(db, "PRAGMA table_info(messages)");
|
||||
while (columns.next())
|
||||
if (columns.text(1) == "read_at") has_read_at = true;
|
||||
}
|
||||
if (!has_read_at) execute(db, "ALTER TABLE messages ADD COLUMN read_at INTEGER");
|
||||
bool has_source = false, has_listing = false;
|
||||
{
|
||||
Statement columns(db, "PRAGMA table_info(filter_revisions)");
|
||||
while (columns.next()) {
|
||||
if (columns.text(1) == "source") has_source = true;
|
||||
if (columns.text(1) == "listing") has_listing = true;
|
||||
}
|
||||
}
|
||||
if (!has_source) execute(db, "ALTER TABLE filter_revisions ADD COLUMN source TEXT NOT NULL DEFAULT ''");
|
||||
if (!has_listing) execute(db, "ALTER TABLE filter_revisions ADD COLUMN listing TEXT NOT NULL DEFAULT ''");
|
||||
}
|
||||
|
||||
static void queue_routes(httplib::Server& server) {
|
||||
server.Post("/api/queues", endpoint([](const auto& request, auto& response) {
|
||||
auto body = object_body(request.body);
|
||||
auto label = label_field(body, "untitled");
|
||||
auto retention = number_field(body, "retention_seconds", 3600, 60, 604800);
|
||||
auto id = uuid(), key = random_hex(48), created = utc_now();
|
||||
std::lock_guard guard(db_lock);
|
||||
prune_expired();
|
||||
Statement insert(db, "INSERT INTO queues(id,read_key,label,retention_seconds,created_at) VALUES(?,?,?,?,?)");
|
||||
insert.bind(1, id).bind(2, key).bind(3, label).bind(4, retention).bind(5, created).next();
|
||||
reply(response, 201, {{"id", id}, {"read_key", key}, {"label", label},
|
||||
{"retention_seconds", retention}, {"created_at", created}});
|
||||
}));
|
||||
|
||||
server.Get(R"(/api/queues/([0-9a-f-]{36})$)", endpoint([](const auto& request, auto& response) {
|
||||
auto id = request.matches[1].str();
|
||||
auto moment = epoch_now();
|
||||
std::lock_guard guard(db_lock);
|
||||
Statement query(db, R"SQL(
|
||||
SELECT q.created_at,q.wasm_path,q.label,q.retention_seconds,COUNT(m.id),
|
||||
COALESCE(SUM(m.not_before<=? AND m.expires_at>? AND m.read_at IS NULL),0)
|
||||
FROM queues q LEFT JOIN messages m ON m.queue_id=q.id WHERE q.id=? GROUP BY q.id
|
||||
)SQL");
|
||||
query.bind(1, moment).bind(2, moment).bind(3, id);
|
||||
if (!query.next()) throw HttpError(404, "queue not found");
|
||||
reply(response, 200, {{"id", id}, {"created_at", query.text(0)}, {"label", query.text(2)},
|
||||
{"retention_seconds", query.number(3)}, {"filter_installed", !query.text(1).empty()},
|
||||
{"stored_count", query.number(4)}, {"ready_count", query.number(5)}});
|
||||
}));
|
||||
}
|
||||
|
||||
static void filter_routes(httplib::Server& server) {
|
||||
server.Post(R"(/api/queues/([0-9a-f-]{36})/filter)", endpoint([](const auto& request, auto& response) {
|
||||
auto id = request.matches[1].str();
|
||||
auto body = object_body(request.body);
|
||||
auto source = text_field(body, "source", "");
|
||||
if (source.empty() || source.size() > 8192 || source.find('\0') != std::string::npos)
|
||||
throw HttpError(400, "need 1..8192 bytes of C source");
|
||||
auto label = label_field(body, "unnamed");
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
require_queue(id);
|
||||
}
|
||||
auto artifact = filters::compile(source);
|
||||
auto state = artifact.ready ? "ready" : "rejected";
|
||||
long long revision;
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
Transaction transaction(db);
|
||||
require_queue(id);
|
||||
Statement insert(db, R"SQL(
|
||||
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
)SQL");
|
||||
insert.bind(1, id).bind(2, label).bind(3, state).bind(4, artifact.path)
|
||||
.bind(5, artifact.diagnostic).bind(6, source).bind(7, artifact.listing)
|
||||
.bind(8, utc_now()).next();
|
||||
revision = sqlite3_last_insert_rowid(db);
|
||||
Statement old(db, R"SQL(
|
||||
SELECT r.id,r.wasm_path FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
|
||||
WHERE r.queue_id=? AND (r.wasm_path='' OR r.wasm_path<>q.wasm_path)
|
||||
AND r.id NOT IN (SELECT id FROM filter_revisions WHERE queue_id=? ORDER BY id DESC LIMIT 16)
|
||||
)SQL");
|
||||
old.bind(1, id).bind(2, id);
|
||||
std::vector<long long> obsolete_ids;
|
||||
std::vector<std::string> obsolete;
|
||||
while (old.next()) {
|
||||
obsolete_ids.push_back(old.number(0));
|
||||
if (!old.text(1).empty()) obsolete.push_back(old.text(1));
|
||||
}
|
||||
for (auto revision_id : obsolete_ids) {
|
||||
Statement erase(db, "DELETE FROM filter_revisions WHERE id=?");
|
||||
erase.bind(1, revision_id).next();
|
||||
}
|
||||
transaction.commit();
|
||||
for (const auto& path : obsolete) {
|
||||
std::error_code error;
|
||||
fs::remove_all(fs::path(path).parent_path(), error);
|
||||
}
|
||||
}
|
||||
reply(response, artifact.ready ? 200 : 422,
|
||||
{{"ok", artifact.ready}, {"compiler", artifact.diagnostic}, {"listing", artifact.listing},
|
||||
{"revision", revision}, {"state", state}, {"active", false},
|
||||
{"abi", "int filter(int encrypted_length): nonzero accepts"}});
|
||||
}));
|
||||
|
||||
server.Get(R"(/api/queues/([0-9a-f-]{36})/filters)", endpoint([](const auto& request, auto& response) {
|
||||
auto id = request.matches[1].str();
|
||||
std::lock_guard guard(db_lock);
|
||||
require_queue(id);
|
||||
Statement query(db, R"SQL(
|
||||
SELECT r.id,r.label,r.state,r.created_at,r.wasm_path=q.wasm_path AND r.wasm_path<>''
|
||||
FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
|
||||
WHERE r.queue_id=? ORDER BY r.id DESC LIMIT 20
|
||||
)SQL");
|
||||
query.bind(1, id);
|
||||
auto history = json::array();
|
||||
while (query.next())
|
||||
history.push_back({{"revision", query.number(0)}, {"label", query.text(1)},
|
||||
{"state", query.text(2)}, {"created_at", query.text(3)},
|
||||
{"active", query.number(4) != 0}});
|
||||
reply(response, 200, {{"filters", history}});
|
||||
}));
|
||||
|
||||
server.Get(R"(/api/queues/([0-9a-f-]{36})/filters/([0-9]{1,18})$)",
|
||||
endpoint([](const auto& request, auto& response) {
|
||||
std::lock_guard guard(db_lock);
|
||||
require_key(request);
|
||||
Statement query(db, R"SQL(
|
||||
SELECT r.label,r.state,r.created_at,r.source,r.compiler_output,r.listing,
|
||||
r.wasm_path=q.wasm_path AND r.wasm_path<>''
|
||||
FROM filter_revisions r JOIN queues q ON q.id=r.queue_id
|
||||
WHERE r.queue_id=? AND r.id=?
|
||||
)SQL");
|
||||
query.bind(1, request.matches[1].str()).bind(2, std::stoll(request.matches[2].str()));
|
||||
if (!query.next()) throw HttpError(404, "revision not found");
|
||||
reply(response, 200, {{"revision", std::stoll(request.matches[2].str())},
|
||||
{"label", query.text(0)}, {"state", query.text(1)},
|
||||
{"created_at", query.text(2)}, {"source", query.text(3)},
|
||||
{"compiler", query.text(4)}, {"listing", query.text(5)},
|
||||
{"active", query.number(6) != 0}});
|
||||
}));
|
||||
|
||||
server.Post(R"(/api/queues/([0-9a-f-]{36})/filters/([0-9]{1,18})/activate)",
|
||||
endpoint([](const auto& request, auto& response) {
|
||||
auto id = request.matches[1].str();
|
||||
auto revision = std::stoll(request.matches[2].str());
|
||||
std::lock_guard guard(db_lock);
|
||||
require_key(request);
|
||||
Statement query(db, "SELECT wasm_path FROM filter_revisions WHERE id=? AND queue_id=? AND state='ready'");
|
||||
query.bind(1, revision).bind(2, id);
|
||||
if (!query.next()) throw HttpError(404, "ready revision not found");
|
||||
Statement update(db, "UPDATE queues SET wasm_path=? WHERE id=?");
|
||||
update.bind(1, query.text(0)).bind(2, id).next();
|
||||
reply(response, 200, {{"active_revision", revision}});
|
||||
}));
|
||||
}
|
||||
|
||||
static void message_routes(httplib::Server& server) {
|
||||
server.Post(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
|
||||
auto id = request.matches[1].str();
|
||||
auto letter = Envelope::read(object_body(request.body));
|
||||
std::string wasm, created, key;
|
||||
long long retention;
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
Statement query(db, "SELECT wasm_path,created_at,retention_seconds,read_key FROM queues WHERE id=?");
|
||||
if (!query.bind(1, id).next()) throw HttpError(404, "queue not found");
|
||||
wasm = query.text(0);
|
||||
created = query.text(1);
|
||||
retention = query.number(2);
|
||||
key = query.text(3);
|
||||
}
|
||||
auto cipher = crypto::seal(key, letter.message);
|
||||
if (!filters::accepts(wasm, cipher.size()))
|
||||
throw HttpError(403, "message rejected by filter");
|
||||
auto instant = utc_now();
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
Transaction transaction(db);
|
||||
prune_expired();
|
||||
Statement insert(db, R"SQL(
|
||||
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
|
||||
)SQL");
|
||||
insert.bind(1, id).bind(2, cipher).bind(3, letter.topic).bind(4, letter.release_at)
|
||||
.bind(5, epoch_now() + retention).bind(6, instant).next();
|
||||
chronicle::append(created, id, letter.topic, cipher, instant);
|
||||
transaction.commit();
|
||||
}
|
||||
reply(response, 201, {{"queued", true}, {"encrypted_length", cipher.size()},
|
||||
{"topic", letter.topic}, {"release_at", letter.release_at}});
|
||||
}));
|
||||
|
||||
server.Get(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
|
||||
auto show_read = request.has_param("show_read") && request.get_param_value("show_read") == "true";
|
||||
auto after = after_id(request);
|
||||
constexpr long long page_size = 128;
|
||||
auto messages = json::array();
|
||||
bool has_more = false;
|
||||
long long last = after;
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
require_key(request);
|
||||
auto moment = epoch_now();
|
||||
Transaction transaction(db);
|
||||
Statement query(db, R"SQL(
|
||||
SELECT id,topic,ciphertext FROM messages
|
||||
WHERE queue_id=? AND id>? AND not_before<=? AND expires_at>?
|
||||
AND (? OR read_at IS NULL) ORDER BY id LIMIT ?
|
||||
)SQL");
|
||||
query.bind(1, request.matches[1].str()).bind(2, after).bind(3, moment)
|
||||
.bind(4, moment).bind(5, show_read ? 1LL : 0LL).bind(6, page_size + 1);
|
||||
while (query.next()) {
|
||||
if (messages.size() == page_size) { has_more = true; break; }
|
||||
last = query.number(0);
|
||||
messages.push_back(message_row(query));
|
||||
}
|
||||
if (!show_read && !messages.empty()) {
|
||||
Statement mark(db, R"SQL(
|
||||
UPDATE messages SET read_at=? WHERE queue_id=? AND id>? AND id<=?
|
||||
AND not_before<=? AND expires_at>? AND read_at IS NULL
|
||||
)SQL");
|
||||
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, after)
|
||||
.bind(4, last).bind(5, moment).bind(6, moment).next();
|
||||
}
|
||||
transaction.commit();
|
||||
}
|
||||
reply(response, 200, {{"messages", messages}, {"has_more", has_more},
|
||||
{"next_after", has_more ? last : 0}});
|
||||
}));
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
initialize();
|
||||
httplib::Server server;
|
||||
server.new_task_queue = [] { return new httplib::ThreadPool(32, 64, 256); };
|
||||
server.set_keep_alive_max_count(8);
|
||||
server.set_keep_alive_timeout(2);
|
||||
server.set_read_timeout(3, 0);
|
||||
server.set_write_timeout(3, 0);
|
||||
server.set_payload_max_length(32768);
|
||||
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
|
||||
if (request.has_header("Range")) {
|
||||
reply(response, 400, {{"error", "range requests are not supported"}});
|
||||
return httplib::Server::HandlerResponse::Handled;
|
||||
}
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
server.Get("/api/health", endpoint([](const auto&, auto& response) {
|
||||
reply(response, 200, {{"status", "ok"}});
|
||||
}));
|
||||
queue_routes(server);
|
||||
filter_routes(server);
|
||||
message_routes(server);
|
||||
server.set_mount_point("/", "/srv/lighthouse/public");
|
||||
bool listening = server.listen("0.0.0.0", 8080);
|
||||
sqlite3_close(db);
|
||||
return listening ? 0 : 1;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "startup failed: " << error.what() << '\n';
|
||||
if (db) sqlite3_close(db);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <regex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
struct HttpError : std::runtime_error {
|
||||
int status;
|
||||
HttpError(int code, const std::string& message) : std::runtime_error(message), status(code) {}
|
||||
};
|
||||
|
||||
inline long long epoch_now() {
|
||||
return std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
inline json object_body(const std::string& input) {
|
||||
auto body = json::parse(input, nullptr, false);
|
||||
if (!body.is_object()) throw HttpError(400, "need a JSON object");
|
||||
return body;
|
||||
}
|
||||
|
||||
inline std::string text_field(const json& body, const char* name, const std::string& fallback) {
|
||||
if (!body.contains(name)) return fallback;
|
||||
if (!body[name].is_string()) throw HttpError(400, std::string(name) + " must be a string");
|
||||
return body[name].get<std::string>();
|
||||
}
|
||||
|
||||
inline long long number_field(const json& body, const char* name, long long fallback,
|
||||
long long low, long long high) {
|
||||
if (!body.contains(name)) return fallback;
|
||||
const auto& field = body[name];
|
||||
if (!field.is_number_integer() || field < low || field > high)
|
||||
throw HttpError(400, std::string(name) + " out of range");
|
||||
return field.get<long long>();
|
||||
}
|
||||
|
||||
inline std::string label_field(const json& body, const std::string& fallback) {
|
||||
auto label = text_field(body, "label", fallback);
|
||||
if (!std::regex_match(label, std::regex("[A-Za-z0-9 _.-]{1,48}")))
|
||||
throw HttpError(400, "bad label");
|
||||
return label;
|
||||
}
|
||||
|
||||
struct Envelope {
|
||||
std::string message;
|
||||
std::string topic;
|
||||
long long release_at;
|
||||
|
||||
static Envelope read(const json& body) {
|
||||
auto encoded = text_field(body, "message", "");
|
||||
if (encoded.empty() || encoded.size() > 5464 || encoded.size() % 4)
|
||||
throw HttpError(400, "message must be 1..4096 bytes of base64 data");
|
||||
static constexpr std::string_view alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
std::string message;
|
||||
message.reserve(encoded.size() / 4 * 3);
|
||||
for (size_t offset = 0; offset < encoded.size(); offset += 4) {
|
||||
unsigned values[4]{};
|
||||
unsigned padding = 0;
|
||||
for (size_t i = 0; i < 4; ++i) {
|
||||
auto c = encoded[offset + i];
|
||||
if (c == '=') {
|
||||
if (i < 2 || offset + 4 != encoded.size())
|
||||
throw HttpError(400, "invalid base64 message");
|
||||
++padding;
|
||||
} else {
|
||||
if (padding) throw HttpError(400, "invalid base64 message");
|
||||
auto digit = alphabet.find(c);
|
||||
if (digit == std::string_view::npos) throw HttpError(400, "invalid base64 message");
|
||||
values[i] = static_cast<unsigned>(digit);
|
||||
}
|
||||
}
|
||||
if ((padding == 1 && (values[2] & 3)) || (padding == 2 && (values[1] & 15)))
|
||||
throw HttpError(400, "invalid base64 message");
|
||||
unsigned word = values[0] << 18 | values[1] << 12 | values[2] << 6 | values[3];
|
||||
message.push_back(static_cast<char>(word >> 16));
|
||||
if (padding < 2) message.push_back(static_cast<char>(word >> 8));
|
||||
if (!padding) message.push_back(static_cast<char>(word));
|
||||
}
|
||||
if (message.empty() || message.size() > 4096)
|
||||
throw HttpError(400, "message must be 1..4096 bytes of base64 data");
|
||||
auto topic = text_field(body, "topic", "inbox");
|
||||
if (!std::regex_match(topic, std::regex("[a-z0-9_.-]{1,32}")))
|
||||
throw HttpError(400, "bad topic");
|
||||
auto delay = number_field(body, "delay_ms", 0, 0, 60000);
|
||||
return {message, topic, epoch_now() + (delay + 999) / 1000};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
|
||||
namespace recipe {
|
||||
|
||||
enum class Op : uint8_t { source = 1, cc, listing };
|
||||
struct Program {
|
||||
std::array<Op, 3> code{};
|
||||
size_t size = 0;
|
||||
};
|
||||
|
||||
consteval Program compile(std::string_view text) {
|
||||
Program program;
|
||||
unsigned effects = 0;
|
||||
while (!text.empty()) {
|
||||
auto end = text.find('|');
|
||||
auto word = text.substr(0, end);
|
||||
while (!word.empty() && word.front() == ' ') word.remove_prefix(1);
|
||||
while (!word.empty() && word.back() == ' ') word.remove_suffix(1);
|
||||
Op op;
|
||||
unsigned needs, gives;
|
||||
if (word == "source") { op = Op::source; needs = 0; gives = 1; }
|
||||
else if (word == "cc") { op = Op::cc; needs = 1; gives = 2; }
|
||||
else if (word == "listing") { op = Op::listing; needs = 2; gives = 4; }
|
||||
else throw "unknown recipe stage";
|
||||
if ((effects & needs) != needs || (effects & gives) || program.size == program.code.size())
|
||||
throw "recipe stages out of order or repeated";
|
||||
effects |= gives;
|
||||
program.code[program.size++] = op;
|
||||
if (end == std::string_view::npos) break;
|
||||
text.remove_prefix(end + 1);
|
||||
if (text.empty()) throw "empty recipe stage";
|
||||
}
|
||||
if (effects != 7) throw "incomplete filter recipe";
|
||||
return program;
|
||||
}
|
||||
|
||||
inline constexpr auto filter = compile("source | cc | listing");
|
||||
|
||||
template <class Build>
|
||||
void run(const Program& program, Build& build) {
|
||||
for (size_t pc = 0; pc < program.size; ++pc) {
|
||||
switch (program.code[pc]) {
|
||||
case Op::source: build.source(); break;
|
||||
case Op::cc: if (!build.cc()) return; break;
|
||||
case Op::listing: build.listing(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <cerrno>
|
||||
#include <ctime>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <sys/random.h>
|
||||
|
||||
inline std::string random_hex(size_t count) {
|
||||
std::string bytes(count, '\0');
|
||||
size_t offset = 0;
|
||||
while (offset < count) {
|
||||
auto got = getrandom(bytes.data() + offset, count - offset, 0);
|
||||
if (got < 0 && errno == EINTR) continue;
|
||||
if (got <= 0) throw std::runtime_error("random source failed");
|
||||
offset += static_cast<size_t>(got);
|
||||
}
|
||||
for (auto& byte : bytes) byte = "0123456789abcdef"[static_cast<unsigned char>(byte) & 15];
|
||||
return bytes;
|
||||
}
|
||||
|
||||
inline std::string uuid() {
|
||||
auto value = random_hex(32);
|
||||
value[12] = '4';
|
||||
value[16] = "89ab"[static_cast<unsigned char>(value[16]) & 3];
|
||||
return value.substr(0,8) + "-" + value.substr(8,4) + "-" + value.substr(12,4) +
|
||||
"-" + value.substr(16,4) + "-" + value.substr(20);
|
||||
}
|
||||
|
||||
inline std::string utc_now() {
|
||||
auto time = std::time(nullptr);
|
||||
std::tm utc{};
|
||||
gmtime_r(&time, &utc);
|
||||
char text[32];
|
||||
std::strftime(text, sizeof(text), "%FT%TZ", &utc);
|
||||
return text;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 yhirose
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
# cpp-httplib
|
||||
|
||||
`httplib.h` is the unmodified header from upstream tag
|
||||
[`v0.53.1`](https://github.com/yhirose/cpp-httplib/releases/tag/v0.53.1).
|
||||
SHA-256: `bc69d53636a8757cb24a1deb9880bf7e2fdae3a80bbc759e145b8c80913cbfa3`.
|
||||
|
||||
The upstream license is included as `CPP-HTTPLIB-LICENSE`. This header replaces
|
||||
Debian bookworm's `libcpp-httplib-dev` (0.11.4) for the Lighthouse binary.
|
||||
The pinned version contains the fixes for CVE-2025-46728,
|
||||
CVE-2025-53628, CVE-2025-53629, and CVE-2026-45352, as well as the
|
||||
subsequent upstream header parsing and regex routing security fixes.
|
||||
Vendored
+21842
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Loopback-only smoke tests using disposable containers and synthetic records."""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
SOURCE = "int filter(int length) { return length <= 8192; }"
|
||||
OLD_JOURNAL = "/var/log/lighthouse/1999-12-31/synthetic-legacy.log"
|
||||
OLD_CONTENT = "synthetic legacy journal; retain these bytes\n"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("seed", "verify"))
|
||||
parser.add_argument("--url", required=True)
|
||||
parser.add_argument("--container", required=True)
|
||||
parser.add_argument("--state", type=Path, required=True)
|
||||
parser.add_argument("--journal", choices=("baseline", "private"), required=True)
|
||||
args = parser.parse_args()
|
||||
parsed = urllib.parse.urlsplit(args.url)
|
||||
if (parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost", "::1")
|
||||
or parsed.username or parsed.password or parsed.query or parsed.fragment):
|
||||
parser.error("tests only accept an explicit loopback HTTP URL")
|
||||
if not re.fullmatch(r"goctf-lighthouse-lab-[a-z0-9-]+", args.container):
|
||||
parser.error("use a disposable container named goctf-lighthouse-lab-...")
|
||||
origin = args.url.rstrip("/")
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
checks = 0
|
||||
|
||||
def check(condition, message):
|
||||
nonlocal checks
|
||||
if not condition:
|
||||
raise AssertionError(message)
|
||||
checks += 1
|
||||
|
||||
def api(method, path, body=None, key=None, expected=200):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if key is not None:
|
||||
headers["X-Queue-Key"] = key
|
||||
request = urllib.request.Request(origin + path, method=method, headers=headers,
|
||||
data=None if body is None else json.dumps(body).encode())
|
||||
try:
|
||||
response = opener.open(request, timeout=12)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
status = response.status
|
||||
result = json.loads(response.read())
|
||||
check(status == expected, f"unexpected HTTP status for {method} {path}: {status}")
|
||||
return result
|
||||
|
||||
def inside(*command, user=None):
|
||||
command_line = ["docker", "exec"]
|
||||
if user:
|
||||
command_line.extend(("--user", user))
|
||||
return subprocess.run(command_line + [args.container, *command],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
|
||||
def mode(path):
|
||||
result = inside("stat", "-c", "%a", path)
|
||||
check(result.returncode == 0, "cannot inspect synthetic journal permissions")
|
||||
return result.stdout.strip()
|
||||
|
||||
check(api("GET", "/api/health")["status"] == "ok", "health response changed")
|
||||
if args.action == "seed":
|
||||
check(not args.state.exists(), "refusing to overwrite a previous test state")
|
||||
queue = api("POST", "/api/queues", {"label": "regression mailbox", "retention_seconds": 3600},
|
||||
expected=201)
|
||||
check(bool(re.fullmatch(r"[0-9a-f-]{36}", queue["id"])), "invalid generated queue ID")
|
||||
check(bool(re.fullmatch(r"[0-9a-f]{48}", queue["read_key"])), "invalid generated read key")
|
||||
path = "/api/queues/" + queue["id"]
|
||||
other = api("POST", "/api/queues", {"label": "other mailbox"}, expected=201)
|
||||
api("GET", path + "/messages", expected=403)
|
||||
api("GET", path + "/messages", key=other["read_key"], expected=403)
|
||||
api("POST", path + "/messages", {"message": "not-base64"}, expected=400)
|
||||
api("POST", path + "/messages", {"message": "eA==", "topic": "invalid/topic"}, expected=400)
|
||||
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "length filter"})
|
||||
check(compiled["ok"] is True, "ordinary C filter did not compile")
|
||||
api("POST", path + f"/filters/{compiled['revision']}/activate", {}, expected=403)
|
||||
api("POST", path + f"/filters/{compiled['revision']}/activate", {}, key=queue["read_key"])
|
||||
api("GET", path + f"/filters/{compiled['revision']}", expected=403)
|
||||
rejected = api("POST", path + "/filter", {"source": "int filter(int x) { return ; broken }"},
|
||||
expected=422)
|
||||
check(rejected["ok"] is False and bool(rejected["compiler"]), "compiler diagnostics missing")
|
||||
raw = b"synthetic regression message\x00with binary data"
|
||||
api("POST", path + "/messages", {"message": base64.b64encode(raw).decode(), "topic": "regression"},
|
||||
expected=201)
|
||||
received = api("GET", path + "/messages", key=queue["read_key"])["messages"]
|
||||
check(len(received) == 1 and received[0]["topic"] == "regression", "normal delivery failed")
|
||||
check(bool(re.fullmatch(r"[0-9a-f]+", received[0]["ciphertext"])), "ciphertext encoding changed")
|
||||
check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [],
|
||||
"reading did not mark the message")
|
||||
journal = f"/var/log/lighthouse/{queue['created_at'][:10]}/{queue['id']}.log"
|
||||
create_old = inside("sh", "-c", 'mkdir -p /var/log/lighthouse/1999-12-31 && '
|
||||
'printf "%s\\n" "synthetic legacy journal; retain these bytes" '
|
||||
'> /var/log/lighthouse/1999-12-31/synthetic-legacy.log && '
|
||||
'chmod 755 /var/log/lighthouse/1999-12-31 && '
|
||||
'chmod 644 /var/log/lighthouse/1999-12-31/synthetic-legacy.log')
|
||||
check(create_old.returncode == 0, "cannot prepare synthetic legacy journal")
|
||||
state = {"queue": queue, "revision": compiled["revision"], "message": received[0], "journal": journal}
|
||||
args.state.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor = os.open(args.state, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, "w") as stream:
|
||||
json.dump(state, stream)
|
||||
else:
|
||||
state = json.loads(args.state.read_text())
|
||||
queue = state["queue"]
|
||||
path = "/api/queues/" + queue["id"]
|
||||
metadata = api("GET", path)
|
||||
check(metadata["label"] == "regression mailbox" and metadata["filter_installed"],
|
||||
"queue metadata or active filter was lost")
|
||||
messages = api("GET", path + "/messages?show_read=true", key=queue["read_key"])["messages"]
|
||||
check(state["message"] in messages, "old message or ciphertext changed across restart")
|
||||
check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [],
|
||||
"old read_at state was not retained")
|
||||
details = api("GET", path + f"/filters/{state['revision']}", key=queue["read_key"])
|
||||
check(details["source"] == SOURCE and details["active"], "old filter was not retained")
|
||||
api("GET", path + "/messages?show_read=true", key="0" * 48, expected=403)
|
||||
api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201)
|
||||
check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1,
|
||||
"old active filter rejected a normal new message")
|
||||
public_compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"})
|
||||
check(public_compiled["ok"] is True, "public filter compilation contract changed")
|
||||
api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter",
|
||||
{"source": SOURCE, "label": "missing queue"}, expected=404)
|
||||
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
|
||||
key=queue["read_key"])
|
||||
check(compiled["ok"] is True, "compilation contract changed after restart")
|
||||
|
||||
paging = api("POST", "/api/queues", {"label": "pagination regression"}, expected=201)
|
||||
paging_path = "/api/queues/" + paging["id"] + "/messages"
|
||||
for index in range(130):
|
||||
api("POST", paging_path, {"message": "eA==", "topic": "page"}, expected=201)
|
||||
first = api("GET", paging_path, key=paging["read_key"])
|
||||
check(len(first["messages"]) == 128 and first["has_more"], "first page boundary changed")
|
||||
check(first["next_after"] == first["messages"][-1]["id"], "first page cursor changed")
|
||||
second = api("GET", paging_path + "?after_id=" + str(first["next_after"]),
|
||||
key=paging["read_key"])
|
||||
check(len(second["messages"]) == 2 and not second["has_more"],
|
||||
"unread messages beyond first page were lost")
|
||||
check(second["messages"][0]["id"] > first["messages"][-1]["id"],
|
||||
"page order changed")
|
||||
check(api("GET", paging_path, key=paging["read_key"])["messages"] == [],
|
||||
"paged read did not mark exactly the delivered messages")
|
||||
check(len(api("GET", paging_path + "?show_read=true", key=paging["read_key"])["messages"]) == 128,
|
||||
"history page changed")
|
||||
api("GET", paging_path + "?after_id=-1", key=paging["read_key"], expected=400)
|
||||
api("GET", paging_path + "?after_id=9223372036854775808", key=paging["read_key"], expected=400)
|
||||
|
||||
expiring = api("POST", "/api/queues", {"label": "expired cleanup"}, expected=201)
|
||||
expiring_path = "/api/queues/" + expiring["id"]
|
||||
api("POST", expiring_path + "/messages", {"message": "eA=="}, expected=201)
|
||||
updated = inside("sqlite3", "/data/lighthouse.db",
|
||||
"UPDATE messages SET expires_at=0 WHERE queue_id='" + expiring["id"] + "'")
|
||||
check(updated.returncode == 0, "cannot prepare synthetic expired row")
|
||||
api("POST", "/api/queues", {"label": "cleanup trigger"}, expected=201)
|
||||
check(api("GET", expiring_path)["stored_count"] == 0,
|
||||
"expired rows were not reclaimed by a public write")
|
||||
|
||||
capped = api("POST", "/api/queues", {"label": "bounded journal"}, expected=201)
|
||||
capped_path = "/api/queues/" + capped["id"]
|
||||
encoded = base64.b64encode(b"x" * 4096).decode()
|
||||
for index in range(68):
|
||||
api("POST", capped_path + "/messages", {"message": encoded}, expected=201)
|
||||
journal_path = f"/var/log/lighthouse/{capped['created_at'][:10]}/{capped['id']}.log"
|
||||
journal_size = inside("stat", "-c", "%s", journal_path)
|
||||
check(journal_size.returncode == 0 and 0 < int(journal_size.stdout) <= 512 * 1024,
|
||||
"journal exceeded the per-queue cap")
|
||||
check(api("GET", capped_path)["stored_count"] == 68,
|
||||
"journal cap dropped messages from SQLite")
|
||||
|
||||
old = inside("cat", OLD_JOURNAL)
|
||||
check(old.returncode == 0 and old.stdout == OLD_CONTENT, "legacy journal bytes were altered")
|
||||
diagnostic = api("POST", path + "/filter", {
|
||||
"source": '#include "' + OLD_JOURNAL + '"\nint filter(int length) { return 1; }',
|
||||
"label": "synthetic journal regression",
|
||||
}, key=queue["read_key"] if args.action == "verify" else None, expected=422)["compiler"]
|
||||
check((OLD_CONTENT.strip() in diagnostic) == (args.journal == "baseline"),
|
||||
"unexpected disclosure of the synthetic journal through compiler diagnostics")
|
||||
incbin = '__asm__(".incbin \\"' + OLD_JOURNAL + '\\",0,32");\nint filter(int length) { return 1; }'
|
||||
compiled_bytes = api("POST", path + "/filter", {
|
||||
"source": incbin, "label": "synthetic incbin regression",
|
||||
}, key=queue["read_key"] if args.action == "verify" else None,
|
||||
expected=422 if args.journal == "private" else 200)
|
||||
check(compiled_bytes["ok"] == (args.journal == "baseline"),
|
||||
"unexpected journal embedding result")
|
||||
expected = "700" if args.journal == "private" else "755"
|
||||
check(mode("/var/log/lighthouse") == expected, "unexpected journal root permissions")
|
||||
for journal in (state["journal"], OLD_JOURNAL):
|
||||
result = inside("test", "-r", journal, user="nobody")
|
||||
check((result.returncode != 0) == (args.journal == "private"),
|
||||
"unexpected unprivileged access to a synthetic journal")
|
||||
if args.journal == "private":
|
||||
check(mode(str(Path(state["journal"]).parent)) == "700", "new journal directory is not private")
|
||||
check(mode(state["journal"]) == "600", "new journal file is not private")
|
||||
print(f"PASS: {checks} checks ({args.action}, journal={args.journal}); no record values printed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user