Skip to content
Draft
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
5 changes: 3 additions & 2 deletions src/backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,10 @@ app.use('/agent', agentRouter);
// The MCP endpoint, authenticated with the same per-user API tokens. JSON-RPC requires POST, so it
// cannot sit behind the readOnlyGuard the /agent router uses and is mounted separately. Its tools are
// registered per domain in src/mcp; tools that change data use registerWriteTool, and the services
// they call do the permission checks.
// they call do the permission checks. getCurrentCar runs after requireApiToken, since it needs the
// organization, and scopes car specific tools to the carid header the same way the app does.
// The handler is async, so its rejections are forwarded to the error handler rather than dropped.
app.all('/mcp', requireApiToken, attachAuthInfo, (req, res, next) => {
app.all('/mcp', requireApiToken, getCurrentCar, attachAuthInfo, (req, res, next) => {
mcpNodeHandler(req, res, req.body).catch(next);
});

Expand Down
30 changes: 5 additions & 25 deletions src/backend/src/mcp/projects.tools.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,10 @@
import * as z from 'zod/v4';
import { validateWBS } from 'shared';
import ProjectsService from '../services/projects.services.js';
import CarsService from '../services/car.services.js';
import { withToolErrors } from './errors.js';
import { LIST_PROJECTS_HINT, registerReadOnlyTool, ToolRegistrar, wbsNumSchema } from './tools.utils.js';

export const registerProjectTools: ToolRegistrar = (server, { user, organization }) => {
registerReadOnlyTool(
server,
'finishline_list_cars',
{
title: 'List cars',
description:
"List the organization's cars with their ids, names, and WBS numbers. The car number is the first " +
'part of every WBS number, and the highest car number is the newest car, which is almost always ' +
'the one the user means. Use a car id from here to filter finishline_list_projects.',
inputSchema: z.object({})
},
async () => withToolErrors('', async () => CarsService.getAllCars(organization))
);

export const registerProjectTools: ToolRegistrar = (server, { user, organization, currentCar }) => {
registerReadOnlyTool(
server,
'finishline_list_projects',
Expand All @@ -28,16 +13,11 @@ export const registerProjectTools: ToolRegistrar = (server, { user, organization
description:
'List projects newest first, with their names, WBS numbers, summaries, status, dates, and teams. ' +
'Start here when the user names a project in words rather than by number, then match the name to ' +
'a WBS number and use the other tools. Pass carId to only list one car; without it, projects ' +
'from every car come back, so prefer passing the newest car from finishline_list_cars.',
inputSchema: z.object({
carId: z
.string()
.optional()
.describe('The id of the car to list projects for, from finishline_list_cars. Omit this for every car.')
})
'a WBS number and use the other tools. Only the projects on the car this connection is scoped to ' +
'come back, or every car when it is not scoped to one.',
inputSchema: z.object({})
},
async ({ carId }) => withToolErrors('', async () => ProjectsService.getAllProjects(organization, carId))
async () => withToolErrors('', async () => ProjectsService.getAllProjects(organization, currentCar?.carId))
);

registerReadOnlyTool(
Expand Down
3 changes: 2 additions & 1 deletion src/backend/src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { AgentContext, ToolRegistrar } from './tools.utils.js';
import { registerProjectTools } from './projects.tools.js';
import { registerTaskTools } from './tasks.tools.js';
import { registerEventTools } from './events.tools.js';
import { registerUserTools } from './users.tools.js';

/** Every domain's tools. A new *.tools.ts file only becomes reachable once it is added here. */
const registrars: ToolRegistrar[] = [registerProjectTools, registerTaskTools, registerEventTools];
const registrars: ToolRegistrar[] = [registerProjectTools, registerTaskTools, registerEventTools, registerUserTools];

/**
* Builds a FinishLine MCP server for one authenticated caller. Called once per request, so nothing
Expand Down
7 changes: 6 additions & 1 deletion src/backend/src/mcp/tools.utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Organization } from '@prisma/client';
import { Organization, Prisma } from '@prisma/client';
import { CallToolResult, McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';
import { User } from 'shared';
Expand All @@ -7,6 +7,11 @@ import { User } from 'shared';
export interface AgentContext {
user: User;
organization: Organization;
/**
* The car from the request's carid header, the same global car the app scopes to. Car specific tools
* filter by it and never take a car as input; undefined means every car, as it does in the app.
*/
currentCar?: Prisma.CarGetPayload<{ include: { wbsElement: true } }>;
}

/**
Expand Down
34 changes: 34 additions & 0 deletions src/backend/src/mcp/users.tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as z from 'zod/v4';
import UsersService from '../services/users.services.js';
import { withToolErrors } from './errors.js';
import { registerReadOnlyTool, ToolRegistrar } from './tools.utils.js';

export const registerUserTools: ToolRegistrar = (server, { organization }) => {
registerReadOnlyTool(
server,
'finishline_get_user_slack_id',
{
title: 'Get user Slack id',
description:
"Get a FinishLine user's Slack member id so you can mention them in Slack. Users returned by the " +
'other tools (leads, managers, assignees, event creators) carry a userId to pass here.\n\n' +
'Whenever you refer to a person in a Slack message, prefer mentioning them over writing their name: ' +
'look up their slackId here and write it as <@SLACK_ID>, for example <@U0123456789>, which Slack ' +
'renders as a mention that notifies them. Use the slackId exactly as returned, inside the angle ' +
'brackets with the @, and never the FinishLine userId. slackId is absent when the user has not ' +
'linked their Slack account; only then fall back to writing their first and last name as plain text.',
inputSchema: z.object({
userId: z.string().min(1).describe('The userId of a user returned by another FinishLine tool.')
})
},
async ({ userId }) =>
withToolErrors('Pass a userId returned by another FinishLine tool.', async () => {
// getSingleUser is what confirms the user is in this organization; getUserSettings alone is not scoped
await UsersService.getSingleUser(userId, organization);
const { slackId } = await UsersService.getUserSettings(userId);

// slackId defaults to an empty string, which means the user never linked Slack
return { userId, slackId: slackId || undefined };
})
);
};
64 changes: 59 additions & 5 deletions src/backend/src/services/api-tokens.services.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Organization, User as PrismaUser } from '@prisma/client';
import { ApiTokenMetadata, GeneratedApiToken, notGuest, User } from 'shared';
import { ApiTokenMetadata, GeneratedApiToken, isAdmin, notGuest, User } from 'shared';
import prisma from '../prisma/prisma.js';
import {
AccessDeniedException,
Expand Down Expand Up @@ -49,6 +49,36 @@ const getSoleOrganization = async (userId: string): Promise<Organization> => {
return organization;
};

/**
* Resolves the FinishLine user a Slack bot is acting on behalf of.
*
* Slack ids are only unique per workspace and nothing stops two users from entering the same id, so
* the lookup is scoped to the organization and must match exactly one user rather than picking one.
*
* @param slackUserId the Slack user id of the person who messaged the bot
* @param organizationId the organization the admin token resolved to
* @returns the matching user
* @throws if no user, or more than one user, in the organization has that Slack id
*/
const getUserBySlackId = async (slackUserId: string, organizationId: string): Promise<PrismaUser> => {
const users = await prisma.user.findMany({
where: {
userSettings: { slackId: slackUserId },
organizations: { some: { organizationId } }
},
take: 2
});

if (users.length === 0) {
throw new HttpException(401, 'Authentication Failed: No user in this organization is linked to that Slack id!');
}
if (users.length > 1) {
throw new HttpException(401, 'Authentication Failed: Multiple users in this organization are linked to that Slack id!');
}

return users[0];
};

export default class ApiTokenService {
/**
* Gets the metadata for the given user's active API token, if they have one.
Expand Down Expand Up @@ -96,14 +126,22 @@ export default class ApiTokenService {
* The guest check runs on every call, so demoting someone to guest revokes their token's access
* immediately rather than whenever the token is next rotated.
*
* When a Slack user id is given, the request is being made by a shared bot on behalf of that Slack
* user. The token must then belong to an admin of the organization (anything else fails outright,
* never falling back to the token's own user), and the request runs as the organization member
* linked to that Slack id instead of as the token's owner.
*
* @param token the raw API token the client sent
* @param organizationId the organization the client asked for, or undefined to use the user's only organization
* @returns the token's user and the organization to scope the request to
* @throws if the token is missing, unknown, or revoked, the organization can't be resolved, or the user is a guest
* @param slackUserId the Slack user id the bot is acting for, or undefined for a normal token request
* @returns the user to act as and the organization to scope the request to
* @throws if the token is missing, unknown, or revoked, the organization can't be resolved, the user
* is a guest, or a Slack user id was given and the token isn't an admin's or the id doesn't resolve
*/
static async authenticateApiToken(
token: string | undefined,
organizationId: string | undefined
organizationId: string | undefined,
slackUserId?: string
): Promise<{ user: PrismaUser; organization: Organization }> {
if (!token) throw new HttpException(401, 'Authentication Failed: No API token provided!');

Expand All @@ -129,6 +167,22 @@ export default class ApiTokenService {
.update({ where: { apiTokenId: apiToken.apiTokenId }, data: { lastUsedAt: new Date() } })
.catch(() => {});

return { user, organization };
if (slackUserId === undefined) return { user, organization };

// a header that was sent but is blank must not fall through to acting as the admin, and an empty
// string would otherwise match every user who never set a Slack id (the column defaults to '')
const trimmedSlackUserId = slackUserId.trim();
if (!trimmedSlackUserId) throw new HttpException(401, 'Authentication Failed: Empty Slack user id!');

const isTokenAdmin = await userHasPermission(user.userId, organization.organizationId, isAdmin);
if (!isTokenAdmin) throw new AccessDeniedException('only admin API tokens can act on behalf of a Slack user');

const slackUser = await getUserBySlackId(trimmedSlackUserId, organization.organizationId);

// the impersonated user is held to the same rule as a token owner
const slackUserHasPermission = await userHasPermission(slackUser.userId, organization.organizationId, notGuest);
if (!slackUserHasPermission) throw new AccessDeniedException('guests cannot use the API');

return { user: slackUser, organization };
}
}
26 changes: 21 additions & 5 deletions src/backend/src/utils/mcp-auth.utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,40 @@
import { NextFunction, Request, Response } from 'express';
import ApiTokenService from '../services/api-tokens.services.js';
import { AccessDeniedException } from './errors.utils.js';
import { AccessDeniedException, HttpException } from './errors.utils.js';

/** The header an API client sends its token in. */
const API_KEY_HEADER = 'x-api-key';

/**
* The header a shared bot (the Slack bot) sends with an admin token to act as a specific Slack user.
* Node lowercases incoming header names, so this matches regardless of the casing the client used.
*/
const SLACKBOT_USER_ID_HEADER = 'x-slackbot-user-id';

/**
* Authenticates a request using a per-user API token instead of the session cookie.
*
* Populates req.currentUser and req.organization exactly like getUserAndOrganization does, so
* downstream services are indistinguishable from the ones the cookie authenticated API calls.
*
* If an x-slackbot-user-id header is present, the token must be an admin's and the request runs as the
* organization member linked to that Slack id (see ApiTokenService.authenticateApiToken).
*/
export const requireApiToken = async (req: Request, _res: Response, next: NextFunction) => {
try {
const tokenHeader = req.headers[API_KEY_HEADER];
const organizationHeader = req.headers.organizationid;
const slackUserHeader = req.headers[SLACKBOT_USER_ID_HEADER];

// a repeated header arrives as an array; treat that as ambiguous rather than picking one
if (Array.isArray(slackUserHeader)) {
throw new HttpException(401, 'Authentication Failed: Multiple Slack user ids provided!');
}

const { user, organization } = await ApiTokenService.authenticateApiToken(
typeof tokenHeader === 'string' ? tokenHeader.trim() : undefined,
typeof organizationHeader === 'string' ? organizationHeader : undefined
typeof organizationHeader === 'string' ? organizationHeader : undefined,
slackUserHeader
);

req.currentUser = user;
Expand Down Expand Up @@ -46,15 +62,15 @@ export const readOnlyGuard = (req: Request, _res: Response, next: NextFunction)
* Hands the authenticated caller to the MCP handler.
*
* toNodeHandler forwards req.auth to the handler as its pass-through authInfo, and AuthInfo.extra
* is the documented place for data of our own, so the MCP server factory reads the user and
* organization back out of it. Must run after requireApiToken.
* is the documented place for data of our own, so the MCP server factory reads the user,
* organization, and current car back out of it. Must run after requireApiToken and getCurrentCar.
*/
export const attachAuthInfo = (req: Request, _res: Response, next: NextFunction) => {
req.auth = {
token: '',
clientId: req.currentUser.userId,
scopes: [],
extra: { user: req.currentUser, organization: req.organization }
extra: { user: req.currentUser, organization: req.organization, currentCar: req.currentCar }
};

return next();
Expand Down
85 changes: 84 additions & 1 deletion src/backend/tests/unit/api-tokens.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { Organization, Role_Type } from '@prisma/client';
import { createTestOrganization, createTestUser, resetUsers } from '../test-utils.js';
import { batmanAppAdmin, theVisitorGuest } from '../test-data/users.test-data.js';
import {
batmanAppAdmin,
member,
supermanAdmin,
supermanSettings,
theVisitorGuest,
wonderwomanGuest,
wonderwomanSettings
} from '../test-data/users.test-data.js';
import { AccessDeniedException, AccessDeniedGuestException, HttpException } from '../../src/utils/errors.utils.js';
import prisma from '../../src/prisma/prisma.js';
import ApiTokenService from '../../src/services/api-tokens.services.js';
Expand Down Expand Up @@ -145,4 +153,79 @@ describe('Api Token Tests', () => {
);
});
});

describe('Authenticate Api Token On Behalf Of A Slack User', () => {
it('resolves to the organization member linked to the slack id', async () => {
const batman = await createTestUser(batmanAppAdmin, orgId);
const superman = await createTestUser(supermanAdmin, orgId, supermanSettings);
const { token } = await ApiTokenService.generateApiToken(batman, organization);

const { user, organization: resolved } = await ApiTokenService.authenticateApiToken(
token,
undefined,
supermanSettings.slackId
);

expect(user.userId).toBe(superman.userId);
expect(resolved.organizationId).toBe(orgId);
});

it('fails outright when the token is not an admin', async () => {
const regularMember = await createTestUser(member, orgId);
await createTestUser(supermanAdmin, orgId, supermanSettings);
const { token } = await ApiTokenService.generateApiToken(regularMember, organization);

await expect(ApiTokenService.authenticateApiToken(token, undefined, supermanSettings.slackId)).rejects.toThrow(
new AccessDeniedException('only admin API tokens can act on behalf of a Slack user')
);
});

it('fails when no user in the organization has the slack id', async () => {
const batman = await createTestUser(batmanAppAdmin, orgId);
const { token } = await ApiTokenService.generateApiToken(batman, organization);

await expect(ApiTokenService.authenticateApiToken(token, undefined, 'unknownSlackId')).rejects.toThrow(
new HttpException(401, 'Authentication Failed: No user in this organization is linked to that Slack id!')
);
});

it('fails when the slack user belongs to a different organization', async () => {
const batman = await createTestUser(batmanAppAdmin, orgId);
// created inline rather than with createTestOrganization, which always uses the same unique creator and slug
const otherOrganization = await prisma.organization.create({
data: {
name: 'Other Org',
slug: 'other-org',
description: 'A second organization',
applicationLink: '',
userCreated: { connect: { userId: batman.userId } }
}
});
await createTestUser(supermanAdmin, otherOrganization.organizationId, supermanSettings);
const { token } = await ApiTokenService.generateApiToken(batman, organization);

await expect(ApiTokenService.authenticateApiToken(token, orgId, supermanSettings.slackId)).rejects.toThrow(
new HttpException(401, 'Authentication Failed: No user in this organization is linked to that Slack id!')
);
});

it('fails for a blank slack id rather than acting as the admin', async () => {
const batman = await createTestUser(batmanAppAdmin, orgId);
const { token } = await ApiTokenService.generateApiToken(batman, organization);

await expect(ApiTokenService.authenticateApiToken(token, undefined, ' ')).rejects.toThrow(
new HttpException(401, 'Authentication Failed: Empty Slack user id!')
);
});

it('fails when the slack user is a guest', async () => {
const batman = await createTestUser(batmanAppAdmin, orgId);
await createTestUser(wonderwomanGuest, orgId, wonderwomanSettings);
const { token } = await ApiTokenService.generateApiToken(batman, organization);

await expect(ApiTokenService.authenticateApiToken(token, undefined, wonderwomanSettings.slackId)).rejects.toThrow(
new AccessDeniedException('guests cannot use the API')
);
});
});
});
Loading
Loading