Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions server/aws-public.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// The AWS inventory before sign-in: spend and breakdowns only. No resource
// The AWS inventory before sign-in: resource totals and breakdowns only. No resource
// names, ids, addresses, DNS names or tags beyond the Dash network, and no
// list of idle resources (that is for members).
const add = (map, key, fields) => {
Expand All @@ -8,7 +8,7 @@ const add = (map, key, fields) => {
};
const rows = (map) => [...map.values()].map((e) => ({ ...e, memoryGiB: Math.round(e.memoryGiB) })).sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));

export function publicInventory(inv) {
export function publicInventory(inv, { includeCosts = false } = {}) {
const running = inv.instances.filter((i) => i.state === 'running');
const byNetwork = new Map(), byRegion = new Map(), byFamily = new Map(), byArch = new Map();
for (const i of running) {
Expand All @@ -21,7 +21,7 @@ export function publicInventory(inv) {
for (const v of inv.volumes) ebsByType.set(v.type || 'unknown', (ebsByType.get(v.type || 'unknown') || 0) + (v.sizeGiB || 0));
const lbByType = {};
for (const l of inv.loadBalancers) lbByType[l.type] = (lbByType[l.type] || 0) + 1;
const c = inv.costs;
const c = includeCosts ? inv.costs : null;
return {
public: true, at: inv.at, regions: inv.regions.length,
regionsInUse: new Set([...inv.instances, ...inv.volumes, ...inv.addresses, ...inv.loadBalancers, ...inv.natGateways].map((x) => x.region)).size,
Expand All @@ -34,6 +34,6 @@ export function publicInventory(inv) {
ecrImages: inv.ecr.reduce((a, r) => a + (r.images || 0), 0), s3Buckets: inv.s3.length },
network: { loadBalancers: inv.loadBalancers.length, loadBalancersByType: lbByType, natGateways: inv.natGateways.length, elasticIps: inv.addresses.length, cloudfront: inv.cloudfront.length },
serverless: { lambda: inv.lambda.length, dynamodb: inv.dynamodb.length },
costs: c ? { at: c.at, month: c.month, currency: c.currency, monthToDate: c.monthToDate, monthEndEstimate: c.monthEndEstimate, lastMonth: c.lastMonth, byService: c.byService, daily: c.daily } : null,
...(includeCosts ? { costs: c ? { at: c.at, month: c.month, currency: c.currency, monthToDate: c.monthToDate, monthEndEstimate: c.monthEndEstimate, lastMonth: c.lastMonth, byService: c.byService, daily: c.daily } : null } : {}),
};
}
38 changes: 26 additions & 12 deletions server/web.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, watch, openSync, readSync, closeSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { websiteReport } from './websites.js';
import { createAuth } from './auth.js';
import { createCi } from './ci.js';
import { createOrgQueue } from './ci-queue.js';
Expand All @@ -28,6 +29,21 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{1

const LIFECYCLE_ACTIONS = ['create-devnet', 'delete-devnet', 'devnet-services', 'devnet-platform', 'platform-reset'];

// Memo with a fixed lifetime. Expired entries are dropped on insert, so keys
// that embed a timestamp (the AWS inventory) cannot accumulate.
export function ttlCache(clock, ttl = 15_000) {
const entries = new Map();
const cached = (key, fn) => {
const hit = entries.get(key);
if (hit && clock() - hit.at < ttl) return hit.value;
for (const [k, e] of entries) if (clock() - e.at >= ttl) entries.delete(k);
const value = fn();
entries.set(key, { at: clock(), value });
return value;
};
return Object.assign(cached, { delete: (key) => entries.delete(key), size: () => entries.size });
}

export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, clock = Date.now, ciGithub = null, ciQueue = {}, mainnetReportToken = process.env.MAINNET_REPORT_TOKEN } = {}) {
const settingsPath = join(dataDir, 'settings.json');
const dirs = { state: join(dataDir, 'state'), requests: join(dataDir, 'requests'), ops: join(dataDir, 'ops') };
Expand Down Expand Up @@ -138,6 +154,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl
res.status(stale ? 503 : 200).json({ ...body, stale });
});

app.get('/api/websites', (req, res) => res.json(websiteReport(dataDir, clock())));
app.get('/api/health', (req, res) => res.json({ service: 'dash-status', status: 'ok' }));
app.get('/api/remediation', (req, res) => {
reloadSettings();
Expand Down Expand Up @@ -181,7 +198,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl
// A change to a private job is announced to members only: its timing is private too.
const pushQueue = (scope) => {
if (!scope) return;
if (scope === 'all') publicCache.delete('ci-queue');
if (scope === 'all') cached.delete('ci-queue');
for (const members of scope === 'all' ? [true, false] : [true]) {
const key = `ci-queue|${members}`;
clearTimeout(debounce.get(key));
Expand Down Expand Up @@ -395,16 +412,10 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl
res.json({ activityHistory });
});

// Infrastructure pages: full detail for any account with access; before
// sign-in a sanitized view (statistics and spend, nothing identifying).
const publicCache = new Map();
const cached = (key, fn) => {
const hit = publicCache.get(key);
if (hit && clock() - hit.at < 15_000) return hit.value;
const value = fn();
publicCache.set(key, { at: clock(), value });
return value;
};
// Infrastructure pages: full detail for any account with access; otherwise a
// sanitized view (statistics, nothing identifying). Spend is never shown
// before sign-in.
const cached = ttlCache(clock);
app.get('/api/ci', (req, res) => res.json(memberOf(settings, user(req)) ? ci.summary({ admin: isAdmin(req) }) : cached('ci', () => ci.publicSummary())));
app.get('/api/ci/queue/capacity', (req, res) => {
const window = typeof req.query.window === 'string' ? req.query.window : '7d';
Expand All @@ -423,7 +434,10 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl
app.get('/api/aws', (req, res) => {
const inv = readJSON(join(awsDir, 'inventory.json'));
if (!inv) return res.status(404).json({ error: 'No AWS inventory yet; the agent collects it every 10 minutes' });
res.json(memberOf(settings, user(req)) ? inv : cached(`aws|${inv.at}`, () => publicInventory(inv)));
const viewer = user(req);
// Cost visibility follows the authenticated session, never query parameters.
// Keep signed-in summaries separate from the anonymous projection cache.
res.vary('Cookie').json(memberOf(settings, viewer) ? inv : cached(`aws|${viewer ? 'signed-in' : 'public'}|${inv.at}`, () => publicInventory(inv, { includeCosts: !!viewer })));
});

// GitHub account lookup so admins can grant access by login.
Expand Down
55 changes: 51 additions & 4 deletions server/web.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createHmac } from 'node:crypto';
import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createWeb } from './web.js';
import { createWeb, ttlCache } from './web.js';
import { DEFAULT_SETTINGS } from '../shared/settings.js';

async function start(userId = 9920871, extraUsers = [], options = {}) {
Expand Down Expand Up @@ -239,20 +239,51 @@ test('CI: admins issue reporter tokens; reporters post with them; infrastructure
costs: { at: 'now', month: '2026-09', monthToDate: 3270.85, monthEndEstimate: 3503.4, lastMonth: 3109.17, byService: [{ service: 'EC2 - Other', amount: 1178.9 }], daily: [] } }));
assert.equal((await (await w.req('/api/aws')).json()).at, 'now');
assert.equal((await (await w.req('/api/aws')).json()).instances[0].publicIp, '192.0.2.9', 'members see the inventory');
assert.equal((await (await w.req('/api/aws')).json()).costs.monthToDate, 3270.85, 'members retain costs');
assert.equal((await w.req(`/api/ci/reporters/${id}`, { method: 'DELETE', headers: { 'x-csrf-token': csrf } })).status, 200);
// Signed out: spend and breakdowns, nothing that names or locates a resource.
// Signed out: resource aggregates, no spend or resource identity.
await w.req('/api/auth/logout', { method: 'POST', headers: { 'x-csrf-token': csrf } });
const pub = await (await w.req('/api/aws')).json();
assert.equal(pub.public, true);
assert.deepEqual(pub.byNetwork, [{ label: 'testnet', count: 1, vcpus: 2, memoryGiB: 2 }]);
assert.equal(pub.costs.monthToDate, 3270.85);
assert.equal(pub.costs, undefined);
const text = JSON.stringify(pub);
for (const leak of ['192.0.2.9', 'i-0123456789abcdef0', 'dn-testnet-masternode-1', 'testnet-alb', 'elb.amazonaws', 'killdate', 'rs-dapi', 'quorums.testnet', 'dash-terraform-state', 'vol-1'])
for (const leak of ['3270.85', '3503.4', '3109.17', '1178.9', '192.0.2.9', 'i-0123456789abcdef0', 'dn-testnet-masternode-1', 'testnet-alb', 'elb.amazonaws', 'killdate', 'rs-dapi', 'quorums.testnet', 'dash-terraform-state', 'vol-1'])
assert.ok(!text.includes(leak), `leaked ${leak}`);
assert.equal((await post(`Bearer ${token}`)).status, 401);
} finally { w.close(); }
});

test('AWS costs require a valid session, including after cache warmup and logout', async () => {
const w = await start(42); // Signed-in user without inventory membership.
try {
const costs = { monthToDate: 1234.56, monthEndEstimate: 2345.67, lastMonth: 3456.78,
byService: [{ service: 'Fixture service', amount: 456.78 }], daily: [{ day: '2026-10-01', amount: 567.89 }] };
writeFileSync(join(w.dataDir, 'aws', 'inventory.json'), JSON.stringify({ at: 'fixture', regions: [],
instances: [], volumes: [], addresses: [], natGateways: [], loadBalancers: [], lambda: [],
dynamodb: [], ecr: [], snapshots: [], cloudfront: [], s3: [], costs }));
const anonymous = async (path = '/api/aws', options) => {
const response = await w.req(path, options);
assert.equal(response.status, 200);
assert.equal(response.headers.get('cache-control'), 'no-store');
assert.match(response.headers.get('vary'), /Cookie/i);
const body = await response.json();
assert.equal(body.public, true);
assert.equal(Object.hasOwn(body, 'costs'), false);
for (const amount of [1234.56, 2345.67, 3456.78, 456.78, 567.89])
assert.ok(!JSON.stringify(body).includes(String(amount)));
};
await anonymous('/api/aws?as=9920871'); // Claimed identity never grants costs.
const csrf = await w.login();
const signedIn = await (await w.req('/api/aws?as=public')).json();
assert.equal(signedIn.public, true, 'sign-in does not grant detailed inventory');
assert.deepEqual(signedIn.costs, costs, 'signed-in summaries retain all costs');
await anonymous('/api/aws?as=42', { headers: { cookie: 'dash-session=invalid' } });
assert.equal((await w.req('/api/auth/logout', { method: 'POST', headers: { 'x-csrf-token': csrf } })).status, 200);
await anonymous(); // Same inventory timestamp must not reuse signed-in costs.
} finally { w.close(); }
});

test('console devnet connection files reach members only', async () => {
const w = await start();
try {
Expand Down Expand Up @@ -444,3 +475,19 @@ test('a deleted devnet no longer blocks its name in the new-devnet form', async
assert.ok(existing.includes('devnet-bonsai') && existing.includes('devnet-stuck') && existing.includes('testnet'));
} finally { w.close(); }
});

test('public projection cache keeps its 15 s lifetime and evicts expired keys on insert', () => {
let now = 0, calls = 0;
const cached = ttlCache(() => now);
for (const at of ['a', 'b']) for (const view of ['public', 'signed-in']) cached(`aws|${view}|${at}`, () => ++calls);
assert.equal(cached('aws|public|a', () => ++calls), 1, 'a live entry is reused');
now = 14_999;
assert.equal(cached('ci', () => ++calls), 5);
assert.equal(cached.size(), 5, 'nothing is evicted before it expires');
now = 15_000;
assert.equal(cached('aws|public|c', () => ++calls), 6);
assert.equal(cached.size(), 2, 'entries from the previous inventory are gone');
assert.equal(cached('ci', () => ++calls), 5);
cached.delete('ci');
assert.equal(cached('ci', () => ++calls), 7);
});
70 changes: 70 additions & 0 deletions server/websites.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';

// Public-data-only boundary: this file is served to anonymous callers, so only
// allowlisted, type-checked fields survive. Unknown fields never pass through.
const MAX_SITES = 16, MAX_HISTORY = 2016; // seven days of five-minute samples
const integer = (v) => Number.isSafeInteger(v) && v >= 0 ? v : null;
const finite = (v) => Number.isFinite(v) && v >= 0 ? v : null;
const percent = (v) => finite(v) !== null && v <= 100 ? v : null;
// Date.parse rolls an impossible date forward (30 February becomes 2 March), so the written date must be a real one.
const realDate = (v) => { const m = /^(\d{4})-(\d\d)-(\d\d)/.exec(v); return !!m && new Date(Date.UTC(m[1], m[2] - 1, m[3])).toISOString().startsWith(m[0]); };
const timestamp = (v) => typeof v === 'string' && realDate(v) && Number.isFinite(Date.parse(v)) ? new Date(v).toISOString() : null;
const text = (v, max) => typeof v === 'string' ? v.slice(0, max) : null;
// Header-derived values may arrive as numbers or digit strings (HTTP version, Age).
const seconds = (v) => integer(typeof v === 'string' && /^\d{1,9}$/.test(v) ? Number(v) : v);
const token = (v) => ['string', 'number'].includes(typeof v) && /^[\w./-]{1,16}$/.test(String(v)) ? String(v) : null;
// Interpolated into an https:// link: a bare DNS name only (no port, path, userinfo or IP literal).
const hostname = (v) => typeof v === 'string' && v.length <= 253 && /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(v) ? v.toLowerCase() : null;
function httpsUrl(v) {
if (typeof v !== 'string' || v.length > 2048) return null;
try { const u = new URL(v); return u.protocol === 'https:' && !u.username && !u.password ? u.href : null; } catch { return null; }
}
const PHASES = ['dnsMs', 'tcpMs', 'tlsMs', 'waitMs', 'downloadMs'];

function sample(s) {
const at = timestamp(s?.at);
if (!at) return null;
return { at, ok: s.ok === true, status: integer(s.status), error: text(s.error, 200),
ttfbMs: finite(s.ttfbMs), totalMs: finite(s.totalMs), redirects: integer(s.redirects), redirectMs: finite(s.redirectMs),
httpVersion: token(s.httpVersion), finalUrl: httpsUrl(s.finalUrl), htmlBytes: integer(s.htmlBytes), transferBytes: integer(s.transferBytes),
encoding: text(s.encoding, 32), cacheStatus: text(s.cacheStatus, 64), age: seconds(s.age), cacheControl: text(s.cacheControl, 200),
phases: Object.fromEntries(PHASES.map((k) => [k, finite(s.phases?.[k])])),
hints: { blockingScripts: integer(s.hints?.blockingScripts), imagesWithoutDimensions: integer(s.hints?.imagesWithoutDimensions) } };
}

// A site is usable only with a link-safe name and a latest sample; the page renders both unconditionally.
function site(s) {
const name = hostname(s?.site), latest = sample(s?.latest);
if (!name || !latest) return null;
const d = s.summary24h;
return { site: name, latest,
summary24h: { ttfbP50Ms: finite(d?.ttfbP50Ms), ttfbP95Ms: finite(d?.ttfbP95Ms), successes: integer(d?.successes), samples: integer(d?.samples), successPercent: percent(d?.successPercent) },
history: (Array.isArray(s.history) ? s.history : []).map(sample).filter(Boolean).sort((a, b) => Date.parse(a.at) - Date.parse(b.at)).slice(-MAX_HISTORY) };
}

function normalize(report) {
if (report?.schemaVersion !== 1 || !Array.isArray(report.sites)) return null;
const sites = report.sites.slice(0, MAX_SITES).map(site).filter((s, i, all) => s && all.findIndex((x) => x?.site === s.site) === i);
return { generatedAt: timestamp(report.generatedAt), location: text(report.location, 80), sites };
}

// One parse per collector write. A file modified within the last two seconds is
// not trusted as a cache key: a second write could share its mtime and size.
// A failed read or parse is never cached: its cause can clear without changing the key.
let cache = null;
function load(file) {
const st = statSync(file), key = `${file}|${st.mtimeMs}|${st.size}|${st.ino}`;
if (cache?.key === key) return cache.report;
const report = (() => { try { return normalize(JSON.parse(readFileSync(file, 'utf8'))); } catch { return null; } })();
cache = report && Date.now() - st.mtimeMs > 2000 ? { key, report } : null;
return report;
}

export function websiteReport(dataDir, now = Date.now()) {
let report = null;
try { report = load(join(dataDir, 'websites', 'report.json')); } catch { /* A missing collector is unknown, not healthy. */ }
if (!report) return { stale: true, sites: [], error: 'Website checks have not reported yet.' };
const age = now - Date.parse(report.generatedAt);
return { ...report, stale: !Number.isFinite(age) || age > 12 * 60_000 || age < -60_000 };
}
Loading
Loading