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 @@ -40,6 +40,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));

jest.mock('../../../models/Integration', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ jest.mock('../../../middleware/auth', () => (req, _res, next) => {
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));

jest.mock('../../../models/Integration', () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ jest.mock('../../../middleware/auth', () => (req, _res, next) => {
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));

// Secret storage and grant revocation are not this file's claim; the ROW is.
Expand Down
2 changes: 2 additions & 0 deletions backend/__tests__/unit/routes/hostedMcpConnect.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ jest.mock('../../../middleware/auth', () => (req, _res, next) => {
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));

jest.mock('../../../models/Integration', () => ({ findOne: jest.fn(), findOneAndUpdate: jest.fn() }));
Expand Down
2 changes: 2 additions & 0 deletions backend/__tests__/unit/routes/installables.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ jest.mock('../../../middleware/auth', () => (req, res, next) => {
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));

jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../models/User', () => ({ findById: jest.fn() }));
jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../services/dmService', () => ({ canViewPod: jest.fn(() => true) }));
jest.mock('jsonwebtoken', () => ({ sign: jest.fn(() => 't'), verify: jest.fn(), decode: jest.fn() }));
Expand Down
59 changes: 59 additions & 0 deletions backend/__tests__/unit/routes/integrations.ingest.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ jest.mock('../../../integrations', () => ({
get: jest.fn(() => ({ ingestEvent: jest.fn().mockResolvedValue([]) })),
}));

jest.mock('../../../models/User', () => ({ findById: jest.fn() }));
jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));

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

describe('integration ingest route', () => {
Expand All @@ -25,13 +30,16 @@ describe('integration ingest route', () => {

beforeEach(() => {
jest.clearAllMocks();
User.findById.mockResolvedValue({ _id: 'user-1', role: 'user' });
Pod.findById.mockResolvedValue(null);
});

it('ingests normalized messages into the buffer', async () => {
Integration.findById.mockReturnValue({
lean: () => ({
_id: 'integration-1',
type: 'slack',
createdBy: 'user-1',
config: { maxBufferSize: 200 },
}),
});
Expand Down Expand Up @@ -90,6 +98,7 @@ describe('integration ingest route', () => {
lean: () => ({
_id: 'integration-1',
type: 'slack',
createdBy: 'user-1',
config: {},
}),
});
Expand All @@ -104,4 +113,54 @@ describe('integration ingest route', () => {

expect(res.status).toBe(400);
});

// The session path is gated like the ingest-token mint: the integration's
// creator, the pod's creator while still a member, or an admin.
it('refuses a signed-in caller who could not mint an ingest token, and writes nothing', async () => {
Integration.findById.mockReturnValue({
lean: () => ({
_id: 'integration-1',
type: 'slack',
createdBy: 'someone-else',
podId: 'pod-1',
config: {},
}),
});
Pod.findById.mockResolvedValue({ createdBy: 'someone-else', members: ['someone-else', 'user-1'] });

const res = await request(app)
.post('/api/integrations/ingest')
.send({
provider: 'slack',
integrationId: 'integration-1',
messages: [{
externalId: 'm1', authorId: 'u1', authorName: 'Mallory', content: 'hi', timestamp: new Date().toISOString(),
}],
});

expect(res.status).toBe(403);
expect(Integration.findByIdAndUpdate).not.toHaveBeenCalled();
});

it('lets an admin session ingest into an integration it did not create', async () => {
User.findById.mockResolvedValue({ _id: 'user-1', role: 'admin' });
Integration.findById.mockReturnValue({
lean: () => ({
_id: 'integration-1', type: 'slack', createdBy: 'someone-else', config: {},
}),
});

const res = await request(app)
.post('/api/integrations/ingest')
.send({
provider: 'slack',
integrationId: 'integration-1',
messages: [{
externalId: 'm1', authorId: 'u1', authorName: 'Ops', content: 'hi', timestamp: new Date().toISOString(),
}],
});

expect(res.status).toBe(200);
expect(Integration.findByIdAndUpdate).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
jest.mock('../../../models/User', () => ({ findById: jest.fn() }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../services/dmService', () => ({ canViewPod: jest.fn() }));
jest.mock('jsonwebtoken', () => ({ sign: jest.fn(() => 't'), verify: jest.fn(), decode: jest.fn() }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../services/dmService', () => ({ canViewPod: jest.fn(async () => true) }));
jest.mock('../../../services/discordService', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../services/dmService', () => ({ canViewPod: jest.fn() }));
jest.mock('jsonwebtoken', () => ({ sign: jest.fn(() => 't'), verify: jest.fn(), decode: jest.fn() }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ jest.mock('../../../middleware/adminAuth', () => (req, res, next) => next());
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
jest.mock('../../../models/User', () => ({ findById: jest.fn() }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,6 @@
"routes/health.ts GET /db [unlimited]",
"routes/health.ts GET /live [unlimited]",
"routes/health.ts GET /ready [unlimited]",
"routes/integrations.ts DELETE /:id/ingest-tokens/:tokenId [unlimited]",
"routes/integrations.ts GET /:id/ingest-tokens [unlimited]",
"routes/integrations.ts GET /:id/messages [unlimited]",
"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/ingest-tokens [unlimited]",
"routes/integrations.ts POST /:id/send [unlimited]",
"routes/integrations.ts POST /ingest [unlimited]",
"routes/marketplace-api.ts DELETE /manifests/:installableId(*) [unlimited]",
"routes/marketplace-api.ts DELETE /publish/:installableId(*) [unlimited]",
"routes/marketplace-api.ts GET /mine [unlimited]",
Expand Down
2 changes: 2 additions & 0 deletions backend/__tests__/unit/routes/slackOAuth.installables.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ jest.mock('../../../middleware/auth', () => (req, res, next) => {
jest.mock('../../../middleware/integrationRateLimit', () => ({
writeIntegrationsRateLimit: (_req, _res, next) => next(),
listIntegrationsRateLimit: (_req, _res, next) => next(),
ingestIngressRateLimit: (_req, _res, next) => next(),
ingestIntegrationsRateLimit: (_req, _res, next) => next(),
}));
jest.mock('../../../models/Pod', () => ({ findById: jest.fn() }));
jest.mock('../../../models/User', () => ({ findById: jest.fn() }));
Expand Down
40 changes: 40 additions & 0 deletions backend/middleware/integrationRateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,48 @@ export const listIntegrationsRateLimit = rateLimit({
},
});

// `POST /ingest` is the provider-service push path. Its credential may also
// arrive as `x-commonly-integration-token` (routes/integrations.ts
// extractToken), which the shared key does not read, so that form would
// otherwise fall back to the caller's address bucket.
export const ingestRateLimitKey = (req: RateLimitRequest): string => {
const ingestToken = req.get?.('x-commonly-integration-token');
if (ingestToken) {
return `int:${createHash('sha256').update(ingestToken).digest('hex').slice(0, 16)}`;
}
return integrationsRateLimitKey(req);
};

// The key above is taken before the token is checked, so a caller rotating
// junk credentials gets a fresh bucket per request. This address ceiling sits
// in front of it and bounds that, at a budget a provider service will not hit.
export const ingestIngressRateLimit = rateLimit({
windowMs: 60_000,
max: 1200,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req: RateLimitRequest) => cloudflareIpRateLimitKeyGenerator(req as unknown as Request),
handler: (_req: unknown, res: { status: (n: number) => { json: (body: unknown) => void } }) => {
res.status(429).json({ msg: 'rate limit exceeded: 1200 ingest requests per 60s' });
},
});

export const ingestIntegrationsRateLimit = rateLimit({
windowMs: 60_000,
max: 300,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: ingestRateLimitKey,
handler: (_req: unknown, res: { status: (n: number) => { json: (body: unknown) => void } }) => {
res.status(429).json({ msg: 'rate limit exceeded: 300 ingest requests per 60s' });
},
});

module.exports = {
integrationsRateLimitKey,
ingestRateLimitKey,
writeIntegrationsRateLimit,
listIntegrationsRateLimit,
ingestIngressRateLimit,
ingestIntegrationsRateLimit,
};
26 changes: 17 additions & 9 deletions backend/routes/integrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ import {
import {
writeIntegrationsRateLimit,
listIntegrationsRateLimit,
ingestIngressRateLimit,
ingestIntegrationsRateLimit,
} from '../middleware/integrationRateLimit';

// The list lives in `utils/serverOwnedConfigKeys.ts` so the manifest contract
Expand Down Expand Up @@ -226,7 +228,7 @@ const ingestAuth = async (req: AuthReq, res: Res, next: () => void) => {
return auth(req, res, next);
};

router.get('/catalog', auth, async (req: AuthReq, res: Res) => {
router.get('/catalog', listIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const entries = await buildCatalogEntries({ userId: req.user?.id });
res.json({ entries });
Expand Down Expand Up @@ -317,14 +319,20 @@ router.delete('/github-app/:id/gig-pod', writeIntegrationsRateLimit, auth, admin
return res.status(204).json({});
});

router.post('/ingest', ingestAuth, async (req: AuthReq, res: Res) => {
router.post('/ingest', ingestIngressRateLimit, ingestIntegrationsRateLimit, ingestAuth, async (req: AuthReq, res: Res) => {
try {
const { provider, integrationId, event, messages } = (req.body || {}) as { provider?: string; integrationId?: string; event?: unknown; messages?: unknown[] };
const { integration: tokenIntegration } = req;
let integration = tokenIntegration as Record<string, unknown> | null | undefined;
if (!integrationId && !integration) return res.status(400).json({ message: 'integrationId is required' });
if (!integration) integration = await Integration.findById(integrationId).lean();
if (!integration) return res.status(404).json({ message: 'Integration not found' });
// A signed-in session (not a cm_int_ token) may push only where it could
// mint an ingest token: the mint route's own gate, so this path grants
// nothing the mint does not. The buffer feeds summaries and agent context.
if (!req.integrationAuth && !await canDeleteIntegration(integration, req.user?.id || '')) {
return res.status(403).json({ message: 'Not authorized' });
}
if (integrationId && (integration._id as { toString: () => string }).toString() !== integrationId.toString()) return res.status(400).json({ message: 'integrationId does not match token' });
const providerName = provider || (integration.type as string);
if (providerName !== integration.type) return res.status(400).json({ message: 'Provider does not match integration type' });
Expand All @@ -350,7 +358,7 @@ router.post('/ingest', ingestAuth, async (req: AuthReq, res: Res) => {
}
});

router.post('/:id/ingest-tokens', auth, async (req: AuthReq, res: Res) => {
router.post('/:id/ingest-tokens', writeIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const { id } = req.params || {};
const { label } = (req.body || {}) as { label?: string };
Expand All @@ -370,7 +378,7 @@ router.post('/:id/ingest-tokens', auth, async (req: AuthReq, res: Res) => {
}
});

router.get('/:id/ingest-tokens', auth, async (req: AuthReq, res: Res) => {
router.get('/:id/ingest-tokens', listIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const { id } = req.params || {};
const integration = await Integration.findById(id) as { createdBy?: { toString: () => string }; podId?: unknown; ingestTokens?: Array<{ _id: { toString: () => string }; label?: string; createdAt?: Date; lastUsedAt?: Date; createdBy?: unknown }> } | null;
Expand All @@ -385,7 +393,7 @@ router.get('/:id/ingest-tokens', auth, async (req: AuthReq, res: Res) => {
}
});

router.delete('/:id/ingest-tokens/:tokenId', auth, async (req: AuthReq, res: Res) => {
router.delete('/:id/ingest-tokens/:tokenId', writeIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const { id, tokenId } = req.params || {};
const integration = await Integration.findById(id) as { createdBy?: { toString: () => string }; podId?: unknown; ingestTokens?: Array<{ _id: { toString: () => string } }>; save: () => Promise<void> } | null;
Expand Down Expand Up @@ -591,7 +599,7 @@ router.post('/:id/disconnect', writeIntegrationsRateLimit, auth, async (req: Aut
}
});

router.get('/:id/stats', auth, async (req: AuthReq, res: Res) => {
router.get('/:id/stats', listIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const { id } = req.params || {};
const integration = await Integration.findById(id) as { type?: string; podId?: unknown } | null;
Expand All @@ -610,7 +618,7 @@ router.get('/:id/stats', auth, async (req: AuthReq, res: Res) => {
}
});

router.get('/:id/messages', auth, async (req: AuthReq, res: Res) => {
router.get('/:id/messages', listIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const { id } = req.params || {};
const { limit, before } = req.query || {};
Expand All @@ -632,7 +640,7 @@ router.get('/:id/messages', auth, async (req: AuthReq, res: Res) => {
}
});

router.post('/:id/send', auth, async (req: AuthReq, res: Res) => {
router.post('/:id/send', writeIntegrationsRateLimit, auth, async (req: AuthReq, res: Res) => {
try {
const { id } = req.params || {};
const { message } = (req.body || {}) as { message?: string };
Expand All @@ -654,7 +662,7 @@ router.post('/:id/send', auth, async (req: AuthReq, res: Res) => {
}
});

router.get('/admin/all', auth, adminAuth, async (_req: AuthReq, res: Res) => {
router.get('/admin/all', listIntegrationsRateLimit, auth, adminAuth, async (_req: AuthReq, res: Res) => {
try {
const integrations = await Integration.find({ isActive: true }).populate('podId', 'name type createdBy').populate('createdBy', 'username email').populate('platformIntegration').sort({ createdAt: -1 });
// The connect code is a member's one-time enable code; the admin list has no reader for it.
Expand Down
Loading