Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): mask nested config secrets on reveal and audit instance updates/redrives (#929)

Yudhi Armyndharisb954a91c4fbc
diff --git a/openapi.json b/openapi.json
index 28c42b546..9f018c901 100644
--- a/openapi.json
+++ b/openapi.json
@@ -35,6 +35,7 @@
"integration_instance_updated",
"integration_instance_secret_regenerated",
"integration_instance_deleted",
+ "integration_instance_redriven",
"infra_config_saved",
"infra_restart_requested",
"infra_data_exported",
@@ -7956,7 +7957,7 @@
},
"config": {
"type": "object",
- "description": "Per-instance config slice passed to the adapter, or null.",
+ "description": "Per-instance config slice passed to the adapter, or null. Fields flagged `secret` in the plugin's config schema are masked ('***') on EVERY response — including create/regenerate-secret; only the ingress secret and verifyToken are ever revealed once.",
"nullable": true
},
"enabled": {
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 7ff8395da..c495a597e 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -34,6 +34,7 @@ export enum AuditAction {
INTEGRATION_INSTANCE_UPDATED = 'integration_instance_updated',
INTEGRATION_INSTANCE_SECRET_REGENERATED = 'integration_instance_secret_regenerated',
INTEGRATION_INSTANCE_DELETED = 'integration_instance_deleted',
+ INTEGRATION_INSTANCE_REDRIVEN = 'integration_instance_redriven',
// Infrastructure events (ADMIN-only operations on the infra module: credential-bearing config
// mutation, server restart / Docker orchestration, and full-DB / storage export+import).
diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.ts
index 844145171..b18199dba 100644
--- a/src/modules/integration/dto/instance.dto.ts
+++ b/src/modules/integration/dto/instance.dto.ts
@@ -113,7 +113,8 @@ export class InstanceView {
verifyToken: string | null;
@ApiPropertyOptional({
- description: 'Per-instance config slice passed to the adapter, or null.',
+ description:
+ "Per-instance config slice passed to the adapter, or null. Fields flagged `secret` in the plugin's config schema are masked ('***') on EVERY response — including create/regenerate-secret; only the ingress secret and verifyToken are ever revealed once.",
nullable: true,
type: Object,
})
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.ts
index cb287f12e..1da6272f3 100644
--- a/src/modules/integration/integration-instance.controller.spec.ts
+++ b/src/modules/integration/integration-instance.controller.spec.ts
@@ -2,6 +2,7 @@ import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { IntegrationInstanceController } from './integration-instance.controller';
import { PluginInstanceService } from './plugin-instance.service';
import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
+import { AuditAction } from '../audit/entities/audit-log.entity';
import { AuditService } from '../audit/audit.service';
import { ScopeBindingService } from './scope-binding.service';
import { ApiKey } from '../auth/entities/api-key.entity';
@@ -23,7 +24,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {
setPluginSessions,
updatePluginConfig,
} as unknown as PluginLoaderService;
- const audit = { logInfo: jest.fn() } as unknown as AuditService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
return { loader, audit, setPluginSessionConfig, setPluginSessions, updatePluginConfig };
}
@@ -43,6 +44,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {
updatedAt: new Date(0),
}),
list: jest.fn().mockResolvedValue([]),
+ maskedView: (i: unknown) => i,
} as unknown as PluginInstanceService;
const controller = new IntegrationInstanceController(
instances,
@@ -423,7 +425,7 @@ describe('IntegrationInstanceController session-scope fence', () => {
setPluginSessions: jest.fn(),
updatePluginConfig: jest.fn(),
} as unknown as PluginLoaderService;
- const audit = { logInfo: jest.fn() } as unknown as AuditService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
const svc = { maskedView: (i: unknown) => i, ...instances } as unknown as PluginInstanceService;
const controller = new IntegrationInstanceController(
svc,
@@ -542,3 +544,210 @@ describe('IntegrationInstanceController session-scope fence', () => {
expect(setEnabled).toHaveBeenCalledWith('chatwoot-adapter', 'acct1', false);
});
});
+
+// The create/regenerate responses are the ONE place plaintext appears — but only for the two fields
+// documented as "revealed once" (the ingress secret + verifyToken). Config fields flagged `secret` in
+// the plugin's schema must stay masked at any depth even there: a reveal that bypassed maskedView
+// would echo a stored provider credential back to the caller.
+describe('IntegrationInstanceController reveal masking', () => {
+ const configSchema = {
+ type: 'object' as const,
+ properties: {
+ baseUrl: { type: 'string' as const },
+ credentials: {
+ type: 'object' as const,
+ properties: {
+ apiToken: { type: 'string' as const, secret: true },
+ region: { type: 'string' as const },
+ },
+ },
+ webhooks: {
+ type: 'array' as const,
+ items: {
+ type: 'object' as const,
+ properties: {
+ url: { type: 'string' as const },
+ signingKey: { type: 'string' as const, secret: true },
+ },
+ },
+ },
+ },
+ };
+
+ const storedConfig = {
+ baseUrl: 'https://chatwoot.example',
+ credentials: { apiToken: 'tok-live-123', region: 'us' },
+ webhooks: [{ url: 'https://hook.example', signingKey: 'whsec-live-456' }],
+ };
+
+ function build() {
+ const loader = {
+ getPlugin: jest.fn().mockReturnValue({
+ manifest: {
+ id: 'chatwoot-adapter',
+ ingress: [{ route: 'chatwoot' }],
+ permissions: ['webhook:ingress'],
+ configSchema,
+ },
+ activeSessions: [],
+ }),
+ setPluginSessionConfig: jest.fn(),
+ setPluginSessions: jest.fn(),
+ updatePluginConfig: jest.fn(),
+ } as unknown as PluginLoaderService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
+ const instance = {
+ id: 'chatwoot-adapter:acct1',
+ pluginId: 'chatwoot-adapter',
+ instanceId: 'acct1',
+ sessionScope: 'sess-1',
+ secret: 'plaintext-ingress-secret',
+ verifyToken: 'verify-token-plain',
+ config: storedConfig,
+ enabled: true,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ };
+ const instances = {
+ create: jest.fn().mockResolvedValue(instance),
+ resolve: jest.fn().mockResolvedValue(instance),
+ regenerateSecret: jest.fn().mockResolvedValue({ ...instance, secret: 'new-plaintext-secret' }),
+ list: jest.fn().mockResolvedValue([]),
+ // The REAL redaction (not a stub) so the test fails if a reveal path ever bypasses it.
+ maskedView: (...args: Parameters<PluginInstanceService['maskedView']>) =>
+ PluginInstanceService.prototype.maskedView(...args),
+ } as unknown as PluginInstanceService;
+ const controller = new IntegrationInstanceController(
+ instances,
+ loader,
+ audit,
+ new ScopeBindingService(instances, loader, audit),
+ );
+ return { controller };
+ }
+
+ function expectMaskedConfig(config: Record<string, unknown>) {
+ // Deep secrets masked; non-secret fields (incl. nested + array siblings) still visible.
+ expect(config.baseUrl).toBe('https://chatwoot.example');
+ expect((config.credentials as Record<string, unknown>).apiToken).toBe('***');
+ expect((config.credentials as Record<string, unknown>).region).toBe('us');
+ const hooks = config.webhooks as Array<Record<string, unknown>>;
+ expect(hooks[0].url).toBe('https://hook.example');
+ expect(hooks[0].signingKey).toBe('***');
+ expect(JSON.stringify(config)).not.toContain('tok-live-123');
+ expect(JSON.stringify(config)).not.toContain('whsec-live-456');
+ }
+
+ it('create reveals ONLY the ingress secret + verifyToken; nested config secrets stay masked', async () => {
+ const { controller } = build();
+
+ const view = await controller.create('chatwoot-adapter', {
+ instanceId: 'acct1',
+ sessionScope: 'sess-1',
+ verifyToken: 'verify-token-plain',
+ config: storedConfig,
+ });
+
+ expect(view.secret).toBe('plaintext-ingress-secret');
+ expect(view.verifyToken).toBe('verify-token-plain');
+ expectMaskedConfig(view.config as Record<string, unknown>);
+ });
+
+ it('regenerate-secret reveals the new secret + verifyToken; nested config secrets stay masked', async () => {
+ const { controller } = build();
+
+ const view = await controller.regenerate('chatwoot-adapter', 'acct1');
+
+ expect(view.secret).toBe('new-plaintext-secret');
+ expect(view.verifyToken).toBe('verify-token-plain');
+ expectMaskedConfig(view.config as Record<string, unknown>);
+ });
+
+ it('a plain read masks secret, verifyToken, AND config secrets (unchanged behavior)', async () => {
+ const { controller } = build();
+
+ const view = await controller.getOne('chatwoot-adapter', 'acct1');
+
+ expect(view.secret).toBe('***');
+ expect(view.verifyToken).toBe('***');
+ expectMaskedConfig(view.config as Record<string, unknown>);
+ });
+});
+
+// A successful PATCH must leave an audit row; the metadata names the CHANGED FIELDS only — never the
+// values, since a config patch can carry credentials and audit metadata is not a credential store.
+describe('IntegrationInstanceController update audit', () => {
+ function build() {
+ const loader = {
+ getPlugin: jest.fn().mockReturnValue({
+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },
+ activeSessions: [],
+ }),
+ setPluginSessionConfig: jest.fn(),
+ setPluginSessions: jest.fn(),
+ updatePluginConfig: jest.fn(),
+ } as unknown as PluginLoaderService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() };
+ const instance = {
+ id: 'chatwoot-adapter:acct1',
+ pluginId: 'chatwoot-adapter',
+ instanceId: 'acct1',
+ sessionScope: 'sess-1',
+ secret: 's',
+ verifyToken: null,
+ config: { apiToken: 'super-secret-token' },
+ enabled: true,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ };
+ const instances = {
+ resolve: jest.fn().mockResolvedValue(instance),
+ setEnabled: jest.fn().mockResolvedValue({ ...instance, enabled: false }),
+ update: jest.fn().mockResolvedValue({ ...instance, config: { apiToken: 'rotated-token' } }),
+ list: jest.fn().mockResolvedValue([]),
+ maskedView: (i: unknown) => i,
+ } as unknown as PluginInstanceService;
+ const controller = new IntegrationInstanceController(
+ instances,
+ loader,
+ audit as unknown as AuditService,
+ new ScopeBindingService(instances, loader, audit as unknown as AuditService),
+ );
+ return { controller, audit, instances };
+ }
+
+ it('emits INTEGRATION_INSTANCE_UPDATED (INFO) on a successful patch with clean metadata', async () => {
+ const { controller, audit } = build();
+
+ await controller.patch('chatwoot-adapter', 'acct1', {
+ enabled: false,
+ config: { apiToken: 'rotated-token' },
+ });
+
+ expect(audit.logInfo).toHaveBeenCalledWith(AuditAction.INTEGRATION_INSTANCE_UPDATED, {
+ metadata: { pluginId: 'chatwoot-adapter', instanceId: 'acct1', updated: ['enabled', 'config'] },
+ });
+ // The metadata must not carry any raw config/secret value.
+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: Record<string, unknown> }]>;
+ expect(JSON.stringify(calls[0][1].metadata)).not.toContain('rotated-token');
+ expect(JSON.stringify(calls[0][1].metadata)).not.toContain('super-secret-token');
+ });
+
+ it('records a sessionScope-only change without dragging config into the metadata', async () => {
+ const { controller, audit } = build();
+
+ await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' });
+
+ expect(audit.logInfo).toHaveBeenCalledWith(AuditAction.INTEGRATION_INSTANCE_UPDATED, {
+ metadata: { pluginId: 'chatwoot-adapter', instanceId: 'acct1', updated: ['sessionScope'] },
+ });
+ });
+
+ it('does not emit an update row when the patch is rejected', async () => {
+ const { controller, audit, instances } = build();
+ (instances.resolve as jest.Mock).mockResolvedValue(null);
+
+ await expect(controller.patch('chatwoot-adapter', 'acct1', { enabled: false })).rejects.toThrow(NotFoundException);
+ expect(audit.logInfo).not.toHaveBeenCalledWith(AuditAction.INTEGRATION_INSTANCE_UPDATED, expect.anything());
+ });
+});
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
index 96dbe8390..f97e426ad 100644
--- a/src/modules/integration/integration-instance.controller.ts
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -142,6 +142,12 @@ export class IntegrationInstanceController {
await this.scopeBinding.applyScopeBinding(pluginId, previousScope, {}, false);
}
await this.scopeBinding.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);
+ // Audit the successful update with the CHANGED FIELD NAMES only — never the values: a config patch
+ // can carry credentials, and audit metadata is not a credential store.
+ const updatedFields = (['enabled', 'sessionScope', 'config'] as const).filter(f => dto[f] !== undefined);
+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_UPDATED, {
+ metadata: { pluginId, instanceId, updated: updatedFields },
+ });
return this.view(updated, this.pluginRoutes(pluginId), false);
}
@@ -206,13 +212,17 @@ export class IntegrationInstanceController {
private view(inst: PluginInstance, routes: string[], reveal: boolean): InstanceView {
const schema = this.loader.getPlugin(inst.pluginId)?.manifest.configSchema;
- const masked = reveal ? inst : this.instances.maskedView(inst, schema);
+ // ALWAYS start from the masked view — including the one-shot reveal responses (create /
+ // regenerate-secret). `reveal` unmasks ONLY the two fields documented as "revealed once" (the
+ // ingress secret and the verifyToken); config fields flagged `secret` in the plugin's schema
+ // stay masked at any depth on every response, so a reveal can never echo a stored credential.
+ const masked = this.instances.maskedView(inst, schema);
return {
id: masked.id,
pluginId: masked.pluginId,
instanceId: masked.instanceId,
sessionScope: masked.sessionScope,
- secret: masked.secret,
+ secret: reveal ? inst.secret : masked.secret,
verifyToken: reveal ? inst.verifyToken : inst.verifyToken ? '***' : null,
config: masked.config,
enabled: masked.enabled,
diff --git a/src/modules/integration/redrive.controller.spec.ts b/src/modules/integration/redrive.controller.spec.ts
index e6edbc262..eff81115f 100644
--- a/src/modules/integration/redrive.controller.spec.ts
+++ b/src/modules/integration/redrive.controller.spec.ts
@@ -3,6 +3,8 @@ import { NotFoundException } from '@nestjs/common';
import { RedriveController } from './redrive.controller';
import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';
import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';
+import { AuditAction } from '../audit/entities/audit-log.entity';
+import { AuditService } from '../audit/audit.service';
import { PluginInstanceService } from './plugin-instance.service';
import { RedriveService } from './redrive.service';
@@ -29,11 +31,13 @@ describe('RedriveController session-scope fence', () => {
sessionScope === undefined ? null : { pluginId: 'chatwoot', instanceId: 'acct1', sessionScope },
),
};
+ const audit = { logInfo: jest.fn() };
const controller = new RedriveController(
redrive as unknown as RedriveService,
instances as unknown as PluginInstanceService,
+ audit as unknown as AuditService,
);
- return { controller, redrive };
+ return { controller, redrive, audit };
}
it('lets a scoped key redrive an instance bound to one of its sessions', async () => {
@@ -65,4 +69,22 @@ describe('RedriveController session-scope fence', () => {
expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');
});
+
+ it('audits a successful redrive with its outcome counts (a redrive can cause real sends)', async () => {
+ const { controller, redrive, audit } = build('sess-1');
+ redrive.redriveInstance.mockResolvedValue({ redriven: 3, remaining: 7, batchSize: 100 });
+
+ await controller.redriveInstance('chatwoot', 'acct1', scopedKey);
+
+ expect(audit.logInfo).toHaveBeenCalledWith(AuditAction.INTEGRATION_INSTANCE_REDRIVEN, {
+ metadata: { pluginId: 'chatwoot', instanceId: 'acct1', redriven: 3, remaining: 7 },
+ });
+ });
+
+ it('does not audit a rejected (out-of-scope) redrive', async () => {
+ const { controller, audit } = build('sess-2');
+
+ await expect(controller.redriveInstance('chatwoot', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);
+ expect(audit.logInfo).not.toHaveBeenCalled();
+ });
});
diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.ts
index 6d5ec9ea7..11eebd3e0 100644
--- a/src/modules/integration/redrive.controller.ts
+++ b/src/modules/integration/redrive.controller.ts
@@ -2,6 +2,8 @@ import { Controller, NotFoundException, Param, Post } from '@nestjs/common';
import { ApiTags, ApiResponse } from '@nestjs/swagger';
import { CurrentApiKey, RequireRole } from '../auth/decorators/auth.decorators';
import { type ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';
+import { AuditAction } from '../audit/entities/audit-log.entity';
+import { AuditService } from '../audit/audit.service';
import { sessionScopeVisible } from '../../common/security/session-scope';
import { PluginInstanceService } from './plugin-instance.service';
import { RedriveService } from './redrive.service';
@@ -16,6 +18,7 @@ export class RedriveController {
constructor(
private readonly redrive: RedriveService,
private readonly instances: PluginInstanceService,
+ private readonly audit: AuditService,
) {}
@Post(':pluginId/:instanceId/redrive')
@@ -34,6 +37,12 @@ export class RedriveController {
if (inst && !sessionScopeVisible(apiKey?.allowedSessions, inst.sessionScope)) {
throw new NotFoundException('instance not found');
}
- return this.redrive.redriveInstance(pluginId, instanceId);
+ const result = await this.redrive.redriveInstance(pluginId, instanceId);
+ // A redrive can trigger real downstream sends, so every successful batch is audited with its
+ // outcome counts (no payload content — the DLQ rows themselves hold those).
+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_REDRIVEN, {
+ metadata: { pluginId, instanceId, redriven: result.redriven, remaining: result.remaining },
+ });
+ return result;
}
}
diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.ts
index 1d92ab77b..62a3912a5 100644
--- a/src/modules/integration/scope-binding.service.spec.ts
+++ b/src/modules/integration/scope-binding.service.spec.ts
@@ -17,7 +17,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {
setPluginSessions,
updatePluginConfig,
} as unknown as PluginLoaderService;
- const audit = { logInfo: jest.fn() } as unknown as AuditService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
return { loader, audit, setPluginSessionConfig, setPluginSessions, updatePluginConfig };
}
@@ -105,7 +105,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {
}),
updatePluginConfig: jest.fn(),
} as unknown as PluginLoaderService;
- const audit = { logInfo: jest.fn() } as unknown as AuditService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
const wildcard = { pluginId: 'chatwoot', instanceId: 'wild', sessionScope: null, config: {}, enabled: true };
const concrete = { pluginId: 'chatwoot', instanceId: 'conc', sessionScope: 'sess-1', config: {}, enabled: true };
diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.ts
index 89380a7ad..c1a1fb639 100644
--- a/src/modules/integration/scope-binding.service.ts
+++ b/src/modules/integration/scope-binding.service.ts
@@ -26,7 +26,7 @@ export class ScopeBindingService implements OnApplicationBootstrap {
/**
* Re-derive every ENABLED instance's runtime scope binding from the persisted `plugin_instances`
* rows, so a binding lost at provisioning time (the plugin was momentarily unloaded, so
- * applyScopeBinding was swallowed as an INFO audit) is restored on the next boot without an operator
+ * applyScopeBinding was swallowed as a WARN audit) is restored on the next boot without an operator
* re-PATCH — otherwise the row shows `enabled` but the ingress handler resolves base config only.
* Runs after every module's onModuleInit (so PluginLoaderService has loaded all plugins).
*
@@ -139,8 +139,11 @@ export class ScopeBindingService implements OnApplicationBootstrap {
}
this.loader.setPluginSessions(pluginId, [...set]);
} catch (err) {
- // Best-effort: don't fail provisioning if the plugin is momentarily unloaded.
- void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_UPDATED, {
+ // Best-effort: don't fail provisioning if the plugin is momentarily unloaded. WARN (not INFO):
+ // the binding is LOST until the next boot-time reconciliation — the instance row reads `enabled`
+ // but the ingress worker won't resolve its config — so this degradation must stand out in the
+ // audit trail rather than blend into routine update rows.
+ void this.audit.logWarn(AuditAction.INTEGRATION_INSTANCE_UPDATED, {
metadata: { pluginId, scope, bridgeError: String(err) },
});
}
diff --git a/test/integration-instance.e2e-spec.ts b/test/integration-instance.e2e-spec.ts
index e735c5ad0..49fdbc825 100644
--- a/test/integration-instance.e2e-spec.ts
+++ b/test/integration-instance.e2e-spec.ts
@@ -16,16 +16,37 @@ import { PluginLoaderService } from '../src/core/plugins/plugin-loader.service';
import { AuthService } from '../src/modules/auth/auth.service';
import { ApiKeyRole } from '../src/modules/auth/entities/api-key.entity';
-// A stub ingress-capable plugin so the capability check passes without a real plugin on disk.
+// A stub ingress-capable plugin so the capability check passes without a real plugin on disk. The
+// configSchema carries a NESTED secret field so the masking tests can prove a `secret:true` config
+// value is redacted at depth — including on the one-shot create/regenerate reveal responses.
const INGRESS_PLUGIN = {
- manifest: { id: 'chatwoot', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress', 'conversation:send'] },
+ manifest: {
+ id: 'chatwoot',
+ ingress: [{ route: 'chatwoot' }],
+ permissions: ['webhook:ingress', 'conversation:send'],
+ configSchema: {
+ type: 'object',
+ properties: {
+ baseUrl: { type: 'string' },
+ credentials: {
+ type: 'object',
+ properties: {
+ apiToken: { type: 'string', secret: true },
+ region: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
};
const NON_INGRESS_PLUGIN = { manifest: { id: 'plain', permissions: [] } };
interface InstanceViewBody {
secret: string;
+ verifyToken: string | null;
enabled: boolean;
sessionScope: string | null;
+ config: { baseUrl?: string; credentials?: { apiToken?: string; region?: string } } | null;
ingressUrls: Array<{ route: string; url: string }>;
}
@@ -133,6 +154,52 @@ describe('IntegrationInstanceController (e2e)', () => {
expect((one.body as InstanceViewBody).secret).toBe('***');
});
+ it('reveals ONLY the ingress secret + verifyToken on create — nested secret config stays masked', async () => {
+ const create = await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances`)
+ .set('X-API-Key', key)
+ .send({
+ instanceId: 'nested1',
+ verifyToken: 'vt-plain-123',
+ config: {
+ baseUrl: 'https://chatwoot.example',
+ credentials: { apiToken: 'tok-e2e-live', region: 'us' },
+ },
+ })
+ .expect(201);
+ const body = create.body as InstanceViewBody;
+ // The two documented "revealed once" fields are plaintext...
+ expect(body.secret).toMatch(/^[0-9a-f]{64}$/);
+ expect(body.verifyToken).toBe('vt-plain-123');
+ // ...while a secret-flagged config field is masked even on this reveal response, at any depth.
+ expect(body.config?.baseUrl).toBe('https://chatwoot.example');
+ expect(body.config?.credentials?.apiToken).toBe('***');
+ expect(body.config?.credentials?.region).toBe('us');
+ expect(JSON.stringify(body)).not.toContain('tok-e2e-live');
+
+ const one = await request(app.getHttpServer())
+ .get(`${base}/chatwoot/instances/nested1`)
+ .set('X-API-Key', key)
+ .expect(200);
+ const read = one.body as InstanceViewBody;
+ expect(read.secret).toBe('***');
+ expect(read.verifyToken).toBe('***');
+ expect(read.config?.credentials?.apiToken).toBe('***');
+ expect(read.config?.baseUrl).toBe('https://chatwoot.example');
+ });
+
+ it('keeps nested secret config masked on the regenerate-secret reveal', async () => {
+ const regen = await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances/nested1/regenerate-secret`)
+ .set('X-API-Key', key)
+ .expect(200);
+ const body = regen.body as InstanceViewBody;
+ expect(body.secret).toMatch(/^[0-9a-f]{64}$/);
+ expect(body.verifyToken).toBe('vt-plain-123');
+ expect(body.config?.credentials?.apiToken).toBe('***');
+ expect(JSON.stringify(body)).not.toContain('tok-e2e-live');
+ });
+
it('patches enabled + sessionScope and returns a masked view', async () => {
const patched = await request(app.getHttpServer())
.patch(`${base}/chatwoot/instances/acct1`)