From 2a3faad46292f147f77495fe2d001d39bc25800c Mon Sep 17 00:00:00 2001 From: Enno Gelhaus Date: Wed, 9 Sep 2026 20:10:01 +0200 Subject: [PATCH] test: cover local storage uploads, the mcp oauth middleware and the channels controller --- .../src/chat/oauth-middleware.spec.ts | 402 ++++++++++++++++++ .../src/upload/local.storage.spec.ts | 200 +++++++++ .../integrations.controller.int.spec.ts | 238 +++++++++++ 3 files changed, 840 insertions(+) create mode 100644 libraries/nestjs-libraries/src/chat/oauth-middleware.spec.ts create mode 100644 libraries/nestjs-libraries/src/upload/local.storage.spec.ts create mode 100644 tests/integration/integrations.controller.int.spec.ts diff --git a/libraries/nestjs-libraries/src/chat/oauth-middleware.spec.ts b/libraries/nestjs-libraries/src/chat/oauth-middleware.spec.ts new file mode 100644 index 00000000..4a70ee87 --- /dev/null +++ b/libraries/nestjs-libraries/src/chat/oauth-middleware.spec.ts @@ -0,0 +1,402 @@ +import type * as http from 'node:http'; + +import type { MCPServerOAuthConfig } from './oauth-types'; +import { + createIntrospectionValidator, + createOAuthMiddleware, + createStaticTokenValidator, +} from './oauth-middleware'; + +const RESOURCE = 'https://api.example.test/mcp-oauth'; + +const config = (over: Partial = {}): MCPServerOAuthConfig => ({ + resource: RESOURCE, + authorizationServers: ['https://auth.example.test'], + ...over, +}); + +/** Captures what the middleware wrote, since it answers on the raw response. */ +const response = () => { + const captured = { + status: 0, + headers: {} as Record, + body: '', + }; + + const res = { + writeHead: (status: number, headers?: Record) => { + captured.status = status; + captured.headers = headers ?? {}; + return res; + }, + end: (body?: string) => { + captured.body = body ?? ''; + return res; + }, + } as unknown as http.ServerResponse; + + return { res, captured, json: () => JSON.parse(captured.body || '{}') }; +}; + +const call = ( + middleware: ReturnType, + path: string, + init: { method?: string; authorization?: string } = {} +) => { + const { res, captured, json } = response(); + const req = { + method: init.method ?? 'GET', + headers: init.authorization ? { authorization: init.authorization } : {}, + } as unknown as http.IncomingMessage; + + return middleware(req, res, new URL(path, RESOURCE)).then((result) => ({ + result, + captured, + json, + })); +}; + +describe('createOAuthMiddleware protected resource metadata', () => { + it('serves the metadata document at the well known path', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { result, captured, json } = await call( + middleware, + '/.well-known/oauth-protected-resource' + ); + + expect(result).toEqual({ proceed: false, handled: true }); + expect(captured.status).toBe(200); + expect(captured.headers['Content-Type']).toBe('application/json'); + expect(json()).toMatchObject({ + resource: RESOURCE, + authorization_servers: ['https://auth.example.test'], + scopes_supported: ['mcp:read', 'mcp:write'], + bearer_methods_supported: ['header'], + }); + }); + + it('carries the optional descriptive fields when configured', async () => { + const middleware = createOAuthMiddleware({ + oauth: config({ + resourceName: 'Postiz MCP', + resourceDocumentation: 'https://docs.example.test', + scopesSupported: ['mcp:read'], + }), + }); + + const { json } = await call( + middleware, + '/.well-known/oauth-protected-resource' + ); + + expect(json()).toMatchObject({ + resource_name: 'Postiz MCP', + resource_documentation: 'https://docs.example.test', + scopes_supported: ['mcp:read'], + }); + }); + + it('answers a cors preflight for the metadata endpoint', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { result, captured } = await call( + middleware, + '/.well-known/oauth-protected-resource', + { method: 'OPTIONS' } + ); + + expect(result).toEqual({ proceed: false, handled: true }); + expect(captured.status).toBe(204); + expect(captured.headers['Access-Control-Allow-Methods']).toContain('GET'); + }); + + it('leaves any other path to the application', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { result } = await call(middleware, '/health'); + + expect(result).toEqual({ proceed: true, handled: false }); + }); +}); + +describe('createOAuthMiddleware token enforcement', () => { + it('refuses an mcp request with no bearer token', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { result, captured, json } = await call(middleware, '/mcp'); + + expect(result).toEqual({ proceed: false, handled: true }); + expect(captured.status).toBe(401); + expect(json()).toEqual({ + error: 'unauthorized', + error_description: 'Bearer token required', + }); + }); + + it('points the client at the metadata document it should read', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { captured } = await call(middleware, '/mcp'); + + // RFC 9728 path-inserted form, so the root well-known can stay a 404 + expect(captured.headers['WWW-Authenticate']).toContain( + 'resource_metadata="https://api.example.test/.well-known/oauth-protected-resource/mcp-oauth"' + ); + }); + + it('rejects an authorization header that is not a bearer', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { captured } = await call(middleware, '/mcp', { + authorization: 'Basic abc', + }); + + expect(captured.status).toBe(401); + }); + + it('accepts a token when no validator is configured', async () => { + const middleware = createOAuthMiddleware({ oauth: config() }); + + const { result } = await call(middleware, '/mcp', { + authorization: 'Bearer anything', + }); + + expect(result).toEqual({ + proceed: true, + handled: false, + tokenValidation: { valid: true }, + }); + }); + + it('lets a validated token through and passes the claims on', async () => { + const middleware = createOAuthMiddleware({ + oauth: config({ + validateToken: async () => ({ valid: true, subject: 'user-1' }), + }), + }); + + const { result } = await call(middleware, '/mcp', { + authorization: 'Bearer good', + }); + + expect(result).toMatchObject({ + proceed: true, + handled: false, + tokenValidation: { valid: true, subject: 'user-1' }, + }); + }); + + it('refuses a token the validator rejects, echoing the reason', async () => { + const middleware = createOAuthMiddleware({ + oauth: config({ + validateToken: async () => ({ + valid: false, + error: 'expired_token', + errorDescription: 'The token expired', + }), + }), + }); + + const { result, captured, json } = await call(middleware, '/mcp', { + authorization: 'Bearer stale', + }); + + expect(result.proceed).toBe(false); + expect(captured.status).toBe(401); + expect(captured.headers['WWW-Authenticate']).toContain('error="expired_token"'); + expect(json()).toEqual({ + error: 'expired_token', + error_description: 'The token expired', + }); + }); + + it('falls back to invalid_token when the validator gives no reason', async () => { + const middleware = createOAuthMiddleware({ + oauth: config({ validateToken: async () => ({ valid: false }) }), + }); + + const { json } = await call(middleware, '/mcp', { + authorization: 'Bearer stale', + }); + + expect(json()).toEqual({ + error: 'invalid_token', + error_description: 'Token validation failed', + }); + }); + + it('protects a configured path other than the default', async () => { + const middleware = createOAuthMiddleware({ + oauth: config(), + mcpPath: '/agent', + }); + + const { result: unprotected } = await call(middleware, '/mcp'); + expect(unprotected).toEqual({ proceed: true, handled: false }); + + const { captured } = await call(middleware, '/agent/messages'); + expect(captured.status).toBe(401); + }); + + it('reports what it did to the logger', async () => { + const debug = vi.fn(); + const middleware = createOAuthMiddleware({ + oauth: config(), + logger: { debug }, + }); + + await call(middleware, '/mcp'); + + expect(debug).toHaveBeenCalledWith(expect.stringContaining('GET /mcp')); + }); +}); + +describe('createStaticTokenValidator', () => { + it('accepts a listed token with the default scopes', async () => { + const validate = createStaticTokenValidator(['tok-1'])!; + + await expect(validate('tok-1', RESOURCE)).resolves.toEqual({ + valid: true, + scopes: ['mcp:read', 'mcp:write'], + }); + }); + + it('rejects anything not on the list', async () => { + const validate = createStaticTokenValidator(['tok-1'])!; + + await expect(validate('tok-2', RESOURCE)).resolves.toMatchObject({ + valid: false, + error: 'invalid_token', + }); + }); +}); + +describe('createIntrospectionValidator', () => { + const ENDPOINT = 'https://auth.example.test/introspect'; + + it('accepts an active token and maps its scopes', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + Response.json({ active: true, scope: 'mcp:read mcp:write', sub: 'u1', exp: 99 }) + ) + ); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ + valid: true, + scopes: ['mcp:read', 'mcp:write'], + subject: 'u1', + expiresAt: 99, + }); + }); + + it('rejects a token the server reports as inactive', async () => { + vi.stubGlobal('fetch', vi.fn(async () => Response.json({ active: false }))); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ + valid: false, + error: 'invalid_token', + errorDescription: 'Token is not active', + }); + }); + + it('refuses a token minted for a different resource', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + Response.json({ active: true, aud: 'https://someone-else.test' }) + ) + ); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ + valid: false, + errorDescription: 'Token audience does not match this resource', + }); + }); + + it('accepts a token whose audience list includes this resource', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + Response.json({ active: true, aud: ['https://other.test', RESOURCE] }) + ) + ); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ valid: true }); + }); + + it('sends basic credentials when the client is configured', async () => { + const fetchSpy = vi.fn( + async (_url: string, _init: RequestInit) => Response.json({ active: true }) + ); + vi.stubGlobal('fetch', fetchSpy); + const validate = createIntrospectionValidator(ENDPOINT, { + clientId: 'client', + clientSecret: 'secret', + })!; + + await validate('tok', RESOURCE); + + const [, init] = fetchSpy.mock.calls[0]; + expect((init.headers as Record)['Authorization']).toBe( + `Basic ${Buffer.from('client:secret').toString('base64')}` + ); + }); + + it('refuses a client id that would break basic auth framing', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + const validate = createIntrospectionValidator(ENDPOINT, { + clientId: 'client:with:colons', + clientSecret: 'secret', + })!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ + valid: false, + error: 'invalid_request', + }); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('reports a non-ok introspection as a server error', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('nope', { status: 503 })) + ); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ + valid: false, + error: 'server_error', + errorDescription: 'Introspection failed: 503', + }); + }); + + it('reports a network failure rather than throwing', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('connect ECONNREFUSED'); + }) + ); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ + valid: false, + error: 'server_error', + errorDescription: 'connect ECONNREFUSED', + }); + }); + + it('treats a token with no scope string as having none', async () => { + vi.stubGlobal('fetch', vi.fn(async () => Response.json({ active: true }))); + const validate = createIntrospectionValidator(ENDPOINT)!; + + await expect(validate('tok', RESOURCE)).resolves.toMatchObject({ scopes: [] }); + }); +}); diff --git a/libraries/nestjs-libraries/src/upload/local.storage.spec.ts b/libraries/nestjs-libraries/src/upload/local.storage.spec.ts new file mode 100644 index 00000000..dadda5e9 --- /dev/null +++ b/libraries/nestjs-libraries/src/upload/local.storage.spec.ts @@ -0,0 +1,200 @@ +const { isSafePublicHttpsUrl } = vi.hoisted(() => ({ + isSafePublicHttpsUrl: vi.fn(async (_url: string) => true), +})); + +// The SSRF check is the gate uploadSimple runs before touching the network, +// so it is the seam that lets a remote upload be exercised at all. +vi.mock('@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator', () => ({ + isSafePublicHttpsUrl, +})); + +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; + +import { LocalStorage } from './local.storage'; + +/** A real 1x1 PNG, so file-type sniffs it rather than trusting a claimed mime. */ +const PNG = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64' +); +const GIF = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'); +const HTML = Buffer.from('', 'utf-8'); + +const dataUrl = (mime: string, buffer: Buffer) => + `data:${mime};base64,${buffer.toString('base64')}`; + +let directory: string; +let storage: LocalStorage; + +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), 'postiz-local-storage-')); + storage = new LocalStorage(directory); + vi.stubEnv('FRONTEND_URL', 'https://app.example.com'); + isSafePublicHttpsUrl.mockResolvedValue(true); +}); + +afterEach(() => { + rmSync(directory, { recursive: true, force: true }); +}); + +/** The public path the uploader returns, resolved back to a real file. */ +const onDisk = (returned: string) => + join(directory, returned.replace('https://app.example.com/uploads', '')); + +describe('LocalStorage.uploadSimple from a data url', () => { + it('writes the decoded bytes under a dated path', async () => { + const returned = await storage.uploadSimple(dataUrl('image/png', PNG)); + + // the name is 32 nibbles joined as hex, but Math.round(random * 16) can + // yield 16, which stringifies to "10", so the length is not fixed at 32 + expect(returned).toMatch( + /^https:\/\/app\.example\.com\/uploads\/\d{4}\/\d{2}\/\d{2}\/[0-9a-f]{32,64}\.png$/ + ); + expect(readFileSync(onDisk(returned))).toEqual(PNG); + }); + + it('sniffs the bytes rather than trusting the declared mime', async () => { + // an attacker declaring svg to get a scriptable extension still gets .png, + // because the extension comes from the sniffed type + const returned = await storage.uploadSimple(dataUrl('image/svg+xml', PNG)); + + expect(returned.endsWith('.png')).toBe(true); + }); + + it('refuses bytes that are not an allowed media type', async () => { + await expect( + storage.uploadSimple(dataUrl('image/png', HTML)) + ).rejects.toThrow(/Unsupported file type/); + }); + + it('writes nothing when the type is refused', async () => { + await storage.uploadSimple(dataUrl('image/png', HTML)).catch(() => undefined); + + const [year] = new Date().toISOString().split('-'); + expect(existsSync(join(directory, year))).toBe(false); + }); + + it('accepts every allowed image format', async () => { + const png = await storage.uploadSimple(dataUrl('image/png', PNG)); + const gif = await storage.uploadSimple(dataUrl('image/gif', GIF)); + + expect(png.endsWith('.png')).toBe(true); + expect(gif.endsWith('.gif')).toBe(true); + }); + + it('gives every upload its own name', async () => { + const first = await storage.uploadSimple(dataUrl('image/png', PNG)); + const second = await storage.uploadSimple(dataUrl('image/png', PNG)); + + expect(first).not.toBe(second); + }); + + it('never reaches the network for a data url', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await storage.uploadSimple(dataUrl('image/png', PNG)); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(isSafePublicHttpsUrl).not.toHaveBeenCalled(); + }); +}); + +describe('LocalStorage.uploadSimple from a remote url', () => { + it('refuses an address the ssrf guard rejects, before fetching', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + isSafePublicHttpsUrl.mockResolvedValue(false); + + await expect( + storage.uploadSimple('http://169.254.169.254/latest/meta-data') + ).rejects.toThrow(/Unsafe URL/); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('downloads and stores an allowed image', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(PNG)) + ); + + const returned = await storage.uploadSimple('https://cdn.example.test/a.png'); + + expect(readFileSync(onDisk(returned))).toEqual(PNG); + }); + + it('ignores the extension in the url and uses the sniffed type', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(GIF)) + ); + + const returned = await storage.uploadSimple( + 'https://cdn.example.test/looks-like.png' + ); + + expect(returned.endsWith('.gif')).toBe(true); + }); + + it('refuses a download whose bytes are not an allowed type', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(HTML)) + ); + + await expect( + storage.uploadSimple('https://cdn.example.test/a.png') + ).rejects.toThrow(/Unsupported file type/); + }); +}); + +describe('LocalStorage.uploadFile', () => { + it('stores the buffer and reports the sniffed type back', async () => { + const result = await storage.uploadFile({ + buffer: PNG, + originalname: 'whatever.svg', + } as never); + + expect(result).toMatchObject({ + filename: expect.stringMatching(/^[0-9a-f]{32,64}\.png$/), + mimetype: 'image/png', + path: expect.stringContaining('https://app.example.com/uploads/'), + }); + expect(readFileSync(onDisk(result.path))).toEqual(PNG); + }); + + it('renames the file rather than keeping what the client sent', async () => { + const result = await storage.uploadFile({ + buffer: PNG, + originalname: '../../escape.html', + } as never); + + expect(result.originalname).toBe(result.filename); + expect(result.filename).not.toContain('escape'); + expect(result.filename).not.toContain('..'); + }); + + it('refuses a buffer that is not an allowed media type', async () => { + await expect( + storage.uploadFile({ buffer: HTML, originalname: 'a.png' } as never) + ).rejects.toThrow(/Unsupported file type/); + }); +}); + +describe('LocalStorage.removeFile', () => { + it('deletes a file that exists', async () => { + const target = join(directory, 'delete-me.png'); + writeFileSync(target, PNG); + + await expect(storage.removeFile(target)).resolves.toBeUndefined(); + expect(existsSync(target)).toBe(false); + }); + + it('rejects when the file cannot be removed', async () => { + await expect( + storage.removeFile(join(directory, 'never-existed.png')) + ).rejects.toBeTruthy(); + }); +}); diff --git a/tests/integration/integrations.controller.int.spec.ts b/tests/integration/integrations.controller.int.spec.ts new file mode 100644 index 00000000..1a715aba --- /dev/null +++ b/tests/integration/integrations.controller.int.spec.ts @@ -0,0 +1,238 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; + +import { DatabaseModule } from '@gitroom/nestjs-libraries/database/prisma/database.module'; +import { IntegrationsController } from '@gitroom/backend/api/routes/integrations.controller'; +import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager'; +import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service'; +import { createTestApp } from '@gitroom/testing/nest/create.test.app'; +import { + createIntegration, + createOrgWithUser, +} from '@gitroom/testing/factories/organization.factory'; +import { + disconnectTestPrisma, + resetDatabase, + testPrisma, +} from '@gitroom/testing/prisma/test.database'; + +/** + * Channel management against real rows: what /list actually joins from the + * provider registry, and that disable, enable and delete change the database + * rather than only answering 200. Ownership matters most here - a channel id + * from another organization must never be touched. + */ +describe('IntegrationsController (integration)', () => { + let app: INestApplication; + let org: Awaited>; + let integrationId: string; + + beforeAll(async () => { + ({ app } = await createTestApp({ + imports: [DatabaseModule], + controllers: [IntegrationsController], + policies: false, + providers: [ + IntegrationManager, + // Refresh reaches the provider over the network; nothing under test + // triggers it. + { provide: RefreshIntegrationService, useValue: { refresh: async () => ({}) } }, + ], + middleware: [ + (req, _res, next) => { + req.org = org.organization; + req.user = org.user; + next(); + }, + ], + })); + }, 60_000); + + afterAll(async () => { + await app?.close(); + await disconnectTestPrisma(); + }); + + beforeEach(async () => { + await resetDatabase(); + org = await createOrgWithUser(); + integrationId = (await createIntegration(org.organization.id)).id; + }); + + describe('GET /integrations/list', () => { + it('describes the connected channel from the row and the provider registry', async () => { + const response = await request(app.getHttpServer()) + .get('/integrations/list') + .expect(200); + + expect(response.body.integrations).toHaveLength(1); + expect(response.body.integrations[0]).toMatchObject({ + id: integrationId, + name: 'Test Mastodon', + identifier: 'mastodon', + disabled: false, + refreshNeeded: false, + editor: expect.any(String), + }); + }); + + it('falls back to a placeholder picture', async () => { + const response = await request(app.getHttpServer()) + .get('/integrations/list') + .expect(200); + + expect(response.body.integrations[0].picture).toBe('/no-picture.jpg'); + }); + + it('parses the stored posting times rather than echoing the json', async () => { + const response = await request(app.getHttpServer()) + .get('/integrations/list') + .expect(200); + + expect(Array.isArray(response.body.integrations[0].time)).toBe(true); + }); + + it('never lists a channel belonging to another organization', async () => { + const other = await createOrgWithUser(); + await createIntegration(other.organization.id, { name: 'Not Mine' }); + + const response = await request(app.getHttpServer()) + .get('/integrations/list') + .expect(200); + + expect(response.body.integrations).toHaveLength(1); + expect(response.body.integrations[0].id).toBe(integrationId); + }); + + it('reports an organization with no channels as empty', async () => { + await testPrisma().integration.deleteMany({ + where: { organizationId: org.organization.id }, + }); + + const response = await request(app.getHttpServer()) + .get('/integrations/list') + .expect(200); + + expect(response.body.integrations).toEqual([]); + }); + }); + + describe('disable and enable', () => { + it('disables a channel in the database', async () => { + await request(app.getHttpServer()) + .post('/integrations/disable') + .send({ id: integrationId }) + .expect(201); + + const saved = await testPrisma().integration.findUniqueOrThrow({ + where: { id: integrationId }, + }); + expect(saved.disabled).toBe(true); + }); + + it('enables it again', async () => { + await testPrisma().integration.update({ + where: { id: integrationId }, + data: { disabled: true }, + }); + + await request(app.getHttpServer()) + .post('/integrations/enable') + .send({ id: integrationId }) + .expect(201); + + const saved = await testPrisma().integration.findUniqueOrThrow({ + where: { id: integrationId }, + }); + expect(saved.disabled).toBe(false); + }); + + // Isolation holds - the update is scoped by organizationId, so Prisma + // matches no row. It surfaces as an unclassified 500 rather than a 404, + // which is pinned here rather than endorsed. + it('leaves another organization channel untouched', async () => { + const other = await createOrgWithUser(); + const foreign = await createIntegration(other.organization.id); + + await request(app.getHttpServer()) + .post('/integrations/disable') + .send({ id: foreign.id }) + .expect(500); + + const saved = await testPrisma().integration.findUniqueOrThrow({ + where: { id: foreign.id }, + }); + expect(saved.disabled).toBe(false); + }); + }); + + describe('DELETE /integrations', () => { + it('removes the channel', async () => { + await request(app.getHttpServer()) + .delete('/integrations/') + .send({ id: integrationId }) + .expect(200); + + const saved = await testPrisma().integration.findUnique({ + where: { id: integrationId }, + }); + expect(saved?.deletedAt ?? null).not.toBeNull(); + }); + + it('refuses to delete a channel of another organization', async () => { + const other = await createOrgWithUser(); + const foreign = await createIntegration(other.organization.id); + + await request(app.getHttpServer()) + .delete('/integrations/') + .send({ id: foreign.id }) + .expect(500); + + const saved = await testPrisma().integration.findUniqueOrThrow({ + where: { id: foreign.id }, + }); + expect(saved.deletedAt).toBeNull(); + }); + }); + + describe('customer and nickname', () => { + it('assigns a customer and reads it back on the list', async () => { + await request(app.getHttpServer()) + .put(`/integrations/${integrationId}/customer-name`) + .send({ name: 'Acme Client' }) + .expect(200); + + const response = await request(app.getHttpServer()) + .get('/integrations/list') + .expect(200); + + expect(response.body.integrations[0].customer).toMatchObject({ + name: 'Acme Client', + }); + }); + + it('lists the customers of the organization', async () => { + await request(app.getHttpServer()) + .put(`/integrations/${integrationId}/customer-name`) + .send({ name: 'Acme Client' }) + .expect(200); + + const response = await request(app.getHttpServer()) + .get('/integrations/customers') + .expect(200); + + expect(JSON.stringify(response.body)).toContain('Acme Client'); + }); + }); + + describe('GET /integrations/plug/list', () => { + it('lists the plugs the registry exposes', async () => { + const response = await request(app.getHttpServer()) + .get('/integrations/plug/list') + .expect(200); + + expect(response.body).toHaveProperty('plugs'); + }); + }); +});