T-14: tests
This commit is contained in:
parent
88022a0790
commit
3e1f108c6f
2 changed files with 275 additions and 0 deletions
270
test/unit/env-safety-ipv4-loopback-qa.test.ts
Normal file
270
test/unit/env-safety-ipv4-loopback-qa.test.ts
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { setLoggerConfig } from '@stock-bot/logger';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
stockAppSchema,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
||||
const QA_WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/;
|
||||
const QA_PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/;
|
||||
const QA_POSTGRES_ERROR = /development environment cannot target QA PostgreSQL/;
|
||||
|
||||
function makeDevConfig(overrides: {
|
||||
mongoUri?: string;
|
||||
mongoReadUri?: string;
|
||||
mongoReadOnly?: boolean;
|
||||
pgHost?: string;
|
||||
pgPort?: number;
|
||||
pgDatabase?: string;
|
||||
}): StockAppConfig {
|
||||
return stockAppSchema.parse({
|
||||
name: 'stock-bot',
|
||||
version: '1.0.0',
|
||||
environment: 'development',
|
||||
service: { name: 'stock-bot', port: 2002, host: '127.0.0.1' },
|
||||
log: { level: 'info', format: 'json' },
|
||||
database: {
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: overrides.pgHost ?? 'localhost',
|
||||
port: overrides.pgPort ?? 5433,
|
||||
database: overrides.pgDatabase ?? 'trading_bot_dev',
|
||||
user: 'dev_user',
|
||||
password: 'dev_pass',
|
||||
ssl: false,
|
||||
},
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri:
|
||||
overrides.mongoUri ??
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
overrides.mongoReadUri ??
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
|
||||
readOnly: overrides.mongoReadOnly ?? false,
|
||||
database: 'stock_dev',
|
||||
},
|
||||
questdb: { enabled: false, host: 'localhost', ilpPort: 9010, httpPort: 9100, pgPort: 8813 },
|
||||
dragonfly: { enabled: true, host: 'localhost', port: 6380 },
|
||||
},
|
||||
providers: {
|
||||
yahoo: {
|
||||
name: 'yahoo',
|
||||
enabled: false,
|
||||
priority: 1,
|
||||
timeout: 30000,
|
||||
baseUrl: 'https://query1.finance.yahoo.com',
|
||||
},
|
||||
qm: {
|
||||
name: 'qm',
|
||||
enabled: false,
|
||||
priority: 2,
|
||||
username: '',
|
||||
password: '',
|
||||
baseUrl: 'https://app.quotemedia.com/quotetools',
|
||||
webmasterId: '',
|
||||
},
|
||||
ib: {
|
||||
name: 'ib',
|
||||
enabled: false,
|
||||
priority: 3,
|
||||
gateway: { host: 'localhost', port: 5000, clientId: 1 },
|
||||
marketDataType: 'delayed',
|
||||
},
|
||||
eod: {
|
||||
name: 'eod',
|
||||
enabled: false,
|
||||
priority: 4,
|
||||
apiKey: '',
|
||||
baseUrl: 'https://eodhistoricaldata.com/api',
|
||||
tier: 'free',
|
||||
},
|
||||
},
|
||||
features: {},
|
||||
});
|
||||
}
|
||||
|
||||
function ingestionBlocked(host: string): boolean {
|
||||
const cfg = makeDevConfig({ mongoUri: `mongodb://u:p@${host}:27017/stock` });
|
||||
try {
|
||||
assertEnvironmentSafety(cfg, 'dataIngestion', {});
|
||||
return false;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && QA_WRITE_ERROR.test(error.message)) {
|
||||
return true;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// mulberry32: tiny deterministic PRNG so the property corpus is identical on every run.
|
||||
function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function encodePart(value: number, rand: () => number): string {
|
||||
const radix = Math.floor(rand() * 3);
|
||||
if (radix === 0) {
|
||||
return value.toString(10);
|
||||
}
|
||||
if (radix === 1) {
|
||||
const zeros = '0'.repeat(1 + Math.floor(rand() * 2));
|
||||
return zeros + value.toString(8);
|
||||
}
|
||||
const prefix = rand() < 0.5 ? '0x' : '0X';
|
||||
const digits = value.toString(16);
|
||||
return prefix + (rand() < 0.5 ? digits.toUpperCase() : digits);
|
||||
}
|
||||
|
||||
/** Encode a 32-bit address in a random 1-4 part inet_aton spelling with random radix per part. */
|
||||
function encodeIpv4(addr: number, rand: () => number): string {
|
||||
const a = (addr >>> 24) & 0xff;
|
||||
const b = (addr >>> 16) & 0xff;
|
||||
const c = (addr >>> 8) & 0xff;
|
||||
const d = addr & 0xff;
|
||||
const arity = 1 + Math.floor(rand() * 4);
|
||||
const parts =
|
||||
arity === 1
|
||||
? [addr >>> 0]
|
||||
: arity === 2
|
||||
? [a, ((b << 16) | (c << 8) | d) >>> 0]
|
||||
: arity === 3
|
||||
? [a, b, ((c << 8) | d) >>> 0]
|
||||
: [a, b, c, d];
|
||||
return parts.map(part => encodePart(part, rand)).join('.');
|
||||
}
|
||||
|
||||
function dotted(addr: number): string {
|
||||
return [(addr >>> 24) & 0xff, (addr >>> 16) & 0xff, (addr >>> 8) & 0xff, addr & 0xff].join('.');
|
||||
}
|
||||
|
||||
describe('Environment safety QA: numeric IPv4 loopback normalization (T-14)', () => {
|
||||
test('pipeline guard blocks reported spellings with port omitted, for both non-read-only and admin read URIs', () => {
|
||||
for (const host of ['127.1', '2130706433', '0x7f000001', '0177.0.0.1']) {
|
||||
for (const authority of [`${host}`, `${host}:`]) {
|
||||
const nonReadOnly = makeDevConfig({
|
||||
mongoReadUri: `mongodb://studio_stock_bot_read:secret@${authority}/stock?authSource=stock`,
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(nonReadOnly, 'dataPipeline', {})).toThrow(
|
||||
QA_PIPELINE_ERROR
|
||||
);
|
||||
|
||||
const admin = makeDevConfig({
|
||||
mongoReadUri: `mongodb://trading_admin:pw@${authority}/stock?authSource=admin`,
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(admin, 'dataPipeline', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).toThrow(QA_PIPELINE_ERROR);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('seeded property: guard blocks exactly 127.0.0.0/8 and 0.0.0.0 across random radix/arity spellings, matching WHATWG URL', () => {
|
||||
const rand = mulberry32(0x7014);
|
||||
const addresses: number[] = [0, 0x7f000000, 0x7f000001, 0x7fffffff, 0x7effffff, 0x80000000];
|
||||
for (let i = 0; i < 400; i++) {
|
||||
const bucket = Math.floor(rand() * 4);
|
||||
if (bucket === 0) {
|
||||
addresses.push((0x7f000000 | Math.floor(rand() * 0x1000000)) >>> 0);
|
||||
} else if (bucket === 1) {
|
||||
// Neighbours of 127/8 and of 0.0.0.0 to catch off-by-one masks.
|
||||
const near = [0x7e000000, 0x80000000, 0x00000000, 0x00ffffff][Math.floor(rand() * 4)] ?? 0;
|
||||
addresses.push((near + Math.floor(rand() * 0x1000000)) >>> 0);
|
||||
} else {
|
||||
addresses.push(Math.floor(rand() * 0x100000000) >>> 0);
|
||||
}
|
||||
}
|
||||
|
||||
const mismatches: string[] = [];
|
||||
for (const addr of addresses) {
|
||||
for (let variant = 0; variant < 3; variant++) {
|
||||
const spelling = encodeIpv4(addr, rand);
|
||||
// Sanity-check the generator against an independent WHATWG IPv4 parser.
|
||||
expect(new URL(`http://${spelling}/`).hostname).toBe(dotted(addr));
|
||||
|
||||
const expected = (addr >>> 24) === 127 || addr === 0;
|
||||
if (ingestionBlocked(spelling) !== expected) {
|
||||
mismatches.push(`${spelling} (${dotted(addr)}) expected blocked=${expected}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(mismatches).toEqual([]);
|
||||
});
|
||||
|
||||
test('4294967295 and 0xffffffff (255.255.255.255) parse but are not treated as loopback', () => {
|
||||
for (const host of ['4294967295', '0xffffffff', '037777777777', '255.0xffffff']) {
|
||||
expect(ingestionBlocked(host)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('empty hex part "0x" is zero, so "0x" and "0x7f.0x.0x.1" are blocked like inet_aton', () => {
|
||||
expect(ingestionBlocked('0x')).toBe(true);
|
||||
expect(ingestionBlocked('0x7f.0x.0x.1')).toBe(true);
|
||||
});
|
||||
|
||||
test('uppercase and double-encoded numeric loopback hosts are blocked', () => {
|
||||
for (const host of ['0X7F.0X0.0X0.0X1', '%2531%2532%2537%252e%2531', '%30%78%37%66%30%30%30%30%30%31']) {
|
||||
expect(ingestionBlocked(host)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed numeric-looking hosts are not misread as loopback', () => {
|
||||
// Five parts, empty middle parts, signs and non-digit hex all fail inet_aton.
|
||||
for (const host of [
|
||||
'127.0.0.0.1',
|
||||
'127..1',
|
||||
'.127.1',
|
||||
'+127.1',
|
||||
'127.-1',
|
||||
'0x7g.0.0.1',
|
||||
'0xx7f000001',
|
||||
'127.1e0',
|
||||
'0b1111111.1',
|
||||
]) {
|
||||
expect(ingestionBlocked(host)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('numeric loopback spellings on non-QA Mongo ports or non-QA Postgres port/database are allowed', () => {
|
||||
for (const host of ['127.1', '2130706433', '0x7f000001', '0177.0.0.1']) {
|
||||
const devOtherPort = makeDevConfig({ mongoUri: `mongodb://u:p@${host}:27019/stock_dev` });
|
||||
expect(() => assertEnvironmentSafety(devOtherPort, 'dataIngestion', {})).not.toThrow();
|
||||
|
||||
const pgDevPort = makeDevConfig({ pgHost: host, pgPort: 5433, pgDatabase: 'trading_bot' });
|
||||
expect(() => assertEnvironmentSafety(pgDevPort, 'dataIngestion', {})).not.toThrow();
|
||||
|
||||
const pgOtherDb = makeDevConfig({ pgHost: host, pgPort: 5432, pgDatabase: 'trading_bot_dev' });
|
||||
expect(() => assertEnvironmentSafety(pgOtherDb, 'dataIngestion', {})).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('QA PostgreSQL numeric loopback block still honours the STOCK_BOT_ALLOW_DEV_ON_QA_DB escape hatch', () => {
|
||||
for (const pgHost of ['127.1', '0x7f000001', '127.1.']) {
|
||||
const cfg = makeDevConfig({ pgHost, pgPort: 5432, pgDatabase: 'trading_bot' });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(QA_POSTGRES_ERROR);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' })
|
||||
).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('IPv4-mapped IPv6 with dotted-quad loopback tail is still blocked (strict tail parser unchanged)', () => {
|
||||
for (const host of ['[::ffff:127.0.0.1]', '[::ffff:7f00:1]']) {
|
||||
expect(ingestionBlocked(host)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue