stock-bot/apps/stock/config/src/env-safety.ts

706 lines
21 KiB
TypeScript

import { hostname as osHostname, networkInterfaces } from 'node:os';
import type { StockAppConfig } from './schemas';
export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator';
interface MongoTargetHost {
host: string;
port?: number;
}
interface ParsedMongoTarget {
hosts: MongoTargetHost[];
host?: string;
database?: string;
username?: string;
}
const LOOPBACK_HOSTS = new Set(['localhost', '0.0.0.0']);
const FORBIDDEN_PROD_SECRETS = new Set([
'trading_pass_dev',
'trading_mongo_dev',
'dev_pass',
'dev_mongo_pass',
'production_redis_password',
'admin123',
]);
function parseIpv4Octets(host: string): [number, number, number, number] | null {
const octets = host.split('.');
if (octets.length !== 4) {
return null;
}
const values: number[] = [];
for (const part of octets) {
if (!/^\d{1,3}$/.test(part)) {
return null;
}
const value = Number(part);
if (value < 0 || value > 255) {
return null;
}
values.push(value);
}
const [a, b, c, d] = values;
if (a === undefined || b === undefined || c === undefined || d === undefined) {
return null;
}
return [a, b, c, d];
}
function parseIpv4Part(part: string): number | null {
let value: number;
const hexMatch = /^0x([0-9a-f]*)$/i.exec(part);
if (hexMatch) {
const digits = hexMatch[1];
if (digits === undefined) {
return null;
}
value = digits === '' ? 0 : parseInt(digits, 16);
} else if (/^0[0-7]+$/.test(part)) {
value = parseInt(part, 8);
} else if (/^(?:0|[1-9]\d*)$/.test(part)) {
value = parseInt(part, 10);
} else {
return null;
}
if (!Number.isSafeInteger(value) || value < 0 || value > 0xffffffff) {
return null;
}
return value;
}
function parseNumericIpv4Octets(host: string): [number, number, number, number] | null {
const parts = host.split('.');
if (parts.length < 1 || parts.length > 4) {
return null;
}
const parsed: number[] = [];
for (const part of parts) {
const value = parseIpv4Part(part);
if (value === null) {
return null;
}
parsed.push(value);
}
const [p0, p1, p2, p3] = parsed;
if (p0 === undefined) {
return null;
}
if (parsed.length === 1) {
return [(p0 >>> 24) & 0xff, (p0 >>> 16) & 0xff, (p0 >>> 8) & 0xff, p0 & 0xff];
}
if (parsed.length === 2) {
if (p1 === undefined || p0 > 0xff || p1 > 0xffffff) {
return null;
}
return [p0, (p1 >>> 16) & 0xff, (p1 >>> 8) & 0xff, p1 & 0xff];
}
if (parsed.length === 3) {
if (p1 === undefined || p2 === undefined || p0 > 0xff || p1 > 0xff || p2 > 0xffff) {
return null;
}
return [p0, p1, (p2 >>> 8) & 0xff, p2 & 0xff];
}
if (
p1 === undefined ||
p2 === undefined ||
p3 === undefined ||
p0 > 0xff ||
p1 > 0xff ||
p2 > 0xff ||
p3 > 0xff
) {
return null;
}
return [p0, p1, p2, p3];
}
function parseDecimalIpv4Octets(host: string): [number, number, number, number] | null {
const octets = host.split('.');
if (octets.length !== 4) {
return null;
}
const values: number[] = [];
for (const part of octets) {
if (!/^\d+$/.test(part)) {
return null;
}
const value = Number(part);
if (!Number.isSafeInteger(value) || value < 0 || value > 255) {
return null;
}
values.push(value);
}
const [a, b, c, d] = values;
if (a === undefined || b === undefined || c === undefined || d === undefined) {
return null;
}
return [a, b, c, d];
}
function isIpv4LoopbackOctets(octets: [number, number, number, number] | null): boolean {
return (
octets !== null &&
(octets[0] === 127 ||
(octets[0] === 0 && octets[1] === 0 && octets[2] === 0 && octets[3] === 0))
);
}
function isIpv4Loopback(host: string): boolean {
// Check both POSIX numeric IPv4 (octal/hex/shorthand, e.g. 0177.0.0.1, 127.1, 0x7f000001)
// and decimal dotted-quad interpretation (e.g. 0127.0.0.1 -> 127.0.0.1) so resolvers that
// read leading-zero quads as decimal cannot bypass the loopback guard.
return (
isIpv4LoopbackOctets(parseNumericIpv4Octets(host)) ||
isIpv4LoopbackOctets(parseDecimalIpv4Octets(host))
);
}
function parseIpv6Side(side: string, allowIpv4Tail: boolean): number[] | null {
if (side === '') {
return [];
}
const parts = side.split(':');
const groups: number[] = [];
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part === undefined) {
return null;
}
if (i === parts.length - 1 && allowIpv4Tail && part.includes('.')) {
const octets = parseIpv4Octets(part);
if (!octets) {
return null;
}
groups.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]);
continue;
}
if (!/^[0-9a-f]{1,4}$/i.test(part)) {
return null;
}
groups.push(parseInt(part, 16));
}
return groups;
}
function parseIpv6Hextets(host: string): number[] | null {
if (!host.includes(':')) {
return null;
}
const zoneIdx = host.indexOf('%');
const addr = zoneIdx >= 0 ? host.slice(0, zoneIdx) : host;
const halves = addr.split('::');
if (halves.length > 2) {
return null;
}
const firstHalf = halves[0];
if (firstHalf === undefined) {
return null;
}
if (halves.length === 1) {
const groups = parseIpv6Side(firstHalf, true);
return groups && groups.length === 8 ? groups : null;
}
const secondHalf = halves[1];
if (secondHalf === undefined) {
return null;
}
const left = parseIpv6Side(firstHalf, false);
const right = parseIpv6Side(secondHalf, true);
if (!left || !right) {
return null;
}
const missing = 8 - left.length - right.length;
if (missing < 1) {
return null;
}
return [...left, ...Array<number>(missing).fill(0), ...right];
}
function isIpv6Loopback(host: string): boolean {
const hextets = parseIpv6Hextets(host);
if (!hextets) {
return false;
}
const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets;
if (
h0 === undefined ||
h1 === undefined ||
h2 === undefined ||
h3 === undefined ||
h4 === undefined ||
h5 === undefined ||
h6 === undefined ||
h7 === undefined
) {
return false;
}
if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0 && h6 === 0) {
return h7 === 0 || h7 === 1;
}
// IPv4-mapped IPv6 (::ffff:0:0/96): match 127.0.0.0/8 and 0.0.0.0 in both dotted and hex forms
if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0xffff) {
const firstOctet = (h6 >> 8) & 0xff;
return firstOctet === 127 || (h6 === 0 && h7 === 0);
}
return false;
}
function isLoopbackHost(host?: string): boolean {
if (!host) {
return false;
}
const normalized = host
.trim()
.replace(/^\[|\]$/g, '')
.replace(/\.+$/, '')
.toLowerCase();
return (
LOOPBACK_HOSTS.has(normalized) ||
isIpv4Loopback(normalized) ||
isIpv6Loopback(normalized)
);
}
const MAX_MONGO_HOST_DECODE_PASSES = 8;
const VALID_IPV6_ZONE_ID = /^[a-z0-9._~-]+$/i;
// Any URL authority/path/query/fragment delimiter, whitespace, or control char inside a
// decoded MongoDB seed host would be re-interpreted by ServerDescription.hostAddress's
// WHATWG URL re-parse (e.g., "localhost%2f:27018" -> "localhost/:27018" -> localhost:27017).
const FORBIDDEN_MONGO_HOST_CHARS = /[/?#@:\\[\],\s]/;
const FORBIDDEN_MONGO_IPV6_HOST_CHARS = /[/?#@\\[\],\s]/;
function isValidIpv6WithZoneId(host: string): boolean {
const zoneIdx = host.indexOf('%');
if (zoneIdx <= 0 || host.indexOf('%', zoneIdx + 1) !== -1) {
return false;
}
const addr = host.slice(0, zoneIdx);
const zone = host.slice(zoneIdx + 1);
return parseIpv6Hextets(addr) !== null && VALID_IPV6_ZONE_ID.test(zone);
}
const FORBIDDEN_MONGO_UNIX_SOCKET_CHARS = /[?#@:\\[\],\s]/;
function isUnixDomainSocketHost(decodedHost: string): boolean {
return (
decodedHost.startsWith('/') &&
decodedHost.endsWith('.sock') &&
!hasAsciiControlChar(decodedHost) &&
!FORBIDDEN_MONGO_UNIX_SOCKET_CHARS.test(decodedHost)
);
}
function decodeMongoHost(
rawHost: string,
isBracketedIpv6 = false,
allowUnixSocket = false
): string {
// MongoDB driver 6.22.0 decodes seed hostnames once in HostAddress.fromString during
// URI parsing and a second time when ServerDescription.hostAddress reparses the
// serialized address for ConnectionPool/Monitor. Decode iteratively to a fixed point
// so double- or multi-encoded loopback hosts cannot bypass the guard.
let current = rawHost;
for (let pass = 0; pass < MAX_MONGO_HOST_DECODE_PASSES; pass++) {
let decoded: string;
try {
decoded = decodeURIComponent(current);
} catch (error) {
if (error instanceof URIError) {
// After the first decode of a bracketed IPv6 literal, a literal '%' is allowed
// only when it separates a valid IPv6 address from a valid zone identifier
// (e.g., "::1%25lo" -> "::1%lo").
if (isBracketedIpv6 && pass > 0 && isValidIpv6WithZoneId(current)) {
break;
}
throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`);
}
throw error;
}
if (decoded === current) {
break;
}
current = decoded;
if (isBracketedIpv6 && isValidIpv6WithZoneId(current)) {
break;
}
}
if (current.includes('%') && !(isBracketedIpv6 && isValidIpv6WithZoneId(current))) {
throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`);
}
if (!isBracketedIpv6 && allowUnixSocket && isUnixDomainSocketHost(current)) {
return current;
}
const forbiddenChars = isBracketedIpv6
? FORBIDDEN_MONGO_IPV6_HOST_CHARS
: FORBIDDEN_MONGO_HOST_CHARS;
if (hasAsciiControlChar(current) || forbiddenChars.test(current)) {
throw new Error(`Safety guard: invalid characters in MongoDB host "${rawHost}".`);
}
return current.toLowerCase();
}
function parseMongoHostPort(
segment: string,
defaultPort: number | undefined,
allowUnixSocket = false
): MongoTargetHost | null {
const trimmed = segment.trim();
if (!trimmed) {
return null;
}
if (trimmed.startsWith('[')) {
const closeIdx = trimmed.indexOf(']');
if (closeIdx <= 1) {
return null;
}
const rawHost = trimmed.slice(1, closeIdx).trim();
if (!rawHost) {
return null;
}
const host = decodeMongoHost(rawHost, true).trim();
if (!host) {
return null;
}
const after = trimmed.slice(closeIdx + 1).trim();
if (after === '' || after === ':') {
return { host, port: defaultPort };
}
if (!after.startsWith(':')) {
return null;
}
const portStr = after.slice(1).trim();
if (!/^\d+$/.test(portStr)) {
return null;
}
const port = Number(portStr);
if (port < 1 || port > 65535) {
return null;
}
return { host, port };
}
const colonIdx = trimmed.indexOf(':');
if (colonIdx === -1) {
const host = decodeMongoHost(trimmed, false, allowUnixSocket).trim();
if (!host) {
return null;
}
if (allowUnixSocket && isUnixDomainSocketHost(host)) {
return { host, port: undefined };
}
return { host, port: defaultPort };
}
if (trimmed.indexOf(':', colonIdx + 1) !== -1) {
return null;
}
const rawHost = trimmed.slice(0, colonIdx).trim();
const portStr = trimmed.slice(colonIdx + 1).trim();
if (!rawHost) {
return null;
}
const host = decodeMongoHost(rawHost).trim();
if (!host) {
return null;
}
if (portStr === '') {
return { host, port: defaultPort };
}
if (!/^\d+$/.test(portStr)) {
return null;
}
const port = Number(portStr);
if (port < 1 || port > 65535) {
return null;
}
return { host, port };
}
function hasAsciiControlChar(value: string): boolean {
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code <= 0x1f || code === 0x7f) {
return true;
}
}
return false;
}
function parseMongoTarget(uri?: string): ParsedMongoTarget {
if (!uri) {
throw new Error('Safety guard: MongoDB URI is missing or empty.');
}
if (hasAsciiControlChar(uri)) {
throw new Error(
'Safety guard: MongoDB URI contains forbidden whitespace or control characters.'
);
}
const trimmed = uri.trim();
if (!trimmed || /\s/.test(trimmed)) {
throw new Error('Safety guard: MongoDB URI is empty or contains forbidden whitespace.');
}
const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/is.exec(trimmed);
const rawScheme = schemeMatch?.[1];
const rest = schemeMatch?.[2];
if (!rawScheme || rest === undefined) {
throw new Error('Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.');
}
const scheme = rawScheme.toLowerCase();
const defaultPort = scheme === 'mongodb' ? 27017 : undefined;
// Match mongodb-connection-string-url: authority ends at '/' or '?', never '#'
const delimiterMatch = /[/?]/.exec(rest);
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : '';
if (!authority) {
throw new Error('Safety guard: MongoDB URI authority is empty.');
}
if (authority.includes('#')) {
throw new Error(
'Safety guard: MongoDB URI authority cannot contain an unencoded "#" character.'
);
}
let database: string | undefined;
if (remainder.startsWith('/')) {
const pathPart = remainder.split(/[?#]/, 1)[0] ?? '';
const firstSegment = pathPart.replace(/^\/+/, '').split('/')[0];
database = firstSegment || undefined;
}
const firstAtIndex = authority.indexOf('@');
if (firstAtIndex === 0) {
throw new Error('Safety guard: MongoDB URI authority cannot have empty userinfo before "@".');
}
if (firstAtIndex !== -1 && authority.indexOf('@', firstAtIndex + 1) !== -1) {
throw new Error(
'Safety guard: MongoDB URI authority cannot contain multiple unencoded "@" characters.'
);
}
const userinfo = firstAtIndex >= 0 ? authority.slice(0, firstAtIndex) : '';
const hostList = firstAtIndex >= 0 ? authority.slice(firstAtIndex + 1) : authority;
if (!hostList) {
throw new Error('Safety guard: MongoDB URI host list is empty.');
}
let username: string | undefined;
if (userinfo) {
const colonIndex = userinfo.indexOf(':');
const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo;
if (rawUsername) {
try {
username = decodeURIComponent(rawUsername);
} catch {
username = rawUsername;
}
}
}
const hosts: MongoTargetHost[] = [];
const allowUnixSocket = scheme === 'mongodb';
for (const segment of hostList.split(',')) {
const parsedHost = parseMongoHostPort(segment, defaultPort, allowUnixSocket);
if (parsedHost) {
hosts.push(parsedHost);
}
}
if (hosts.length === 0) {
throw new Error('Safety guard: MongoDB URI did not contain any valid host.');
}
return {
hosts,
host: hosts[0]?.host,
database,
username,
};
}
function getLocalMachineHosts(): Set<string> {
const hosts = new Set<string>();
const rawHostname = osHostname().trim().toLowerCase().replace(/\.+$/, '');
if (rawHostname) {
hosts.add(rawHostname);
const shortName = rawHostname.split('.')[0];
if (shortName) {
hosts.add(shortName);
hosts.add(`${shortName}.local`);
}
}
const ifaces = networkInterfaces();
for (const entries of Object.values(ifaces)) {
if (!entries) {
continue;
}
for (const entry of entries) {
if (entry.address) {
const addr = entry.address.split('%')[0]?.trim().toLowerCase();
if (addr) {
hosts.add(addr);
}
}
}
}
return hosts;
}
function isLocalMachineHost(host?: string): boolean {
if (!host) {
return false;
}
if (isLoopbackHost(host)) {
return true;
}
const normalized = host
.trim()
.replace(/^\[|\]$/g, '')
.replace(/\.+$/, '')
.toLowerCase();
const localHosts = getLocalMachineHosts();
if (localHosts.has(normalized)) {
return true;
}
// Also normalize numeric/decimal IPv4 spellings (e.g. hex or leading-zero LAN IP)
const numericOctets = parseNumericIpv4Octets(normalized) ?? parseDecimalIpv4Octets(normalized);
if (numericOctets !== null) {
const dotted = numericOctets.join('.');
if (localHosts.has(dotted)) {
return true;
}
}
return false;
}
function isQaMongoTargetHosts(target: ParsedMongoTarget): boolean {
return target.hosts.some(
entry => isLocalMachineHost(entry.host) && (entry.port === undefined || entry.port === 27017)
);
}
function isQaMongoTarget(uri: string | undefined): boolean {
return isQaMongoTargetHosts(parseMongoTarget(uri));
}
function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean {
return isLocalMachineHost(pg.host) && pg.port === 5432 && pg.database === 'trading_bot';
}
/**
* Enforce environment isolation between dev, qa, and prod so services cannot
* accidentally mutate QA or production databases from the wrong environment.
*/
export function assertEnvironmentSafety(
config: StockAppConfig,
serviceName?: StockServiceName,
env: Record<string, string | undefined> = process.env
): void {
const environment = config.environment;
if (environment === 'test') {
return;
}
if (environment === 'development') {
if (
config.database.postgres.enabled &&
isQaPostgresTarget(config.database.postgres) &&
env.STOCK_BOT_ALLOW_DEV_ON_QA_DB !== 'true'
) {
throw new Error(
'Safety guard: development environment cannot target QA PostgreSQL (localhost:5432/trading_bot). ' +
'Start dev infrastructure on port 5433 (trading_bot_dev) or run with NODE_ENV=qa.'
);
}
const isReadOnlyPipeline = serviceName === 'dataPipeline';
const mongo = config.database.mongodb;
if (mongo.enabled) {
if (isReadOnlyPipeline) {
const effectiveUri = mongo.readUri ?? mongo.uri;
const readTarget = parseMongoTarget(effectiveUri);
if (
isQaMongoTargetHosts(readTarget) &&
(mongo.readOnly !== true || readTarget.username === 'trading_admin')
) {
throw new Error(
'Safety guard: development data-pipeline cannot read QA MongoDB (localhost:27017) ' +
'with admin credentials or without read-only mode enabled. ' +
'Configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) and enable mongoReadOnly: true.'
);
}
} else if (
!mongo.readOnly &&
isQaMongoTarget(mongo.uri) &&
env.STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE !== 'true'
) {
throw new Error(
`Safety guard: development service "${serviceName ?? 'app'}" cannot open a writable MongoDB ` +
'connection to QA MongoDB (localhost:27017/stock). ' +
'Point MONGODB_URI to dev MongoDB (localhost:27018/stock_dev) for ingestion writes, ' +
'or use data-pipeline with MONGODB_READ_URI for read-only QA reads.'
);
}
}
return;
}
if (environment === 'qa') {
if (config.database.postgres.enabled && config.database.postgres.database.endsWith('_dev')) {
throw new Error(
`Safety guard: qa environment cannot target dev PostgreSQL database "${config.database.postgres.database}".`
);
}
if (config.database.mongodb.enabled && config.database.mongodb.database.endsWith('_dev')) {
throw new Error(
`Safety guard: qa environment cannot target dev MongoDB database "${config.database.mongodb.database}".`
);
}
return;
}
if (environment === 'production') {
if (env.STOCK_BOT_AUTH_DISABLED === 'true') {
throw new Error('Safety guard: STOCK_BOT_AUTH_DISABLED=true is forbidden in production.');
}
if (FORBIDDEN_PROD_SECRETS.has(config.database.postgres.password)) {
throw new Error('Safety guard: production PostgreSQL password cannot use a default dev/qa credential.');
}
const mongoTarget = config.database.mongodb.enabled
? parseMongoTarget(config.database.mongodb.uri)
: undefined;
const mongoUriHasDevPass = Array.from(FORBIDDEN_PROD_SECRETS).some(secret =>
config.database.mongodb.uri.includes(`:${secret}@`)
);
if (
mongoUriHasDevPass ||
(config.database.mongodb.password && FORBIDDEN_PROD_SECRETS.has(config.database.mongodb.password))
) {
throw new Error(
`Safety guard: production MongoDB (${mongoTarget?.host ?? 'configured URI'}) cannot use a default dev/qa credential.`
);
}
if (
config.database.dragonfly.password &&
FORBIDDEN_PROD_SECRETS.has(config.database.dragonfly.password)
) {
throw new Error('Safety guard: production Dragonfly/Redis password cannot use a placeholder/dev credential.');
}
}
}