Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(config): log an S3 endpoint without a scheme at boot, refuse a save
Yudhi Armyndharis18d6692075a2
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex 3d1e5b6d1..e9185c4a7 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -1,5 +1,5 @@import { LogLevel } from '../common/services/logger.service';-import { validateEnv } from './env.validation';+import { s3EndpointError, validateEnv } from './env.validation';/** Regression locks for boot-time env validation (no silent coercion). */describe('validateEnv', () => {@@ -627,38 +627,47 @@ describe('validateEnv', () => {expect(() => validateEnv({ NODE_URL: 'https://node-a.internal' })).not.toThrow();});- // Without a scheme the S3 client throws "Invalid URL" on every call and media quietly lands on local disk.+ // Without a scheme the S3 client throws "Invalid URL" on every call and media quietly lands on local disk. That+ // deployment runs today, so the boot reports the endpoint instead of refusing it (validateEnv never throws for+ // it); the Infrastructure save is what refuses.describe('S3_ENDPOINT', () => {+ const s3 = (S3_ENDPOINT: string | undefined, STORAGE_TYPE = 's3') => ({ STORAGE_TYPE, S3_ENDPOINT });+it.each(['minio:9000', '127.0.0.1:9000', 'localhost:9000', 'minio', 'ftp://minio:9000'])(- 'rejects %s while S3 is the selected storage',+ 'reports %s while S3 is the selected storage, and still lets validateEnv pass',endpoint => {- expect(() => validateEnv({ STORAGE_TYPE: 's3', S3_ENDPOINT: endpoint })).toThrow(- /S3_ENDPOINT must be an absolute http\(s\) URL/,- );+ expect(s3EndpointError(s3(endpoint))).toMatch(/^S3_ENDPOINT must be an absolute http\(s\) URL/);+ expect(() => validateEnv(s3(endpoint))).not.toThrow();},);- it('does not echo the value, which may carry credentials', () => {- expect(() => validateEnv({ STORAGE_TYPE: 's3', S3_ENDPOINT: 'AKIAKEY:hunter2@s3host:9000' })).not.toThrow(- /hunter2/,- );- expect(() => validateEnv({ STORAGE_TYPE: 's3', S3_ENDPOINT: 'AKIAKEY:hunter2@s3host:9000' })).toThrow(- /S3_ENDPOINT/,+ it('says where to fix it', () => {+ expect(s3EndpointError(s3('minio:9000'))).toMatch(+ /environment, \.\/\.env or data\/\.env\.generated, or on the Infrastructure page/,);});- it.each(['http://minio:9000', 'https://s3.example.com', 'https://gateway.example.com/s3/', ' http://minio:9000 '])(- 'accepts %s',- endpoint => {- expect(() => validateEnv({ STORAGE_TYPE: 's3', S3_ENDPOINT: endpoint })).not.toThrow();- },- );+ it('does not echo the value, which may carry credentials', () => {+ const message = s3EndpointError(s3('AKIAKEY:hunter2@s3host:9000'));+ expect(message).toMatch(/S3_ENDPOINT/);+ expect(message).not.toMatch(/hunter2|AKIAKEY|s3host/);+ });++ it.each([+ 'http://minio:9000',+ 'https://s3.example.com',+ 'https://gateway.example.com/s3/',+ ' http://minio:9000 ',+ 'HTTP://minio:9000',+ ])('accepts %s', endpoint => {+ expect(s3EndpointError(s3(endpoint))).toBeNull();+ });it('leaves an unset or blank endpoint alone, and a stale one while storage is local', () => {- expect(() => validateEnv({ STORAGE_TYPE: 's3' })).not.toThrow();- expect(() => validateEnv({ STORAGE_TYPE: 's3', S3_ENDPOINT: ' ' })).not.toThrow();- expect(() => validateEnv({ STORAGE_TYPE: 'local', S3_ENDPOINT: 'minio:9000' })).not.toThrow();- expect(() => validateEnv({ S3_ENDPOINT: 'minio:9000' })).not.toThrow();+ expect(s3EndpointError(s3(undefined))).toBeNull();+ expect(s3EndpointError(s3(' '))).toBeNull();+ expect(s3EndpointError(s3('minio:9000', 'local'))).toBeNull();+ expect(s3EndpointError({ S3_ENDPOINT: 'minio:9000' })).toBeNull();});});diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex af75a65ba..4dfcce080 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -91,6 +91,30 @@ export function builtinRedisUsernameError(config: EnvConfig): string | null {);}+/**+ * The S3 client builds every request from S3_ENDPOINT. A value without a scheme (`minio:9000`) does not stop the+ * client from being built: each call then fails as "Invalid URL" and media goes to the local fallback directory.+ * That deployment runs today, so validateEnv leaves it alone and the boot reports this message at ERROR level; the+ * Infrastructure save refuses it, so the page never stores one. Only checked while S3 is the selected storage, and+ * the value is not echoed, as it may hold keys.+ */+export function s3EndpointError(config: EnvConfig): string | null {+ const raw = config.S3_ENDPOINT;+ const endpoint = typeof raw === 'string' ? raw.trim() : '';+ if (!endpoint || config.STORAGE_TYPE !== 's3') return null;+ let protocol: string | undefined;+ try {+ protocol = new URL(endpoint).protocol;+ } catch {+ protocol = undefined;+ }+ if (protocol === 'http:' || protocol === 'https:') return null;+ return (+ 'S3_ENDPOINT must be an absolute http(s) URL such as "http://minio:9000"; set it in the environment, ./.env or ' ++ 'data/.env.generated, or on the Infrastructure page'+ );+}+/*** Fail-fast environment validation. Wired as ConfigModule's `validate`* callback so a misconfigured deployment is rejected at BOOT instead of silently@@ -620,22 +644,6 @@ export function validateEnv(config: EnvConfig): EnvConfig {}}- // The S3 client builds every request from this URL. A value without a scheme (`minio:9000`) fails each call as- // "Invalid URL" and media goes to the local fallback directory instead, so a typo in the endpoint reads as a- // working bucket. Only checked while S3 is the selected storage; the value is not echoed, as it may hold keys.- const s3Endpoint = str('S3_ENDPOINT');- if (s3Endpoint && rawEnum('STORAGE_TYPE') === 's3') {- let protocol: string | undefined;- try {- protocol = new URL(s3Endpoint).protocol;- } catch {- protocol = undefined;- }- if (protocol !== 'http:' && protocol !== 'https:') {- errors.push('S3_ENDPOINT must be an absolute http(s) URL such as "http://minio:9000"');- }- }-// Boolean feature flags read at module-eval time (app.module.ts) with a bare `=== 'true'` /// `!== 'false'` comparison: a typo (`True`, `1`, `yes`) or trailing whitespace/CR silently// (dis)ables the feature. Validate the RAW value — NOT a trimmed one — so `'true '` / `'true\r'`diff --git a/src/main.ts b/src/main.tsindex 44f7646fe..fec4fa8b8 100644--- a/src/main.ts+++ b/src/main.ts@@ -17,7 +17,7 @@ import {} from './config/swagger.config';import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';import { runBootstrapOrExit } from './config/bootstrap-fatal';-import { validateEnv } from './config/env.validation';+import { s3EndpointError, validateEnv } from './config/env.validation';import { resolveStorageRoot } from './config/storage-root';import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';import { applyGlobalValidation } from './config/app-validation';@@ -67,6 +67,15 @@ async function bootstrap() {// PostgreSQL container is started; an invalid config would do both and then be reported twice.validateEnv(process.env);+ // Reported, not refused: with S3 selected and an endpoint the client cannot use, the instance runs today on its+ // local fallback directory, so an upgrade must not turn that into a crash loop. The Infrastructure save refuses it.+ const s3EndpointProblem = s3EndpointError(process.env);+ if (s3EndpointProblem) {+ bootstrapLogger.error(+ `${s3EndpointProblem}. Until then S3 is unavailable and media is written to the local directory.`,+ );+ }+// Advisory (not enforced): an unset/blank NODE_ENV is the deliberate local-dev default, but it// silently degrades four controls to their dev posture (the default-secret guard, wildcard CORS,// Swagger UI, validation error detail) — warn so a production deployment that simply forgot thediff --git a/src/modules/infra/bundled-host-decisions.spec.ts b/src/modules/infra/bundled-host-decisions.spec.tsindex e4464c644..861da85e7 100644--- a/src/modules/infra/bundled-host-decisions.spec.ts+++ b/src/modules/infra/bundled-host-decisions.spec.ts@@ -64,7 +64,7 @@ interface Case {flag: Flag;}-// A storage endpoint that is not an absolute http(s) URL is refused by boot validation, so a save never reaches the+// A storage endpoint that is not an absolute http(s) URL is refused by the save, so a save never reaches the// decisions below with one; the blank spelling is no endpoint at all.const isSavableHost = (service: ServiceName, host: string): boolean =>service !== 'storage' || host.trim() === '' || /^https?:\/\//i.test(host.trim());diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsindex e16eb2f00..1043634cc 100644--- a/src/modules/infra/infra-config.controller.spec.ts+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -180,6 +180,18 @@ describe('InfraConfigController.saveConfig values the next boot refuses', () =>['a negative pool size', { database: { ...external, poolSize: -5 } }],['a fractional pool size', { database: { ...external, poolSize: 1.5 } }],['a redis port that is not a number', { redis: { enabled: true, host: 'cache', port: 'x' } }],+ [+ 'an S3 endpoint without a scheme',+ {+ storage: {+ type: 's3',+ builtIn: false,+ s3Endpoint: 'minio:9000',+ s3AccessKey: 'AccessKey1234',+ s3SecretKey: 'SecretKey1234567',+ },+ },+ ],])('refuses %s instead of writing it', (_label, config) => {(fs.writeFileSync as jest.Mock).mockClear();@@ -187,6 +199,39 @@ describe('InfraConfigController.saveConfig values the next boot refuses', () =>expect(fs.writeFileSync).not.toHaveBeenCalled();});+ // The boot only reports an S3 endpoint the client cannot use, so a deployment running on its local fallback must+ // still be able to save other settings; only a save that names the storage type or the endpoint is refused.+ describe('an S3 endpoint without a scheme already stored', () => {+ const STORED =+ 'STORAGE_TYPE=s3\nS3_ENDPOINT=minio:9000\nS3_ACCESS_KEY_ID=AccessKey1234\nS3_SECRET_ACCESS_KEY=SecretKey1234567\n';+ beforeEach(() => {+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue(STORED);+ (fs.writeFileSync as jest.Mock).mockClear();+ });+ afterEach(() => {+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });++ it('does not stop a save of another section', () => {+ expect(newController().saveConfig({ engine: { headless: false } }).saved).toBe(true);+ });++ it('refuses a save that names the storage type again, with the boot text', () => {+ expect(() => newController().saveConfig({ storage: { type: 's3', s3Bucket: 'media' } } as never)).toThrow(+ /fails boot validation\. S3_ENDPOINT must be an absolute http\(s\) URL/,+ );+ expect(fs.writeFileSync).not.toHaveBeenCalled();+ });++ it('accepts the endpoint once it carries the scheme', () => {+ expect(+ newController().saveConfig({ storage: { type: 's3', s3Endpoint: 'http://minio:9000' } } as never).saved,+ ).toBe(true);+ });+ });+it('writes a blank host and user as the defaults and trims a padded port', () => {(fs.writeFileSync as jest.Mock).mockClear();diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.tsindex 08522ea06..8451e7a9e 100644--- a/src/modules/infra/infra-config.controller.ts+++ b/src/modules/infra/infra-config.controller.ts@@ -31,7 +31,7 @@ import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { SaveConfigDto } from './dto/save-config.dto';import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-security';-import { validateEnv } from '../../config/env.validation';+import { s3EndpointError, validateEnv } from '../../config/env.validation';import { BLANK_SHADOWED_ENV_KEYS, isEnvPinned, isOsProvidedEnv } from '../../config/env-precedence';import { resolveStorageRoot } from '../../config/storage-root';import { randomUUID } from 'crypto';@@ -216,7 +216,7 @@ export class InfraConfigController {this.assertNoLineBreakValues(updates);const merged = this.mergeWithExisting(existing, ctx);this.assertProductionBootable(merged);- this.assertBootValidates(merged);+ this.assertBootValidates(updates, merged);this.assertStorageRootWritable(updates, merged);this.persistGeneratedEnv(envPath, merged);this.auditConfigSaved(config, profiles);@@ -355,10 +355,15 @@ export class InfraConfigController {// The environment validation the next boot runs (env.validation.ts), applied to the same view of the merged result.// Without it a save the dashboard accepts, a PostgreSQL selection with no host or a pool size that is not a plain// integer, crash-loops the instance and the dashboard that could undo it.- private assertBootValidates(merged: Record<string, string>): void {+ // The boot only reports an S3 endpoint the client cannot use, so a deployment on its local fallback keeps starting+ // and keeps saving other settings; a save that names the storage type or the endpoint is refused instead.+ private assertBootValidates(updates: Record<string, string>, merged: Record<string, string>): void {const bootValue = this.bootValueReader(merged);try {- validateEnv(Object.fromEntries(Object.keys({ ...process.env, ...merged }).map(key => [key, bootValue(key)])));+ const env = Object.fromEntries(Object.keys({ ...process.env, ...merged }).map(key => [key, bootValue(key)]));+ validateEnv(env);+ const s3Problem = 'STORAGE_TYPE' in updates || 'S3_ENDPOINT' in updates ? s3EndpointError(env) : null;+ if (s3Problem) throw new Error(s3Problem);} catch (error) {const detail = error instanceof Error ? error.message : String(error);throw new BadRequestException(`Refusing to save a configuration that fails boot validation. ${detail}`);