🔐 feat: Limit API Key Runs to Their Grants by Default (#18377)

This commit is contained in:
Danny Avila 2026-11-18 14:05:23 -05:00 • committed by GitHub
parent 3375bb5c3c
commit d24769ea1a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 134 additions and 17 deletions

View file

@ -40,8 +40,10 @@ describe('API key routes', () => {
});
});
it('lists keys without the grants flag where key runs are not limited', async () => {
getAppConfig.mockResolvedValueOnce({ endpoints: { agents: {} } });
it('lists keys without the grants flag where the operator left key runs unlimited', async () => {
getAppConfig.mockResolvedValueOnce({
endpoints: { agents: { remoteApi: { integrations: { mode: 'owner' } } } },
});
const response = await request(app).get('/api/api-keys');
expect(response.status).toBe(200);
expect(response.body).toEqual({ keys: mockKeys });

View file

@ -42,9 +42,10 @@ describe('API key grant wiring', () => {
});
});
it('lets a personal key run through untouched where key runs are not limited', async () => {
it('lets a personal key run through untouched where the operator left key runs unlimited', async () => {
const host = require('./grants');
for (const config of [undefined, { endpoints: { agents: {} } }]) {
const owner = { remoteApi: { integrations: { mode: 'owner' } } };
for (const config of [{ endpoints: { agents: owner } }]) {
getAppConfig.mockResolvedValueOnce(config);
const req = { user: { id: 'owner', role: 'USER' } };
await expect(

View file

@ -26,8 +26,8 @@ import {
getScheduleMCPExecution,
bindScheduledMCPInvocation,
} from '~/schedules/authorization/execution';
import { getRemoteRunKeyId, resolveRemoteIntegrations, createAgentKeyMCPGrantHost } from './grants';
import { createRemoteExecutionContext } from '~/agents/authority/context';
import { createAgentKeyMCPGrantHost, getRemoteRunKeyId } from './grants';
import { getMCPRequestContext } from '~/mcp/request';
const queryTool: Tool = {
@ -216,10 +216,21 @@ afterEach(() => jest.restoreAllMocks());
const refused = (reason: string) => ({ failure: { reason, automaticReplay: false } });
it('leaves key runs as they were unless the operator asks for grants', async () => {
for (const integrations of [null, {}, { mode: 'owner', resources: { warehouse: resource } }]) {
it('leaves key runs as they were only where the operator says so', async () => {
const s = setup({ mode: 'owner', resources: { warehouse: resource } });
await expect((await s.run()).call()).resolves.toBe('unrestricted');
expect(await s.host.service.view(s.identity())).toMatchObject({
state: 'unsupported',
offer: null,
});
});
it('limits key runs to their grants unless told otherwise, even with nothing declared', async () => {
for (const integrations of [null, {}]) {
const s = setup(integrations);
await expect((await s.run()).call()).resolves.toBe('unrestricted');
expect(resolveRemoteIntegrations(s.config).mode).toBe('delegated');
await expect((await s.run()).call()).rejects.toMatchObject(refused('consent_missing'));
// Nothing is declared, so there is nothing the owner could grant.
expect(await s.host.service.view(s.identity())).toMatchObject({
state: 'unsupported',
offer: null,

View file

@ -31,7 +31,10 @@ import { checkAccess } from '~/middleware/access';
type RemoteAgentAccessParams = Parameters<typeof checkRemoteAgentAccess>[0];
export interface RemoteIntegrations {
/** `owner`: every server the key's owner can use. `delegated`: only what a grant covers. */
/**
* `delegated`, the default: only what the key's owner granted it. `owner`: every server the
* owner can use, which is how key runs behaved before grants existed.
*/
mode: 'owner' | 'delegated';
maxLifetimeHours: number;
resources?: Record<string, ScheduledMCPResourceBinding>;
@ -41,7 +44,7 @@ export interface RemoteIntegrations {
export function resolveRemoteIntegrations(appConfig?: AppConfig): RemoteIntegrations {
const integrations = appConfig?.endpoints?.[EModelEndpoint.agents]?.remoteApi?.integrations;
return {
mode: integrations?.mode ?? 'owner',
mode: integrations?.mode ?? 'delegated',
maxLifetimeHours: integrations?.maxLifetimeHours ?? DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS,
...(integrations?.resources && { resources: integrations.resources }),
};

View file

@ -30,14 +30,15 @@ function setup(getAppConfig?: ApiKeyHandlerDependencies['getAppConfig']) {
}
describe('listApiKeys', () => {
it('lists keys as before where nothing says grants are in use', async () => {
it('lists keys without the flag where the operator left key runs unlimited', async () => {
const { list, keys } = setup();
expect(await list()).toEqual({ keys });
for (const config of [undefined, configured(), configured('owner')])
expect(await setup(async () => config).list()).toEqual({ keys });
expect(await setup(async () => configured('owner')).list()).toEqual({ keys });
});
it('tells the client when key runs are limited to what the owner granted', async () => {
it('tells the client when key runs are limited to what the owner granted, which is the default', async () => {
for (const config of [undefined, configured()])
expect(await setup(async () => config).list()).toMatchObject({ grants: true });
const getAppConfig = jest.fn(async () => configured('delegated'));
const { list, keys } = setup(getAppConfig);
expect(await list()).toEqual({ keys, grants: true });

View file

@ -0,0 +1,16 @@
version: 1.3.8
cache: true
interface:
remoteAgents:
use: true
endpoints:
agents:
remoteApi:
integrations:
resources:
warehouse:
url: https://warehouse.example/mcp
credentialMode: stored_oauth
issuer: https://issuer.example/
audience: warehouse
scopes: [read]

View file

@ -0,0 +1,10 @@
version: 1.3.8
cache: true
interface:
remoteAgents:
use: true
endpoints:
agents:
remoteApi:
integrations:
mode: owner

View file

@ -0,0 +1,5 @@
version: 1.3.8
cache: true
interface:
remoteAgents:
use: true

View file

@ -277,6 +277,33 @@ describe('createCustomConfigLoader retired schedule tool policy', () => {
expect(warnings(warn)).not.toContain('readOnlyPolicy');
});
it('tells an operator who uses the remote API that key runs have no MCP server to be granted', async () => {
process.env.CONFIG_PATH = path.join(__dirname, '__fixtures__', 'remote', 'ungrantable.yaml');
const config = await createLoader()(false);
expect(config?.interface?.remoteAgents).toMatchObject({ use: true });
expect(warnings(warn)).toContain('Agent API key runs cannot use MCP tools');
expect(warnings(warn)).toContain('endpoints.agents.remoteApi.integrations.resources');
expect(warnings(warn)).toContain('"owner"');
});
it.each(['declared', 'owner'])(
'says nothing about key runs when the %s configuration answers it',
async (name) => {
process.env.CONFIG_PATH = path.join(__dirname, '__fixtures__', 'remote', `${name}.yaml`);
await createLoader()(false);
expect(warnings(warn)).not.toContain('Agent API key runs');
},
);
it('says nothing about key runs to a deployment that does not mention the remote API', async () => {
process.env.CONFIG_PATH = fixture('valid');
await createLoader()(false);
expect(warnings(warn)).not.toContain('Agent API key runs');
});
});
describe('createCustomConfigLoader remote fetch failures', () => {

View file

@ -158,6 +158,41 @@ function reportRetiredScheduleToolPolicy(configPath: string, config: unknown): v
);
}
/**
* API key runs may use only the MCP tools the key's owner granted, and an owner can grant only
* servers the operator declared. A deployment that uses the remote API and declares none has
* every key run's MCP tools refused with nothing to grant, so its operator is told how to
* declare them or how to keep the earlier behaviour.
*/
function reportUngrantableKeyRuns(configPath: string, config: unknown): void {
const root = config as {
interface?: { remoteAgents?: unknown };
endpoints?: { agents?: { remoteApi?: { integrations?: unknown } } };
} | null;
const remoteApi = root?.endpoints?.agents?.remoteApi;
if (root?.interface?.remoteAgents == null && remoteApi == null) {
return;
}
const integrations = remoteApi?.integrations as
| { mode?: unknown; resources?: unknown }
| null
| undefined;
const declared =
integrations?.resources != null &&
typeof integrations.resources === 'object' &&
Object.keys(integrations.resources).length > 0;
if (integrations?.mode === 'owner' || declared) {
return;
}
logger.warn(
`Agent API key runs cannot use MCP tools with the configuration in ${configPath}: a key may ` +
'use only the servers and tools its owner granted it, and no server is declared under ' +
'endpoints.agents.remoteApi.integrations.resources. Declare the servers keys may be ' +
'granted, or set endpoints.agents.remoteApi.integrations.mode to "owner" to let a key ' +
'use every server its owner can, as before.',
);
}
function reportThemeCheck(configPath: string, errors: string[], warnings: string[]): void {
if (errors.length > 0) {
logger.warn(
@ -314,6 +349,7 @@ export function createCustomConfigLoader({
loadedConfig = linkCheck.config;
reportPolicyLinkCheck(configPath, linkCheck.dropped);
reportRetiredScheduleToolPolicy(configPath, loadedConfig);
reportUngrantableKeyRuns(configPath, loadedConfig);
setMaxSubagents(getConfiguredMaxSubagents(loadedConfig));
/* `filters` PII patterns are sized by RE2, which the shared schema cannot carry. Every

View file

@ -141,12 +141,16 @@ endpoints:
agents:
remoteApi:
integrations:
mode: delegated # default `owner`: every server the key's owner can use
mode: delegated # the default. `owner`: every server the key's owner can use
maxLifetimeHours: 168
resources: # the servers a key may be granted, as for schedules
warehouse: { url: ..., credentialMode: ..., issuer: ..., audience: ..., scopes: [] }
```
`delegated` is the default. With no `resources` declared there is nothing an owner can grant,
so every key run's MCP tools are refused; the config loader warns a deployment that uses the
remote API about it. `mode: owner` restores the behaviour from before grants existed.
Under `delegated`, a run started with a personal key (chat completions, Responses, and a
background Responses worker) is put under that key's grant for the agent before any tool is
loaded. A key with no grant for the agent may not use MCP tools at all (`consent_missing`).

View file

@ -1149,8 +1149,9 @@ const remoteApiAuthSchema = z.object({
/**
* Which of the key owner's MCP servers a run started with an API key may use.
* `owner`: every server the owner can use, as before. `delegated`: only the servers and
* tools the owner approved for that key and that agent; anything else is refused.
* `delegated`, the default: only the servers and tools the owner approved for that key and
* that agent; anything else is refused. `owner`: every server the owner can use, which is how
* key runs behaved before grants existed.
*/
const remoteApiIntegrationsSchema = z.object({
mode: z.enum(['owner', 'delegated']).optional(),