Skip to content
Closed
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
20 changes: 20 additions & 0 deletions backend/__tests__/unit/routes/grants.mint.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@ jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
jest.mock('../../../models/Integration', () => ({ findById: jest.fn(), findOne: jest.fn() }));
jest.mock('../../../models/Installable', () => ({ findOne: jest.fn() }));
jest.mock('../../../services/githubAppService', () => ({}));
jest.mock('../../../services/connectorEventService', () => ({
emitConnectorsChanged: jest.fn(),
emitConnectorsChangedFor: jest.fn(),
}));
jest.mock('../../../models/ToolCall', () => ({ __esModule: true, default: {}, digestArgs: jest.fn(), reserveBudgetLineage: jest.fn() }));

const Pod = require('../../../models/Pod');
const Integration = require('../../../models/Integration');
const Installable = require('../../../models/Installable');
const { emitConnectorsChanged } = require('../../../services/connectorEventService');
const { buildGithubToolInstallable, GRANT_BROKER_ID } = require('../../../services/installable/toolInstallables');

const POD = 'aaaaaaaaaaaaaaaaaaaaaa01';
Expand Down Expand Up @@ -79,6 +84,21 @@ beforeEach(async () => {
});

describe('POST /api/grants', () => {
test('TASK-135: the mint invalidates the granter\u2019s other clients, in the user room', async () => {
const res = await mint({});
expect(res.status).toBe(201);

// The page that must re-read is this user's other tab, not the pod: a pod
// fan-out would reach members who cannot see the row.
expect(emitConnectorsChanged).toHaveBeenCalledWith(OWNER, 'grant-created');
});

test('TASK-135: a refused mint emits nothing', async () => {
const res = await mint({ tools: ['github.delete_repo'] });
expect(res.status).toBe(400);
expect(emitConnectorsChanged).not.toHaveBeenCalled();
});

test('brokerId comes from the tool Installable, never the body', async () => {
const res = await mint({});
expect(res.status).toBe(201);
Expand Down
35 changes: 35 additions & 0 deletions backend/__tests__/unit/routes/grants.read.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,15 @@ jest.mock('../../../controllers/podController', () => ({
jest.mock('../../../services/dmService', () => ({
canViewPod: jest.fn(async (userId, pod) => (pod.members || []).map(String).includes(String(userId))),
}));
jest.mock('../../../services/connectorEventService', () => ({
emitConnectorsChanged: jest.fn(),
emitConnectorsChangedFor: jest.fn(),
}));

const Pod = require('../../../models/Pod');
const Integration = require('../../../models/Integration');
const ToolCall = require('../../../models/ToolCall');
const { emitConnectorsChanged } = require('../../../services/connectorEventService');

const POD = 'aaaaaaaaaaaaaaaaaaaaaa01';
const OWNER = 'bbbbbbbbbbbbbbbbbbbbbb01'; // installed the App: every grant's granter
Expand Down Expand Up @@ -257,7 +262,37 @@ describe('GET /api/grants/:grantId', () => {
});
});

describe('POST /api/grants/:grantId/attenuate', () => {
test('TASK-135: the invalidation targets the connection owner, not the agent caller', async () => {
const row = await RoomGrant.create(grant({ audience: [SEAT] }));

const res = await request(app)
.post(`/api/grants/${row.grantId}/attenuate`)
.set('x-test-agent', SEAT)
.send({ tools: ['github.list_issues'] });

expect(res.status).toBe(201);
// The caller here is an AGENT, which has no Connectors page; the stale row
// lives in the connection owner's browser. This is the only path where the
// two ids differ, so it is the only place the distinction can rot: rewiring
// the emit to the caller leaves the owner's tab stale again and every other
// assertion in this file still passes (sprint-review on #1751).
expect(emitConnectorsChanged).toHaveBeenCalledWith(OWNER, 'grant-attenuated');
expect(emitConnectorsChanged).not.toHaveBeenCalledWith(SEAT, 'grant-attenuated');
});
});

describe('POST /api/grants/:grantId/revoke', () => {
test('TASK-135: the revoke invalidates the granter\u2019s other clients', async () => {
const row = await RoomGrant.create(grant());
const res = await request(app).post(`/api/grants/${row.grantId}/revoke`).set('x-test-user', OWNER);
expect(res.status).toBe(200);

// eslint-disable-next-line global-require
const { emitConnectorsChanged } = require('../../../services/connectorEventService');
expect(emitConnectorsChanged).toHaveBeenCalledWith(OWNER, 'grant-revoked');
});

test('records the authenticated caller as revokedBy', async () => {
const row = await RoomGrant.create(grant());
const res = await request(app).post(`/api/grants/${row.grantId}/revoke`).set('x-test-user', OWNER);
Expand Down
37 changes: 37 additions & 0 deletions backend/__tests__/unit/routes/integrations.linkedUserId.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ jest.mock('../../../models/DiscordIntegration', () => function DiscordIntegratio
this.save = jest.fn().mockResolvedValue(this);
});
jest.mock('../../../services/discordService', () => jest.fn());
jest.mock('../../../services/connectorEventService', () => ({
emitConnectorsChanged: jest.fn(),
emitConnectorsChangedFor: jest.fn(),
}));
jest.mock('../../../models/Integration', () => {
function Integration(data) {
Object.assign(this, data);
Expand All @@ -38,6 +42,10 @@ jest.mock('../../../models/Integration', () => {
const Integration = require('../../../models/Integration');
const User = require('../../../models/User');
const Pod = require('../../../models/Pod');
const {
emitConnectorsChanged,
emitConnectorsChangedFor,
} = require('../../../services/connectorEventService');
const integrationRoutes = require('../../../routes/integrations');

const app = express();
Expand Down Expand Up @@ -99,6 +107,35 @@ describe('PATCH /api/integrations/:id — linkedUserId guard', () => {
expect(update['config.linkedUserId']).toBe('user-1');
});

it('TASK-135: a PATCH invalidates this user\u2019s other Connectors clients', async () => {
const res = await request(app)
.patch(`/api/integrations/${integrationId}`)
.send({ config: { liveRelay: true } });

expect(res.status).toBe(200);
// The actor is the row's creator here, so one event covers both.
expect(emitConnectorsChangedFor).toHaveBeenCalledWith(expect.anything(), 'integration-updated');
expect(emitConnectorsChanged).not.toHaveBeenCalled();
});

it('TASK-135: a pod creator acting on someone else\u2019s connector invalidates the author too', async () => {
// canDeleteIntegration admits the pod's creator, who may not have created
// this connector — without the second emit that author's tabs stay stale.
Integration.findById.mockResolvedValue({ ...telegramIntegration(), createdBy: { toString: () => 'other-user' } });
Pod.findById.mockResolvedValue({ createdBy: { toString: () => 'user-1' } });

const res = await request(app)
.patch(`/api/integrations/${integrationId}`)
.send({ config: { liveRelay: true } });

expect(res.status).toBe(200);
// The route passes the document's ObjectId; stringifying into the room name
// is the service's contract (pinned in connectorEventService.test.js).
const [authorId, reason] = emitConnectorsChanged.mock.calls[0];
expect(String(authorId)).toBe('other-user');
expect(reason).toBe('integration-updated');
});

it("derives linkedUserId when liveRelay arrives as the string 'true' (#1293)", async () => {
const res = await request(app)
.patch(`/api/integrations/${integrationId}`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,6 @@
"routes/integrations.ts GET /:id/stats [unlimited]",
"routes/integrations.ts GET /admin/all [unlimited]",
"routes/integrations.ts GET /catalog [unlimited]",
"routes/integrations.ts POST /:id/connect [unlimited]",
"routes/integrations.ts POST /:id/disconnect [unlimited]",
"routes/integrations.ts POST /:id/ingest-tokens [unlimited]",
"routes/integrations.ts POST /:id/send [unlimited]",
"routes/integrations.ts POST /ingest [unlimited]",
Expand Down
161 changes: 161 additions & 0 deletions backend/__tests__/unit/services/connectorEventService.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/**
* TASK-135 — the user-scoped invalidation that lets a VISIBLE Connectors tab
* re-read when another client of the same user changes something.
*
* The properties that matter are the ones a wrong version fails silently on:
* an event sent to the wrong room reaches nobody (or everyone), a payload with
* the wrong shape still emits, and an unbound socket.io must be a no-op rather
* than a throw from inside a route that already committed its write. So this
* pins the room, the event name, the payload, and the three no-op paths —
* without needing a server.
*/
const {
bindSocketIO,
emitConnectorsChanged,
emitConnectorsChangedFor,
joinUserRoom,
userRoom,
CONNECTORS_UPDATED_EVENT,
} = require('../../../services/connectorEventService');

const USER = 'bbbbbbbbbbbbbbbbbbbbbb01';
const OTHER = 'cccccccccccccccccccccc01';

const makeIo = () => {
const emitted = [];
return {
emitted,
io: {
to: (room) => ({ emit: (event, payload) => emitted.push({ room, event, payload }) }),
},
};
};

describe('connectorEventService', () => {
test('emits into the user room, not a pod room', () => {
const { emitted, io } = makeIo();
bindSocketIO(io);

emitConnectorsChanged(USER, 'grant-created');

expect(emitted).toHaveLength(1);
expect(emitted[0].room).toBe(`user_${USER}`);
expect(emitted[0].event).toBe(CONNECTORS_UPDATED_EVENT);
expect(emitted[0].payload).toEqual({ userId: USER, reason: 'grant-created' });
// A pod room would reach members who cannot read the row; that is the
// mistake this event exists to avoid.
expect(emitted[0].room).not.toContain('pod_');
});

test('an ObjectId user id is stringified, so the room matches the joined one', () => {
const { emitted, io } = makeIo();
bindSocketIO(io);
const objectId = { toString: () => USER };

emitConnectorsChanged(objectId, 'integration-updated');

expect(emitted[0].room).toBe(`user_${USER}`);
expect(emitted[0].payload.userId).toBe(USER);
});

test('no user id and no bound socket are both silent no-ops', () => {
const { emitted, io } = makeIo();
bindSocketIO(io);

emitConnectorsChanged(undefined, 'integration-deleted');
emitConnectorsChanged(null, 'integration-deleted');
emitConnectorsChanged('', 'integration-deleted');
expect(emitted).toHaveLength(0);
});

test('an unbound socket.io does not throw', () => {
// Re-require in a fresh registry so `ioRef` is null, the state every test
// run and every script path starts in.
jest.resetModules();
// eslint-disable-next-line global-require
const fresh = require('../../../services/connectorEventService');
expect(() => fresh.emitConnectorsChanged(USER, 'grant-revoked')).not.toThrow();
});

test('a throwing transport is swallowed: the write already committed', () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
bindSocketIO({
to: () => ({
emit: () => { throw new Error('transport down'); },
}),
});

expect(() => emitConnectorsChanged(USER, 'grant-created')).not.toThrow();
expect(warn).toHaveBeenCalled();
warn.mockRestore();
});

describe('emitConnectorsChangedFor reads the id wherever the auth path put it', () => {
// The three shapes are not interchangeable: the JWT middleware sets
// `req.userId`, the populated shapes use `req.user.id` / `req.user._id`,
// and the agent runtime token sets `req.agentUser._id`. A helper that
// reads only one emits to nobody while the route returns 201.
test.each([
['req.userId', { userId: USER }],
['req.user.id', { user: { id: USER } }],
['req.user._id', { user: { _id: USER } }],
['req.agentUser._id', { agentUser: { _id: USER } }],
])('%s', (_label, req) => {
const { emitted, io } = makeIo();
bindSocketIO(io);

emitConnectorsChangedFor(req, 'grant-created');

expect(emitted).toHaveLength(1);
expect(emitted[0].room).toBe(`user_${USER}`);
});

test('an empty request emits nothing rather than a user_undefined room', () => {
const { emitted, io } = makeIo();
bindSocketIO(io);

emitConnectorsChangedFor({}, 'grant-created');
emitConnectorsChangedFor(null, 'grant-created');
emitConnectorsChangedFor(undefined, 'grant-created');

expect(emitted).toHaveLength(0);
});

test('userId wins over a populated user, matching the routes’ own derivation', () => {
const { emitted, io } = makeIo();
bindSocketIO(io);

emitConnectorsChangedFor({ userId: USER, user: { id: OTHER } }, 'grant-created');

expect(emitted[0].room).toBe(`user_${USER}`);
});
});

test('userRoom is the single spelling of the room name', () => {
expect(userRoom(USER)).toBe(`user_${USER}`);
});

describe('joinUserRoom', () => {
// server.ts is not importable in a test, so the join itself is pinned here.
// A missing join is the silent failure this whole event exists to avoid:
// every emit still succeeds and reaches an empty room.
test('joins the socket to its own user room', () => {
const joined = [];

joinUserRoom({ userId: USER, join: (room) => joined.push(room) });

expect(joined).toEqual([`user_${USER}`]);
});

test('an unauthenticated socket joins nothing', () => {
const joined = [];
const socket = { join: (room) => joined.push(room) };

joinUserRoom(socket);
joinUserRoom({ ...socket, userId: null });
joinUserRoom({ ...socket, userId: '' });

expect(joined).toEqual([]);
});
});
});
11 changes: 11 additions & 0 deletions backend/routes/grants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
RoomGrantError,
} from '../services/roomGrantService';
import type { RoomGrantCreateInput } from '../services/roomGrantService';
import { emitConnectorsChanged } from '../services/connectorEventService';
import { resolveBrokerFor } from '../services/installable/toolInstallables';
import { grantBrokerRefusal } from '../services/grantBrokerConfinement';
import type { GrantBrokerRefusal } from '../services/grantBrokerConfinement';
Expand Down Expand Up @@ -335,6 +336,9 @@ router.post('/', grantRateLimit, auth, async (req: AuthenticatedRequest, res: ex
brokerId: broker.brokerId,
};
const grant = await createGrant(grantInput);
// The Connectors page lists this grant; every other tab this user has open
// re-reads rather than waiting for a tab switch (TASK-135).
emitConnectorsChanged(userId, 'grant-created');
return res.status(201).json(grant);
} catch (error) {
return handleError(res, error);
Expand Down Expand Up @@ -369,6 +373,12 @@ router.post(
audience: body.audience as string[] | undefined,
expiresAt: body.expiresAt as string | undefined,
});
// Attenuation is agent-initiated, so the socket to invalidate is the
// connection owner's, not the caller's: an agent has no Connectors page.
// One lookup on an agent-only path, and a failure here must not fail the
// mint that already happened.
const connection = await findConnection(parent.connectionId).catch(() => null);
emitConnectorsChanged(connectionOwnerId(connection), 'grant-attenuated');
return res.status(201).json(child);
} catch (error) {
return handleError(res, error);
Expand All @@ -386,6 +396,7 @@ const revokeHandler = async (req: AuthenticatedRequest, res: express.Response):
return res.status(403).json({ error: 'access_denied' });
}
const revoked = await revokeGrant(grant.grantId, userId);
emitConnectorsChanged(userId, 'grant-revoked');
return res.json({ grantId: grant.grantId, revoked });
} catch (error) {
return handleError(res, error);
Expand Down
Loading
Loading