Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@
// SlowBuffer dependency is irrelevant to these suites.
jest.mock('jsonwebtoken', () => ({}));

// The catalogue is empty on this head, so a hosted removal reaches the sequence
// but never a real entry. `findHostedMcpEntry` is the one seam the sequence
// reads, and a page entry has to be reachable through the ROUTE for the
// response's `revokeAt` to have a witness at all — nothing else asserts that
// the route passes it on. Setting the override is the only arm that does.
let mockHostedEntryOverride = null;
jest.mock('../../../integrations/hostedMcp/entries', () => {
const actual = jest.requireActual('../../../integrations/hostedMcp/entries');
return {
...actual,
findHostedMcpEntry: (entries, id) => mockHostedEntryOverride
|| actual.findHostedMcpEntry(entries, id),
};
});

const express = require('express');
const request = require('supertest');
const { MongoMemoryServer } = require('mongodb-memory-server');
Expand Down Expand Up @@ -220,3 +235,117 @@ describe('DELETE /api/integrations/:id ends the connection\'s grants first', ()
expect(row.revokedAt).toBeNull();
});
});

// TASK-172 §10 step 6 — the same route, over a hosted-MCP row. A hosted row is
// the only type whose removal has a provider step, so it takes the whole §9
// sequence rather than the grants-then-delete path the arms above pin.
describe('DELETE /api/integrations/:id over a hosted-MCP row', () => {
// §2: a hosted row is a per-person Connection, so `scope: 'user'` and no
// `podId` — the schema requires `podId` only when `scope === 'pod'`, which is
// also what keeps pod deletion from ever reaching one of these rows.
const seedHostedRow = async () => Integration.create({
type: 'hosted-mcp',
status: 'connected',
scope: 'user',
createdBy: OWNER,
isActive: true,
config: {
entryId: 'linear',
credentialRef: 'access-ref',
refreshTokenRef: 'refresh-ref',
},
});

it('refuses with provider_revoke_failed and keeps the row, its refs and its grants state', async () => {
const connection = await seedHostedRow();
const root = grantFixture({
connectionId: String(connection._id),
installationId: 'install-none-hosted',
});
await RoomGrant.create(root);

const res = await request(app)
.delete(`/api/integrations/${connection._id}`)
.set('x-test-user', OWNER);

// `HOSTED_MCP_ENTRIES` is empty on this head, so every hosted removal takes
// the "no known entry" branch. That is the shipped state, and it is worth an
// arm of its own: it proves the route dispatches to the sequence rather than
// falling through to the delete, and that a removal which cannot finish
// answers a named state instead of a 500 or a silent success.
expect(res.status).toBe(502);
expect(res.body.code).toBe('provider_revoke_failed');
expect(res.body.message).toMatch(/names no known entry/);

const row = await Integration.findById(connection._id).lean();
expect(row).not.toBeNull();
// Step 2 ran before the entry lookup, so the row the broker would still
// honour is refused from the instant of the failed attempt.
expect(row.status).toBe('disconnected');
expect(row.revokedAt).toBeInstanceOf(Date);
// The material is untouched, which is what makes the retry possible: the
// refresh token the vendor revoke needs is still there.
expect(row.config.credentialRef).toBe('access-ref');
expect(row.config.refreshTokenRef).toBe('refresh-ref');
// And the row is not active-flagged off, or the orphan sweep would take the
// material out from under the retry.
expect(row.isActive).toBe(true);

const grant = await RoomGrant.findOne({ grantId: root.grantId }).lean();
expect(grant.revokedAt).toBeInstanceOf(Date);
});

it('carries a page entry back as revokeAt and completes the removal', async () => {
const page = 'https://linear.app/settings/security';
mockHostedEntryOverride = {
id: 'linear',
title: 'Linear',
resource: 'https://mcp.linear.app/mcp',
issuer: 'https://mcp.linear.app',
client: 'cimd',
scopes: ['read'],
revoke: { page },
tools: [],
};
try {
// Real secret-id-shaped refs: the page path completes the removal, so
// unlike the refusal arm above it reaches `material` — and a real
// `ConnectorSecret.deleteOne` on a non-ObjectId ref is a CastError, not a
// no-op. The refs are what the sequence must destroy, so they have to be
// the shape the sequence is handed in production.
const connection = await Integration.create({
type: 'hosted-mcp',
status: 'connected',
scope: 'user',
createdBy: OWNER,
isActive: true,
config: {
entryId: 'linear',
credentialRef: new mongoose.Types.ObjectId().toString(),
refreshTokenRef: new mongoose.Types.ObjectId().toString(),
},
});
const root = grantFixture({
connectionId: String(connection._id),
installationId: 'install-page-hosted',
});
await RoomGrant.create(root);

const res = await request(app)
.delete(`/api/integrations/${connection._id}`)
.set('x-test-user', OWNER);

// §10.5: a page entry calls no vendor, so the removal completes — and the
// response has to name the page a person finishes at, or the last step of
// the removal is a URL only the entry knows.
expect(res.status).toBe(200);
expect(res.body.revokeAt).toBe(page);
expect(await Integration.findById(connection._id).lean()).toBeNull();
const grant = await RoomGrant.findOne({ grantId: root.grantId }).lean();
expect(grant.revokedAt).toBeInstanceOf(Date);
} finally {
// A leaked override would silently rewrite every arm that follows.
mockHostedEntryOverride = null;
}
});
});
107 changes: 107 additions & 0 deletions backend/__tests__/unit/routes/integrations.serverOwnedConfig.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// PATCH /api/integrations/:id — bridge attribution guard.
// config.linkedUserId is the identity every inbound live-relay message is
// AUTHORED as (pod row, socket payload, agent wake). The route derives it from
// the authenticated caller when liveRelay flips on and rejects any
// client-supplied value: without this, any caller passing canDeleteIntegration
// could name someone else as the bridge author (sprint-review on #1290).
const request = require('supertest');
const express = require('express');

jest.mock('../../../middleware/auth', () => (req, res, next) => {
req.user = { id: req.header('x-test-user') || 'user-1' };
next();
});
jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
jest.mock('../../../models/User', () => ({ findById: jest.fn() }));
jest.mock('../../../models/DiscordIntegration', () => function DiscordIntegration(data) {
Object.assign(this, data);
this.save = jest.fn().mockResolvedValue(this);
});
jest.mock('../../../services/discordService', () => jest.fn());
jest.mock('../../../models/Integration', () => {
function Integration(data) {
Object.assign(this, data);
this._id = this._id || 'integration-new';
this.save = jest.fn().mockResolvedValue(this);
}
Integration.findById = jest.fn();
Integration.findByIdAndUpdate = jest.fn();
Integration.aggregate = jest.fn().mockResolvedValue([]);
return Integration;
});

const Integration = require('../../../models/Integration');
const User = require('../../../models/User');
const Pod = require('../../../models/Pod');
const integrationRoutes = require('../../../routes/integrations');

const app = express();
app.use(express.json());
app.use('/api/integrations', integrationRoutes);

const integrationId = '64b64c1f7e5b8f0a12345674';

// The PATCH body reaches the write loop as `relay.next`, and every key of that
// object becomes a `config.<key>` update (integrations.ts:748-757). So what a
// caller may WRITE is decided by `stripServerOwnedConfig`, not by the loop: the
// loop persists every key it is given, and it is never given a server-owned one.
//
// Two mechanisms protect these keys and they are not interchangeable. A key with
// an explicit refusal in the route (`linkedUserId`, `botToken`) is refused with a
// 4xx; every other server-owned key is silently removed from the body, which is
// what makes `providerRevokedAt` unwritable — the mark the removal sequence
// treats as proof that a provider revoke TAKES, and whose forgery would let a
// row claim a revoke that never happened.
const telegramIntegration = () => ({
_id: 'integration-1',
type: 'telegram',
podId: 'pod-1',
createdBy: { toString: () => 'user-1' },
config: {
chatId: '42',
chatType: 'private',
toObject() { return { chatId: '42', chatType: 'private' }; },
},
});

describe('PATCH /api/integrations/:id — server-owned config keys are not writable', () => {
beforeEach(() => {
jest.clearAllMocks();
User.findById.mockResolvedValue({ _id: 'user-1', role: 'member' });
Pod.findById.mockResolvedValue(null);
Integration.findById.mockResolvedValue(telegramIntegration());
Integration.findByIdAndUpdate.mockResolvedValue({ _id: 'integration-1' });
});

it('does not write a supplied mark, while writing the fields beside it', async () => {
const res = await request(app)
.patch(`/api/integrations/${integrationId}`)
// `liveRelay` is NOT server-owned, so it is the acceptance control: it
// proves the loop ran, which is what makes the mark's absence evidence
// about the strip rather than about a request that never reached a write.
// (`chatId` would have been the wrong control — it is on the list too.)
.send({ config: { providerRevokedAt: '2026-09-30T00:00:00.000Z', liveRelay: false } });

expect(res.status).toBe(200);
const [, update] = Integration.findByIdAndUpdate.mock.calls[0];
// The write happened, so the absence below is the strip and not a refusal.
expect(update['config.liveRelay']).toBe(false);
expect(Object.keys(update)).not.toContain('config.providerRevokedAt');
expect(Object.values(update)).not.toContain('2026-09-30T00:00:00.000Z');
});

it('refuses a supplied linkedUserId outright — the other mechanism', async () => {
const res = await request(app)
.patch(`/api/integrations/${integrationId}`)
.send({ config: { providerRevokedAt: '2026-09-30T00:00:00.000Z', linkedUserId: 'VICTIM-USER-ID' } });

expect(res.status).toBe(400);
expect(res.body.message).toMatch(/linkedUserId is derived from the authenticated caller/);
expect(Integration.findByIdAndUpdate).not.toHaveBeenCalled();
});
});
Loading
Loading