test: add comprehensive v1.1 security, proxy/SFTP, automation/CLI & bundle tests

This commit is contained in:
tyuXX 2026-11-28 05:31:16 +00:00
parent f45d128c4f
commit a5a937850e
4 changed files with 1228 additions and 3 deletions

View file

@ -0,0 +1,388 @@
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import WebSocket from 'ws';
import { redactSecrets } from '../src/server/ai/redactor.js';
import { createGCoordinatorServer } from '../src/server/app.js';
import { resolveRuntimeLimits } from '../src/server/config/runtime-limits.js';
import { openDatabase } from '../src/server/db/database.js';
import { AuditService } from '../src/server/security/audit.js';
import {
EgressBlockedError,
assertEgressUrlAllowed,
fetchWithEgressGuard,
} from '../src/server/security/egress-guard.js';
import { RateLimiter } from '../src/server/security/guards.js';
import { EmergencyRecoveryService } from '../src/server/security/recovery-store.js';
import { VaultService } from '../src/server/security/vault.js';
import { AlertChannelSchema } from '../src/shared/schemas/alerts.schema.js';
const cleanups: Array<() => Promise<void> | void> = [];
class CookieJar {
private cookies = new Map<string, string>();
updateFrom(res: Response): void {
const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie;
const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : [];
for (const line of rawList) {
const first = line.split(';')[0] ?? '';
const eq = first.indexOf('=');
if (eq > 0) {
const name = first.slice(0, eq).trim();
const val = first.slice(eq + 1).trim();
if (val === '') this.cookies.delete(name);
else this.cookies.set(name, val);
}
}
}
header(): string {
return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
}
}
afterEach(async () => {
while (cleanups.length > 0) {
await cleanups.pop()!();
}
});
describe('v1.1 Security Hardening Suite', () => {
it('enforces Zero-Trust Egress Guard, CIDR allowlist, and redirect blocking', async () => {
await expect(assertEgressUrlAllowed('http://127.0.0.1:8080/api')).rejects.toBeInstanceOf(
EgressBlockedError,
);
await expect(
assertEgressUrlAllowed('http://169.254.169.254/latest/meta-data/'),
).rejects.toBeInstanceOf(EgressBlockedError);
await expect(assertEgressUrlAllowed('http://10.0.0.5/hook')).rejects.toBeInstanceOf(
EgressBlockedError,
);
let internalRedirectFollowed = false;
const srv = http.createServer((req, res) => {
if (req.url === '/ok') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hello-egress');
return;
}
if (req.url === '/redir') {
res.writeHead(302, { Location: `http://127.0.0.1:${port}/never-hit` });
res.end();
return;
}
if (req.url === '/never-hit') {
internalRedirectFollowed = true;
res.writeHead(200).end('leaked');
return;
}
res.writeHead(404).end();
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
cleanups.push(() => new Promise<void>((r) => srv.close(() => r())));
const port = (srv.address() as { port: number }).port;
const okRes = await fetchWithEgressGuard(
`http://127.0.0.1:${port}/ok`,
{ method: 'GET' },
{ allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 },
);
expect(okRes.status).toBe(200);
expect(await okRes.text()).toBe('hello-egress');
await expect(
fetchWithEgressGuard(
`http://127.0.0.1:${port}/redir`,
{ method: 'GET' },
{ allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 },
),
).rejects.toThrow();
expect(internalRedirectFollowed).toBe(false);
});
it('persists SQLite RateLimiter lockouts across instances and removes legacy recovery passwords', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-rl-'));
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }));
const dbPath = path.join(dir, 'gcoord.db');
const db1 = openDatabase(dbPath);
const rl1 = new RateLimiter({ db: db1 });
for (let i = 0; i < 6; i++) {
rl1.recordFailure('login', '198.51.100.77');
}
expect(rl1.check('login', '198.51.100.77').allowed).toBe(false);
db1.close();
const db2 = openDatabase(dbPath);
const rl2 = new RateLimiter({ db: db2 });
expect(rl2.check('login', '198.51.100.77').allowed).toBe(false);
db2.close();
// Passwordless emergency recovery + chmod 0600 Vault keyfile + seal()
const vault = new VaultService(path.join(dir, 'vault.enc'), {
keyFilePath: path.join(dir, 'vault.key'),
allowLocalKeyFile: true,
});
vault.initRuntime({ autoCreateIfMissing: true });
const keyMode = fs.statSync(path.join(dir, 'vault.key')).mode & 0o777;
expect(keyMode).toBe(0o600);
vault.unlockForModifications();
vault.upsertCredential({
id: 'wh-1',
name: 'Webhook Sec',
type: 'webhook-secret',
secret: 'super-secret-wh-value',
});
const recovery = new EmergencyRecoveryService(dir);
const bundle = recovery.syncState({
enabled: true,
vault,
username: 'admin',
passwordMetaList: [{ id: 'pw-1', label: 'Primary', createdAt: Date.now() }],
});
expect(bundle).not.toBeNull();
const recMode = fs.statSync(recovery.filePath).mode & 0o777;
expect(recMode).toBe(0o600);
const serialized = fs.readFileSync(recovery.filePath, 'utf8');
expect(serialized).not.toContain('passwordHash');
expect(serialized).not.toContain('plaintext');
let panicTriggered = false;
vault.onPanicLock(() => {
panicTriggered = true;
});
vault.seal();
expect(vault.sealState).toBe('sealed');
expect(vault.isRuntimeReady).toBe(false);
expect(panicTriggered).toBe(false);
const keyHex = fs.readFileSync(path.join(dir, 'vault.key'), 'utf8').trim();
vault.unlock(keyHex);
expect(vault.sealState).toBe('unlocked');
expect(vault.isRuntimeReady).toBe(true);
});
it('scales AI redactor linearly O(n) on huge malformed inputs and strips truncated PEM & Vault secrets', () => {
const bigPem = `-----BEGIN RSA PRIVATE KEY-----\n${'MIIEowIBAAKCAQEA'.repeat(8000)}\n`;
const sampleJson = `{"password":"my-db-pass-123","api_key":"sk-live-secret-999","token":"tok-abc"}`;
const payload = `${bigPem}\n${sampleJson}\nAuthorization: Bearer topsecretbearer\n`;
const started = Date.now();
const res = redactSecrets(payload, ['topsecretbearer', 'xy99']);
const elapsed = Date.now() - started;
expect(elapsed).toBeLessThan(1000);
expect(res.text).toContain('[REDACTED_PRIVATE_KEY]');
expect(res.text).not.toContain('my-db-pass-123');
expect(res.text).not.toContain('sk-live-secret-999');
expect(res.text).not.toContain('topsecretbearer');
expect(res.redactedCount).toBeGreaterThanOrEqual(3);
});
it('enforces idle timeout, real-time WS revocation, audit CSV formula neutralization, alert security events & throttle presets', async () => {
const low = resolveRuntimeLimits('low-resource');
const bal = resolveRuntimeLimits('balanced');
const unth = resolveRuntimeLimits('unthrottled');
expect(low.maxConcurrentMetricPolls).toBeLessThan(bal.maxConcurrentMetricPolls);
expect(unth.maxConcurrentMetricPolls).toBe(0); // 0 = unthrottled unlimited polls
expect(low.maxConcurrentWorkflows).toBeLessThan(bal.maxConcurrentWorkflows);
expect(bal.maxConcurrentWorkflows).toBeLessThan(unth.maxConcurrentWorkflows);
expect(low.argon2Concurrency).toBe(1);
// Non-webhook-secret creds are rejected by alerts test or config runtime check cleanly; schema parses valid channel
expect(() =>
AlertChannelSchema.parse({
id: 'ch1',
name: 'Ch',
type: 'generic',
url: 'https://hooks.example.com/1',
secretRef: 'wh-sec',
}),
).not.toThrow();
let receivedWebhook: Record<string, unknown> | null = null;
const whSrv = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on('data', (c: Buffer) => chunks.push(c));
req.on('end', () => {
try {
receivedWebhook = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>;
} catch {
receivedWebhook = { raw: Buffer.concat(chunks).toString('utf8') };
}
res.writeHead(200).end('ok');
});
});
await new Promise<void>((r) => whSrv.listen(0, '127.0.0.1', () => r()));
cleanups.push(() => new Promise<void>((r) => whSrv.close(() => r())));
const whPort = (whSrv.address() as { port: number }).port;
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-sec-e2e-'));
const server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
cleanups.push(async () => {
await server.close();
fs.rmSync(dataDir, { recursive: true, force: true });
});
const baseUrl = `http://127.0.0.1:${server.port}`;
const jar = new CookieJar();
let csrfToken = '';
const api = async (
pathname: string,
opts: { method?: string; body?: unknown; raw?: boolean } = {},
) => {
const headers: Record<string, string> = {};
if (jar.header()) headers.Cookie = jar.header();
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
const res = await fetch(`${baseUrl}${pathname}`, {
method: opts.method ?? 'GET',
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
jar.updateFrom(res);
if (opts.raw) {
return { status: res.status, text: await res.text(), data: {} as Record<string, unknown> };
}
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
return { status: res.status, data, text: '' };
};
const bootInfo = await api('/api/auth/bootstrap');
const totp = new OTPAuth.TOTP({
issuer: 'GCoordinator',
label: 'admin',
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)),
});
const bootRes = await api('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password: 'v11-hardening-password!',
totpCode: totp.generate(),
securityPreset: 'relaxed',
},
});
expect(bootRes.status).toBe(201);
csrfToken = String(bootRes.data.csrfToken);
// Initialize Vault + allow localhost egress for webhook test
await api('/api/vault/init', { method: 'POST', body: {} });
await api('/api/vault/credentials', {
method: 'POST',
body: { id: 'tok-not-wh', name: 'API Token', type: 'api-token', token: 'bearer-xyz' },
});
await api('/api/vault/credentials', {
method: 'POST',
body: { id: 'wh-valid', name: 'Webhook', type: 'webhook-secret', secret: 'wh-tok-1' },
});
await api('/api/auth/security-policy', {
method: 'PUT',
body: { egressAllowedCidrs: ['127.0.0.1/32'], sessionIdleTimeoutMin: 60 },
});
// Reject referencing non-webhook-secret credential in channel test
await api('/api/alerts/config', {
method: 'PUT',
body: {
channels: [
{
id: 'bad-ch',
name: 'Bad Channel',
type: 'generic',
url: `http://127.0.0.1:${whPort}/hook`,
secretRef: 'tok-not-wh',
enabled: true,
},
{
id: 'good-ch',
name: 'Good Channel',
type: 'generic',
url: `http://127.0.0.1:${whPort}/hook`,
secretRef: 'wh-valid',
enabled: true,
},
],
rules: [
{
id: 'sec-lockout',
name: 'Auth Lockout Event',
kind: 'security-event',
events: ['auth.lockout'],
severity: 'critical',
forConsecutivePolls: 1,
cooldownSec: 0,
channelIds: ['good-ch'],
enabled: true,
},
],
},
});
const badTest = await api('/api/alerts/channels/bad-ch/test', { method: 'POST' });
expect(badTest.status === 400 || badTest.data.ok === false).toBe(true);
// Trigger security-event alert -> webhook receives notification
await server.alertEngine.emitSecurityEvent('auth.lockout', {
message: 'Repeated login failure from 203.0.113.9',
});
expect(receivedWebhook).not.toBeNull();
// Audit formula-injection neutralization + filtering + CSV/NDJSON export
server.auditService.log({
action: 'custom.formula',
actorIp: '127.0.0.1',
target: '=CMD|calc',
status: 'denied',
details: 'formula-needle',
});
const filteredAudit = await api('/api/audit?action=custom.formula&status=denied&q=formula-needle');
expect(filteredAudit.status).toBe(200);
expect(filteredAudit.data.total).toBe(1);
const csvRes = await api('/api/audit/export?format=csv&action=custom.formula', { raw: true });
expect(csvRes.status).toBe(200);
expect(csvRes.text).toContain('"\'=CMD|calc"');
const ndjsonRes = await api('/api/audit/export?format=ndjson&action=custom.formula', { raw: true });
expect(ndjsonRes.status).toBe(200);
const firstRow = JSON.parse(ndjsonRes.text.trim().split('\n')[0]!) as { action: string };
expect(firstRow.action).toBe('custom.formula');
// Real-time WS close with 4001 on logout/revocation
const wsCloseCode = await new Promise<number>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/ws`, {
headers: { Cookie: jar.header() },
});
ws.once('open', () => {
void api('/api/auth/logout', { method: 'POST' });
});
ws.once('close', (code) => resolve(code));
ws.once('error', reject);
});
expect(wsCloseCode).toBe(4001);
// Log back in and verify sliding sessionIdleTimeoutMin invalidates idle session
await new Promise((r) => setTimeout(r, 20));
const reLogin = await api('/api/auth/login', {
method: 'POST',
body: { username: 'admin', passwords: ['v11-hardening-password!'], codes: [] },
});
expect(reLogin.status).toBe(200);
server.db.prepare('UPDATE sessions SET last_seen_at = ?').run(Date.now() - 120 * 60_000);
const afterIdle = await api('/api/auth/status');
expect(afterIdle.status).toBe(200);
expect(afterIdle.data.authenticated).toBe(false);
});
});