safety
This commit is contained in:
parent
879e9b4228
commit
c3cb36c8d6
51 changed files with 2290 additions and 1467 deletions
277
libs/core/di/src/http/security.ts
Normal file
277
libs/core/di/src/http/security.ts
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import type { Hono, MiddlewareHandler } from 'hono';
|
||||
|
||||
type Role = 'read' | 'admin' | 'service';
|
||||
export interface HttpSecurityOptions {
|
||||
readToken?: string;
|
||||
adminToken?: string;
|
||||
serviceToken?: string;
|
||||
disabled?: boolean;
|
||||
environment?: string;
|
||||
hostname?: string;
|
||||
origins?: string[];
|
||||
browserSessions?: boolean;
|
||||
}
|
||||
const cookieName = 'stock_bot_session';
|
||||
const sessionSeconds = 3600;
|
||||
const digest = (value: string) => createHash('sha256').update(value).digest();
|
||||
const equal = (a: string, b: string) => timingSafeEqual(digest(a), digest(b));
|
||||
|
||||
export function httpSecurityOptions(env: NodeJS.ProcessEnv = process.env): HttpSecurityOptions {
|
||||
return {
|
||||
readToken: env.STOCK_BOT_READ_TOKEN,
|
||||
adminToken: env.STOCK_BOT_ADMIN_TOKEN,
|
||||
serviceToken: env.STOCK_BOT_SERVICE_TOKEN,
|
||||
disabled: env.STOCK_BOT_AUTH_DISABLED === 'true',
|
||||
environment: env.NODE_ENV ?? 'development',
|
||||
hostname: env.STOCK_BOT_HTTP_HOST ?? '127.0.0.1',
|
||||
origins: env.STOCK_BOT_ALLOWED_ORIGINS?.split(',')
|
||||
.map(origin => origin.trim())
|
||||
.filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
/** A small operator boundary, not a multi-user identity provider. Secure by default. */
|
||||
export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOptions()) {
|
||||
const environment = options.environment ?? 'development';
|
||||
const hostname = options.hostname ?? '127.0.0.1';
|
||||
const disabled = options.disabled === true;
|
||||
if (
|
||||
disabled &&
|
||||
(environment === 'production' || !['127.0.0.1', '::1', 'localhost'].includes(hostname))
|
||||
) {
|
||||
throw new Error(
|
||||
'Authentication may only be disabled on an explicit loopback development/test listener'
|
||||
);
|
||||
}
|
||||
const tokens = {
|
||||
read: options.readToken,
|
||||
admin: options.adminToken,
|
||||
service: options.serviceToken,
|
||||
};
|
||||
if (!disabled) {
|
||||
if (!tokens.admin || !tokens.service) {
|
||||
throw new Error(
|
||||
'Set STOCK_BOT_ADMIN_TOKEN and STOCK_BOT_SERVICE_TOKEN before starting HTTP services'
|
||||
);
|
||||
}
|
||||
const values = Object.values(tokens).filter((value): value is string => !!value);
|
||||
if (
|
||||
values.some(value => value.length < 32 || value.trim() !== value) ||
|
||||
new Set(values).size !== values.length
|
||||
) {
|
||||
throw new Error(
|
||||
'HTTP access tokens must be distinct, unpadded secrets of at least 32 characters'
|
||||
);
|
||||
}
|
||||
}
|
||||
const allowedOrigins =
|
||||
options.origins ??
|
||||
(environment === 'production'
|
||||
? []
|
||||
: [
|
||||
'http://localhost:3000',
|
||||
'http://localhost:4200',
|
||||
'http://localhost:5173',
|
||||
'http://localhost:5174',
|
||||
'http://127.0.0.1:3000',
|
||||
'http://127.0.0.1:5173',
|
||||
]);
|
||||
if (allowedOrigins.includes('*') || allowedOrigins.includes('null')) {
|
||||
throw new Error('Explicit trusted HTTP origins are required');
|
||||
}
|
||||
const originAllowed = (request: Request) => {
|
||||
const origin = request.headers.get('origin');
|
||||
return !!origin && (origin === new URL(request.url).origin || allowedOrigins.includes(origin));
|
||||
};
|
||||
const signingKey = (role: 'read' | 'admin') => tokens[role];
|
||||
const signature = (payload: string, key: string) =>
|
||||
createHmac('sha256', key).update(`stock-bot-ui:${payload}`).digest('base64url');
|
||||
function roleForToken(value: string): Role | undefined {
|
||||
for (const role of ['read', 'admin', 'service'] as const) {
|
||||
if (tokens[role] && equal(value, tokens[role])) {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function authenticate(request: Request): { role: Role; cookie: boolean } | undefined {
|
||||
if (disabled) {
|
||||
return { role: 'admin', cookie: false };
|
||||
}
|
||||
const authorization = request.headers.get('authorization');
|
||||
if (authorization) {
|
||||
const match = /^Bearer ([^\s]+)$/i.exec(authorization);
|
||||
const role = match?.[1] ? roleForToken(match[1]) : undefined;
|
||||
return role ? { role, cookie: false } : undefined;
|
||||
}
|
||||
if (!options.browserSessions) {
|
||||
return undefined;
|
||||
}
|
||||
const value = request.headers
|
||||
.get('cookie')
|
||||
?.split(';')
|
||||
.map(part => part.trim())
|
||||
.find(part => part.startsWith(`${cookieName}=`))
|
||||
?.slice(cookieName.length + 1);
|
||||
if (!value || value.length > 512) {
|
||||
return;
|
||||
}
|
||||
const [role, expiry, nonce, mac, extra] = value.split('.');
|
||||
if (
|
||||
(role !== 'read' && role !== 'admin') ||
|
||||
extra ||
|
||||
!nonce ||
|
||||
!mac ||
|
||||
!/^\d+$/.test(expiry ?? '')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const expiresAt = Number(expiry);
|
||||
if (
|
||||
!Number.isSafeInteger(expiresAt) ||
|
||||
expiresAt <= Date.now() / 1000 ||
|
||||
expiresAt > Date.now() / 1000 + sessionSeconds + 10
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const key = signingKey(role);
|
||||
if (!key || !equal(mac, signature(`${role}.${expiry}.${nonce}`, key))) {
|
||||
return;
|
||||
}
|
||||
return { role, cookie: true };
|
||||
}
|
||||
function authorize(request: Request, admin = false): Response | undefined {
|
||||
const identity = authenticate(request);
|
||||
if (!identity) {
|
||||
return Response.json(
|
||||
{ error: 'Authentication required' },
|
||||
{ status: 401, headers: { 'WWW-Authenticate': 'Bearer', 'Cache-Control': 'no-store' } }
|
||||
);
|
||||
}
|
||||
if (admin && identity.role === 'read') {
|
||||
return Response.json({ error: 'Administrator access required' }, { status: 403 });
|
||||
}
|
||||
const isWebSocket = request.headers.get('upgrade')?.toLowerCase() === 'websocket';
|
||||
const mutates = !['GET', 'HEAD', 'OPTIONS'].includes(request.method);
|
||||
// Browser sessions are CSRF-protected. WebSocket upgrades validate Origin as well.
|
||||
if (
|
||||
(isWebSocket && request.headers.has('origin') && !originAllowed(request)) ||
|
||||
(identity.cookie && (mutates || isWebSocket) && !originAllowed(request))
|
||||
) {
|
||||
return Response.json({ error: 'Untrusted request origin' }, { status: 403 });
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const middleware: MiddlewareHandler = async (context, next) => {
|
||||
const path = context.req.path;
|
||||
if (
|
||||
path === '/health' ||
|
||||
path.startsWith('/health/') ||
|
||||
(options.browserSessions && path === '/api/auth/session') ||
|
||||
context.req.method === 'OPTIONS'
|
||||
) {
|
||||
await next();
|
||||
return undefined;
|
||||
}
|
||||
const admin =
|
||||
!['GET', 'HEAD'].includes(context.req.method) ||
|
||||
/^\/api\/(queue|operations|handlers)(\/|$)/.test(path);
|
||||
const rejection = authorize(context.req.raw, admin);
|
||||
if (rejection) {
|
||||
return rejection;
|
||||
}
|
||||
await next();
|
||||
return undefined;
|
||||
};
|
||||
function mount(app: Hono): void {
|
||||
app.use('*', middleware);
|
||||
if (!options.browserSessions) {
|
||||
return;
|
||||
}
|
||||
const cookie = (value: string, maxAge: number) =>
|
||||
`${cookieName}=${value}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${environment === 'production' ? '; Secure' : ''}`;
|
||||
app.get('/api/auth/session', context => {
|
||||
const identity = authenticate(context.req.raw);
|
||||
context.header('Cache-Control', 'no-store');
|
||||
return context.json(
|
||||
{ authenticated: !!identity, role: identity?.role },
|
||||
identity ? 200 : 401
|
||||
);
|
||||
});
|
||||
let attempts = 0;
|
||||
let windowStart = Date.now();
|
||||
app.post('/api/auth/session', async context => {
|
||||
context.header('Cache-Control', 'no-store');
|
||||
if (Date.now() - windowStart > 60_000) {
|
||||
attempts = 0;
|
||||
windowStart = Date.now();
|
||||
}
|
||||
if (++attempts > 30) {
|
||||
return context.json({ error: 'Too many sign-in attempts' }, 429);
|
||||
}
|
||||
if (context.req.header('origin') && !originAllowed(context.req.raw)) {
|
||||
return context.json({ error: 'Untrusted request origin' }, 403);
|
||||
}
|
||||
if (!context.req.header('content-type')?.startsWith('application/json')) {
|
||||
return context.json({ error: 'JSON required' }, 415);
|
||||
}
|
||||
const input: unknown = await context.req.json().catch(() => null);
|
||||
const token =
|
||||
input && typeof input === 'object' && 'token' in input && typeof input.token === 'string'
|
||||
? input.token
|
||||
: '';
|
||||
if (token.length > 4096) {
|
||||
return context.json({ error: 'Invalid access token' }, 401);
|
||||
}
|
||||
const role = disabled ? 'admin' : roleForToken(token);
|
||||
if (!role || role === 'service') {
|
||||
return context.json({ error: 'Invalid access token' }, 401);
|
||||
}
|
||||
const key = signingKey(role);
|
||||
if (key) {
|
||||
const payload = `${role}.${Math.floor(Date.now() / 1000) + sessionSeconds}.${randomBytes(16).toString('hex')}`;
|
||||
context.header(
|
||||
'Set-Cookie',
|
||||
cookie(`${payload}.${signature(payload, key)}`, sessionSeconds)
|
||||
);
|
||||
}
|
||||
return context.json({ authenticated: true, role });
|
||||
});
|
||||
app.delete('/api/auth/session', context => {
|
||||
if (!originAllowed(context.req.raw)) {
|
||||
return context.json({ error: 'Untrusted request origin' }, 403);
|
||||
}
|
||||
context.header('Set-Cookie', cookie('', 0));
|
||||
context.header('Cache-Control', 'no-store');
|
||||
return context.json({ authenticated: false });
|
||||
});
|
||||
}
|
||||
return { mount, authorize, hostname, allowedOrigins };
|
||||
}
|
||||
|
||||
export type HttpSecurity = ReturnType<typeof createHttpSecurity>;
|
||||
|
||||
/** Used only by server-to-server clients; never expose this token to the browser. */
|
||||
export function authenticatedServiceFetch(
|
||||
input: string | URL | Request,
|
||||
init?: RequestInit
|
||||
): Promise<Response> {
|
||||
const token = process.env.STOCK_BOT_SERVICE_TOKEN;
|
||||
if (!token) {
|
||||
const target = new URL(input instanceof Request ? input.url : input.toString());
|
||||
if (
|
||||
process.env.STOCK_BOT_AUTH_DISABLED !== 'true' ||
|
||||
process.env.NODE_ENV === 'production' ||
|
||||
!['localhost', '127.0.0.1', '[::1]'].includes(target.hostname)
|
||||
) {
|
||||
throw new Error('STOCK_BOT_SERVICE_TOKEN is required for internal HTTP requests');
|
||||
}
|
||||
}
|
||||
const headers = new Headers(input instanceof Request ? input.headers : undefined);
|
||||
new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
|
||||
if (token) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
return fetch(input, { ...init, headers, redirect: 'error' });
|
||||
}
|
||||
|
|
@ -2,6 +2,12 @@
|
|||
export { ServiceApplication } from './service-application';
|
||||
export { ServiceContainerBuilder } from './container/builder';
|
||||
export { OperationContext } from './operation-context';
|
||||
export {
|
||||
createHttpSecurity,
|
||||
httpSecurityOptions,
|
||||
authenticatedServiceFetch,
|
||||
} from './http/security';
|
||||
export type { HttpSecurity, HttpSecurityOptions } from './http/security';
|
||||
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
|
||||
export { ServiceLifecycleManager } from './utils/lifecycle';
|
||||
export { HandlerScanner } from './scanner/handler-scanner';
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import type { HandlerScanner } from './scanner';
|
|||
export interface ServiceApplicationConfig {
|
||||
/** Service name for logging and identification */
|
||||
serviceName: string;
|
||||
hostname?: string;
|
||||
|
||||
/** CORS configuration - if not provided, uses permissive defaults */
|
||||
corsConfig?: Parameters<typeof cors>[0];
|
||||
|
|
@ -435,6 +436,8 @@ export class ServiceApplication {
|
|||
// Start HTTP server
|
||||
const port = this.config.service.port;
|
||||
this.server = Bun.serve({
|
||||
hostname: this.serviceConfig.hostname,
|
||||
maxRequestBodySize: 1_048_576,
|
||||
port,
|
||||
fetch: this.app.fetch,
|
||||
development: this.config.environment === 'development',
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
|
||||
import pino from 'pino';
|
||||
import pretty from 'pino-pretty';
|
||||
import { redactLogValue } from './redact';
|
||||
import type { LogContext, LoggerConfig, LogLevel, LogMetadata } from './types';
|
||||
|
||||
// Simple cache for logger instances
|
||||
|
|
@ -183,12 +184,12 @@ export class Logger {
|
|||
}
|
||||
|
||||
if (typeof message === 'string') {
|
||||
this.pino[level](data, message);
|
||||
this.pino[level](redactLogValue(data), redactLogValue(message) as string);
|
||||
} else {
|
||||
if (globalConfig.hideObject && level !== 'error' && level !== 'fatal') {
|
||||
this.pino[level]({}, `Object logged (hidden)`);
|
||||
} else {
|
||||
this.pino[level]({ ...data, data: message }, 'Object logged');
|
||||
this.pino[level](redactLogValue({ ...data, data: message }), 'Object logged');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
52
libs/core/logger/src/redact.ts
Normal file
52
libs/core/logger/src/redact.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
const sensitiveKey =
|
||||
/password|passwd|secret|token|api[_-]?key|authorization|cookie|credential|private[_-]?key|session[_-]?id/i;
|
||||
const hidden = '[REDACTED]';
|
||||
|
||||
function redactText(value: string): string {
|
||||
return value
|
||||
.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, `$1${hidden}@`)
|
||||
.replace(
|
||||
/([?&](?:api[_-]?(?:key|token)|token|key|password|secret|credential|auth)=)[^&#\s]*/gi,
|
||||
`$1${hidden}`
|
||||
)
|
||||
.replace(/\bBearer\s+[a-z0-9._~+/=-]+/gi, `Bearer ${hidden}`);
|
||||
}
|
||||
|
||||
/** Redact without mutating callers, including error objects and circular metadata. */
|
||||
export function redactLogValue(value: unknown, seen = new WeakSet<object>()): unknown {
|
||||
if (typeof value === 'string') {
|
||||
return redactText(value);
|
||||
}
|
||||
if (!value || typeof value !== 'object') {
|
||||
return value;
|
||||
}
|
||||
if (seen.has(value)) {
|
||||
return '[Circular]';
|
||||
}
|
||||
seen.add(value);
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
}
|
||||
if (Buffer.isBuffer(value)) {
|
||||
return '[Binary]';
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(item => redactLogValue(item, seen));
|
||||
}
|
||||
const source =
|
||||
value instanceof Error
|
||||
? {
|
||||
...value,
|
||||
name: value.name,
|
||||
message: value.message,
|
||||
stack: value.stack,
|
||||
cause: value.cause,
|
||||
}
|
||||
: value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(source).map(([key, item]) => [
|
||||
key,
|
||||
sensitiveKey.test(key) ? hidden : redactLogValue(item, seen),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
|
@ -88,3 +88,8 @@ export type {
|
|||
MemberMetadataDecorator,
|
||||
ClassMemberMetadataDecorator,
|
||||
} from './decorators';
|
||||
export {
|
||||
REFERENCE_DATA_RESET_CONFIRMATION,
|
||||
parseReferenceDataResetRequest,
|
||||
} from './reference-data';
|
||||
export type { ReferenceDataResetRequest, ReferenceDataResetScope } from './reference-data';
|
||||
|
|
|
|||
23
libs/core/types/src/reference-data.ts
Normal file
23
libs/core/types/src/reference-data.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
export type ReferenceDataResetScope = 'exchanges' | 'provider_mappings' | 'all';
|
||||
export interface ReferenceDataResetRequest {
|
||||
type: ReferenceDataResetScope;
|
||||
confirmation: string;
|
||||
}
|
||||
export const REFERENCE_DATA_RESET_CONFIRMATION = 'DELETE STOCK REFERENCE DATA';
|
||||
|
||||
/** Dependency-free validation shared by HTTP and queue consumers. No default destructive scope. */
|
||||
export function parseReferenceDataResetRequest(input: unknown): ReferenceDataResetRequest {
|
||||
if (
|
||||
input &&
|
||||
typeof input === 'object' &&
|
||||
'type' in input &&
|
||||
'confirmation' in input &&
|
||||
(input.type === 'exchanges' || input.type === 'provider_mappings' || input.type === 'all') &&
|
||||
input.confirmation === `${REFERENCE_DATA_RESET_CONFIRMATION}:${input.type}`
|
||||
) {
|
||||
return { type: input.type, confirmation: input.confirmation };
|
||||
}
|
||||
throw new Error(
|
||||
'Reset requires an explicit type and matching DELETE STOCK REFERENCE DATA:<type> confirmation'
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue