From 62cc6f73c650100fa1e9d19d75009c25fd2e9dc2 Mon Sep 17 00:00:00 2001 From: George Lambert Date: Fri, 11 Sep 2026 19:10:11 -0400 Subject: [PATCH] Initial import of verae-access-leaf from zapier monorepo --- NATS.md | 9 +++++ README.md | 13 ++++++ package-lock.json | 46 +++++++++++++++++++++ package.json | 14 +++++++ src/allow.js | 28 +++++++++++++ src/server.js | 98 +++++++++++++++++++++++++++++++++++++++++++++ test/health.test.js | 63 +++++++++++++++++++++++++++++ 7 files changed, 271 insertions(+) create mode 100644 NATS.md create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/allow.js create mode 100644 src/server.js create mode 100644 test/health.test.js diff --git a/NATS.md b/NATS.md new file mode 100644 index 0000000..7f9d539 --- /dev/null +++ b/NATS.md @@ -0,0 +1,9 @@ +# NATS — verae-access-leaf + +| Direction | Address | Kind | +|-----------|---------|------| +| IN | `verae.access.leaf.in` | queue `access-leaf` `{ token, target, payload, principal }` | +| OUT | `verae.access.authz.check` | request-reply | +| OUT | allowed `target` only | pub after allow | + +Do not export `verae.billing.*` to the leaf account. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ce2f273 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# verae-access-leaf + +**Server-to-server leaf node** access plane. Remote machines connect as NATS leaf nodes (or POST `/forward` with a leaf token). They never get the core billing subjects. + +**Forgejo:** https://git.georgelambert.org/marchon/verae-access-leaf + +```text +remote leaf → verae.access.leaf.in → authz.check → verae.archive.put | jobs.* +``` + +Denied: `verae.billing.balance.adjust`, `verae.billing.statement.get`. A compromised WORM/leaf cannot credit customers. + +`LEAF_TOKEN` required. Port `:3023`. Do not publish NATS `4222` to the internet; leaf nodes use a private leafnode port / tunnel. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..740e2af --- /dev/null +++ b/package-lock.json @@ -0,0 +1,46 @@ +{ + "name": "verae-access-leaf", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "verae-access-leaf", + "version": "0.1.0", + "dependencies": { + "nats": "^2.28.2" + } + }, + "node_modules/nats": { + "version": "2.29.3", + "resolved": "https://registry.npmjs.org/nats/-/nats-2.29.3.tgz", + "integrity": "sha512-tOQCRCwC74DgBTk4pWZ9V45sk4d7peoE2njVprMRCBXrhJ5q5cYM7i6W+Uvw2qUrcfOSnuisrX7bEx3b3Wx4QA==", + "deprecated": "Package moved. Use @nats-io/transport-node from https://github.com/nats-io/nats.js", + "license": "Apache-2.0", + "dependencies": { + "nkeys.js": "1.1.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/nkeys.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz", + "integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==", + "license": "Apache-2.0", + "dependencies": { + "tweetnacl": "1.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..52dd272 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "verae-access-leaf", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Server-to-server NATS leaf-node access plane", + "scripts": { + "start": "node src/server.js", + "test": "node --test test/*.test.js" + }, + "dependencies": { + "nats": "^2.28.2" + } +} diff --git a/src/allow.js b/src/allow.js new file mode 100644 index 0000000..abd2703 --- /dev/null +++ b/src/allow.js @@ -0,0 +1,28 @@ +import fs from 'node:fs'; + +const FALLBACK = [ + 'verae.archive.put', + 'verae.archive.query', + 'verae.archive.reply.', + 'verae.zapier.jobs.watch', + 'verae.zapier.jobs.events', + 'verae.zapier.webhooks.deliver', +]; + +export function leafAllowList() { + const p = process.env.NATS_POLICY_PATH; + if (p && fs.existsSync(p)) { + try { + return JSON.parse(fs.readFileSync(p, 'utf8')).leafAllow || FALLBACK; + } catch { + return FALLBACK; + } + } + return FALLBACK; +} + +export function leafAllowed(subject) { + return leafAllowList().some((p) => + p.endsWith('.') ? subject.startsWith(p) : subject === p || subject.startsWith(`${p}.`), + ); +} diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..82d8798 --- /dev/null +++ b/src/server.js @@ -0,0 +1,98 @@ +#!/usr/bin/env node +/** + * Server-to-server / NATS leaf-node ingress. + * Remote servers publish verae.access.leaf.in; this process authz-checks + * then forwards only allowed internal subjects (archive + jobs, never billing). + */ +import http from 'node:http'; +import { leafAllowed } from './allow.js'; + +const PORT = Number(process.env.PORT || 3023); +const AUTHZ = (process.env.AUTHZ_URL || 'http://127.0.0.1:3020').replace(/\/$/, ''); +const TOKEN = process.env.LEAF_TOKEN || 'leaf-dev-token'; +const PLANE = 'leaf'; +const IN = 'verae.access.leaf.in'; + +async function check(subject, principal) { + const r = await fetch(`${AUTHZ}/check`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ plane: PLANE, subject, principal }), + }); + return r.json(); +} + +function authorizedToken(got) { + return got && got === TOKEN; +} + +async function forward(body) { + if (!authorizedToken(body.token)) { + return { status: 401, body: { allow: false, reason: 'bad leaf token' } }; + } + const target = body.target || body.subject; + if (!leafAllowed(target)) { + return { status: 403, body: { allow: false, reason: `leaf policy denies ${target}` } }; + } + const gate = await check(target, body.principal || 'leaf'); + if (!gate.allow) return { status: 403, body: gate }; + const url = process.env.NATS_URL; + if (url) { + const { connect, StringCodec } = await import('nats'); + const nc = await connect({ servers: url.split(','), name: 'verae-access-leaf' }); + const sc = StringCodec(); + nc.publish(gate.subject, sc.encode(JSON.stringify({ ...(body.payload || {}), plane: PLANE }))); + await nc.flush(); + await nc.close(); + } + return { status: 200, body: { forwarded: gate.subject, plane: PLANE, nats: Boolean(url) } }; +} + +async function startNats() { + const url = process.env.NATS_URL; + if (!url) return; + const { connect, StringCodec } = await import('nats'); + const nc = await connect({ servers: url.split(','), name: 'verae-access-leaf' }); + const sc = StringCodec(); + (async () => { + for await (const m of nc.subscribe(IN, { queue: 'access-leaf' })) { + let payload = {}; + try { + payload = JSON.parse(sc.decode(m.data) || '{}'); + } catch { + payload = {}; + } + const out = await forward(payload); + if (m.reply) m.respond(sc.encode(JSON.stringify(out.body))); + } + })(); + process.stdout.write(`access-leaf nats ${IN}\n`); +} + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`); + const json = (code, obj) => { + res.writeHead(code, { 'content-type': 'application/json' }); + res.end(JSON.stringify(obj)); + }; + try { + if (req.method === 'GET' && url.pathname === '/health') { + return json(200, { ok: true, role: 'verae-access-leaf', plane: PLANE, ingress: IN }); + } + if (req.method === 'POST' && url.pathname === '/forward') { + const chunks = []; + for await (const c of req) chunks.push(c); + const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); + const out = await forward(body); + return json(out.status, out.body); + } + json(404, { error: 'not found' }); + } catch (err) { + json(502, { error: err.message }); + } +}); + +server.listen(PORT, '0.0.0.0', () => { + process.stdout.write(`verae-access-leaf http://0.0.0.0:${PORT}/ plane=${PLANE}\n`); +}); +startNats().catch((err) => process.stderr.write(`nats optional: ${err.message}\n`)); diff --git a/test/health.test.js b/test/health.test.js new file mode 100644 index 0000000..1fb1d9a --- /dev/null +++ b/test/health.test.js @@ -0,0 +1,63 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); +const authzRoot = path.join(root, '..', 'verae-access-authz'); + +test('leaf forwards archive.put and refuses billing adjust', async () => { + const authzPort = 18026; + const leafPort = 18027; + const authz = spawn(process.execPath, ['src/server.js'], { + cwd: authzRoot, + env: { ...process.env, PORT: String(authzPort) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const leaf = spawn(process.execPath, ['src/server.js'], { + cwd: root, + env: { + ...process.env, + PORT: String(leafPort), + AUTHZ_URL: `http://127.0.0.1:${authzPort}`, + LEAF_TOKEN: 'leaf-dev-token', + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + await new Promise((r) => setTimeout(r, 500)); + try { + const h = await (await fetch(`http://127.0.0.1:${leafPort}/health`)).json(); + assert.equal(h.plane, 'leaf'); + const ok = await fetch(`http://127.0.0.1:${leafPort}/forward`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + token: 'leaf-dev-token', + target: 'verae.archive.put', + principal: 'ns2', + payload: { sha256: 'abc' }, + }), + }); + assert.equal(ok.status, 200); + const no = await fetch(`http://127.0.0.1:${leafPort}/forward`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + token: 'leaf-dev-token', + target: 'verae.billing.balance.adjust', + payload: { customerId: 'c1', cents: 9999 }, + }), + }); + assert.equal(no.status, 403); + const bad = await fetch(`http://127.0.0.1:${leafPort}/forward`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ token: 'wrong', target: 'verae.archive.put' }), + }); + assert.equal(bad.status, 401); + } finally { + leaf.kill('SIGTERM'); + authz.kill('SIGTERM'); + } +});