Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e2a0cdf
[US-001] Generalize scope helpers for runtime tables and add barrel e…
amikofalvy Mar 15, 2026
ac98033
[US-002] Fix unscoped runtime DAL functions (security)
amikofalvy Mar 15, 2026
8eacee2
[US-003] Add PG retry utility and fix runtime-tasks-scoping test type…
amikofalvy Mar 15, 2026
15c7ebb
[US-004] Fix ledgerArtifacts.ts crash bug and replace ad-hoc FK viola…
amikofalvy Mar 15, 2026
5fe6273
[US-005] Extract Drizzle queries from auth.ts and add DAL boundary li…
amikofalvy Mar 15, 2026
28bf794
[US-006] Migrate 9 simple manage DAL files to scope helpers
amikofalvy Mar 15, 2026
ec27cb1
[US-007] Migrate agents, credentialReferences, dataComponents, artifa…
amikofalvy Mar 15, 2026
e8c9117
[US-008] Migrate skills, functionTools, projects, projectLifecycle to…
amikofalvy Mar 15, 2026
46af230
[US-009] Migrate subAgentRelations.ts to scope helpers
amikofalvy Mar 15, 2026
05b2c54
[US-010] Migrate evalConfig.ts to scope helpers
amikofalvy Mar 15, 2026
7a0bb28
[US-011] Migrate subAgentTeamAgentRelations and agentFull to scope he…
amikofalvy Mar 15, 2026
8f810f8
[US-012] Migrate 10 runtime DAL files to scope helpers
amikofalvy Mar 15, 2026
a190502
[US-013] Migrate 5 runtime DAL files with mixed params to scope helpers
amikofalvy Mar 15, 2026
30fd2cc
style: auto-format with biome
github-actions[bot] Mar 15, 2026
3a62977
fix: correct scope level for subAgents and subAgentArtifactComponents…
amikofalvy Mar 16, 2026
e48f7f9
refactor: tighten types in fetchComponentRelationships to remove as-a…
amikofalvy Mar 16, 2026
24ac971
refactor: extract repeated scope objects into reusable variables
amikofalvy Mar 16, 2026
dd27b55
fix: address PR review feedback — inline error checks and lint script
amikofalvy Mar 16, 2026
16413b6
fix: address remaining PR review comments (1-5)
amikofalvy Mar 16, 2026
6c11c7e
chore: add changeset for DAL scope helper migration
amikofalvy Mar 16, 2026
0e94d78
chore: soften changeset message
amikofalvy Mar 16, 2026
07a69b0
docs: add dal-boundary to pnpm check description in AGENTS.md
amikofalvy Mar 16, 2026
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: 5 additions & 0 deletions .changeset/sudden-cyan-centipede.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@inkeep/agents-core": patch
---

Add defense-in-depth tenant scoping to runtime DAL functions and migrate all DAL files to type-safe scope helpers
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ This file provides guidance for AI coding agents (Claude Code, Cursor, Codex, Am
**Pre-push** (run both, in order):
```bash
pnpm format # auto-fix formatting
pnpm check # lint + typecheck + test + format:check + env-descriptions + route-handler-patterns + knip
pnpm check # lint + typecheck + test + format:check + env-descriptions + route-handler-patterns + dal-boundary + knip
```

**Single-command iteration:** `pnpm typecheck`, `pnpm lint` (`lint:fix`), `pnpm test`, `cd <pkg> && pnpm test --run <file>`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
getConversation,
getEvaluatorById,
getProjectScopedRef,
isForeignKeyViolation,
resolveRef,
updateEvaluationResult,
withRef,
Expand Down Expand Up @@ -114,9 +115,8 @@ async function createRelationStep(payload: RunDatasetItemPayload, conversationId
);

return { relationId, success: true };
} catch (error: any) {
// If foreign key constraint fails, the conversation doesn't exist
if (error?.cause?.code === '23503' || error?.code === '23503') {
} catch (error) {
if (isForeignKeyViolation(error)) {
logger.warn(
{ tenantId, projectId, datasetItemId, datasetRunId, conversationId },
'Conversation does not exist, skipping relation creation'
Expand Down
6 changes: 3 additions & 3 deletions agents-api/src/domains/manage/routes/apiKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ErrorResponseSchema,
generateApiKey,
getApiKeyById,
isForeignKeyViolation,
listApiKeysPaginated,
PaginationQueryParamsSchema,
TenantProjectIdParamsSchema,
Expand Down Expand Up @@ -193,9 +194,8 @@ app.openapi(
},
201
);
} catch (error: any) {
// Handle foreign key constraint violations (PostgreSQL foreign key violation)
if (error?.cause?.code === '23503') {
} catch (error) {
if (isForeignKeyViolation(error)) {
throw createApiError({
code: 'bad_request',
message: 'Invalid agentId - agent does not exist',
Expand Down
4 changes: 2 additions & 2 deletions agents-api/src/domains/manage/routes/subAgentToolRelations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
getAgentToolRelationByAgent,
getAgentToolRelationById,
getAgentToolRelationByTool,
isForeignKeyViolation,
listAgentToolRelations,
PaginationQueryParamsSchema,
SubAgentToolRelationApiInsertSchema,
Expand Down Expand Up @@ -254,8 +255,7 @@ app.openapi(
});
return c.json({ data: agentToolRelation }, 201);
} catch (error) {
// Handle foreign key constraint violations (PostgreSQL foreign key violation)
if ((error as any)?.cause?.code === '23503') {
if (isForeignKeyViolation(error)) {
throw createApiError({
code: 'bad_request',
message: 'Invalid subAgent ID or tool ID - referenced entity does not exist',
Expand Down
1 change: 1 addition & 0 deletions agents-api/src/domains/run/a2a/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ async function handleMessageSend(

await updateTask(runDbClient)({
taskId: task.id,
scopes: { tenantId: agent.tenantId, projectId: agent.projectId },
data: {
status: result.status.state.toLowerCase(),
metadata: {
Expand Down
2 changes: 2 additions & 0 deletions agents-api/src/domains/run/artifacts/ArtifactService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,13 @@ export class ArtifactService {
try {
const taskIds = await listTaskIdsByContextId(runDbClient)({
contextId: contextId,
scopes: { tenantId, projectId },
});

for (const taskId of taskIds) {
const task = await getTask(runDbClient)({
id: taskId,
scopes: { tenantId, projectId },
});
if (!task) {
logger.warn({ taskId }, 'Task not found when fetching artifacts');
Expand Down
4 changes: 4 additions & 0 deletions agents-api/src/domains/run/context/contextCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ export class ContextCache {
contextConfigId,
contextVariableKey,
requestHash,
scopes: {
tenantId: this.executionContext.tenantId,
projectId: this.executionContext.projectId,
},
});
if (!cacheEntry) {
return null;
Expand Down
10 changes: 9 additions & 1 deletion agents-api/src/domains/run/handlers/executionHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,10 @@ export class ExecutionHandler {
'Task already exists, fetching existing task'
);

const existingTask = await getTask(runDbClient)({ id: taskId });
const existingTask = await getTask(runDbClient)({
id: taskId,
scopes: { tenantId, projectId },
});
if (existingTask) {
task = existingTask;
logger.info(
Expand Down Expand Up @@ -368,6 +371,7 @@ export class ExecutionHandler {
if (task) {
await updateTask(runDbClient)({
taskId: task.id,
scopes: { tenantId, projectId },
data: {
status: 'failed',
metadata: {
Expand Down Expand Up @@ -536,6 +540,7 @@ export class ExecutionHandler {
const updateTaskStart = Date.now();
await updateTask(runDbClient)({
taskId: task.id,
scopes: { tenantId, projectId },
data: {
status: 'completed',
metadata: {
Expand Down Expand Up @@ -636,6 +641,7 @@ export class ExecutionHandler {
if (task) {
await updateTask(runDbClient)({
taskId: task.id,
scopes: { tenantId, projectId },
data: {
status: 'failed',
metadata: {
Expand Down Expand Up @@ -699,6 +705,7 @@ export class ExecutionHandler {
if (task) {
await updateTask(runDbClient)({
taskId: task.id,
scopes: { tenantId, projectId },
data: {
status: 'failed',
metadata: {
Expand Down Expand Up @@ -747,6 +754,7 @@ export class ExecutionHandler {
if (task) {
await updateTask(runDbClient)({
taskId: task.id,
scopes: { tenantId, projectId },
data: {
status: 'failed',
metadata: {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"typecheck": "turbo typecheck --filter='!agents-cookbook-templates'",
"typecheck:watch": "turbo typecheck:watch",
"precheck": "pnpm install --frozen-lockfile",
"check": "turbo check --filter='!agents-cookbook-templates' && pnpm format:check && pnpm check:env-descriptions && pnpm check:route-handler-patterns && pnpm knip",
"check": "turbo check --filter='!agents-cookbook-templates' && pnpm format:check && pnpm check:env-descriptions && pnpm check:route-handler-patterns && pnpm check:dal-boundary && pnpm knip",
"check:husky": "turbo check:husky --filter='!agents-cookbook-templates' --filter='!@inkeep/agents-docs'",
"check:prepush": "turbo check:prepush --filter='!agents-cookbook-templates' --filter='!@inkeep/agents-docs'",
"check:fix": "biome check --write",
Expand Down Expand Up @@ -79,6 +79,7 @@
"spicedb:sync": "bash scripts/sync-spicedb.sh",
"spicedb:sync:apply": "bash scripts/sync-spicedb.sh --apply",
"db:auth:init": "pnpm --filter @inkeep/agents-core db:auth:init",
"check:dal-boundary": "bash scripts/lint-data-access-boundary.sh",
"check:env-descriptions": "node scripts/check-env-descriptions.mjs",
"check:route-handler-patterns": "node scripts/check-route-handler-patterns.mjs",
"setup-slack-dev": "tsx scripts/setup-slack-dev.ts"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,10 @@ describe('API Keys Data Access', () => {
update: mockUpdate,
} as any;

await updateApiKeyLastUsed(mockDb)(apiKeyId);
await updateApiKeyLastUsed(mockDb)({
id: apiKeyId,
scopes: { tenantId: 'test-tenant', projectId: 'test-project' },
});

expect(mockUpdate).toHaveBeenCalled();
// Verify the set method was called with lastUsedAt
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ describe('Context Cache Data Access', () => {
conversationId: testConversationId,
contextConfigId: testContextConfigId,
contextVariableKey: testContextVariableKey,
scopes: { tenantId: testTenantId, projectId: testProjectId },
});

expect(mockQuery.contextCache.findFirst).toHaveBeenCalled();
Expand All @@ -85,6 +86,7 @@ describe('Context Cache Data Access', () => {
conversationId: testConversationId,
contextConfigId: testContextConfigId,
contextVariableKey: testContextVariableKey,
scopes: { tenantId: testTenantId, projectId: testProjectId },
});

expect(result).toBeNull();
Expand Down Expand Up @@ -124,6 +126,7 @@ describe('Context Cache Data Access', () => {
contextConfigId: testContextConfigId,
contextVariableKey: testContextVariableKey,
requestHash: 'newHash',
scopes: { tenantId: testTenantId, projectId: testProjectId },
});

expect(result).toBeNull();
Expand Down Expand Up @@ -163,6 +166,7 @@ describe('Context Cache Data Access', () => {
contextConfigId: testContextConfigId,
contextVariableKey: testContextVariableKey,
requestHash: 'matchingHash',
scopes: { tenantId: testTenantId, projectId: testProjectId },
});

expect(result).not.toBeNull();
Expand All @@ -185,6 +189,7 @@ describe('Context Cache Data Access', () => {
conversationId: testConversationId,
contextConfigId: testContextConfigId,
contextVariableKey: testContextVariableKey,
scopes: { tenantId: testTenantId, projectId: testProjectId },
});

expect(result).toBeNull();
Expand Down Expand Up @@ -224,6 +229,7 @@ describe('Context Cache Data Access', () => {
contextConfigId: testContextConfigId,
contextVariableKey: testContextVariableKey,
requestHash: 'someHash',
scopes: { tenantId: testTenantId, projectId: testProjectId },
});

expect(result).not.toBeNull();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { getCacheEntry, setCacheEntry } from '../../../data-access/runtime/contextCache';
import type { AgentsRunDatabaseClient } from '../../../db/runtime/runtime-client';
import { contextCache, conversations } from '../../../db/runtime/runtime-schema';
import { generateId } from '../../../utils/conversations';
import { testRunDbClient } from '../../setup';

describe('runtime contextCache scoping isolation', () => {
let db: AgentsRunDatabaseClient;
const tenantA = 'tenant-a';
const tenantB = 'tenant-b';
const projectA = 'project-a';
const projectB = 'project-b';
const conversationId = 'conv-1';
const contextConfigId = 'config-1';
const contextVariableKey = 'var-key';

beforeEach(async () => {
db = testRunDbClient;
await db.delete(contextCache);
await db.delete(conversations);

await db.insert(conversations).values({
id: conversationId,
tenantId: tenantA,
projectId: projectA,
activeSubAgentId: 'sub-1',
});
});

it('getCacheEntry should not return a cache entry belonging to a different tenant', async () => {
await setCacheEntry(db)({
id: generateId(),
tenantId: tenantA,
projectId: projectA,
conversationId,
contextConfigId,
contextVariableKey,
ref: { type: 'branch', name: 'main', hash: 'abc' },
value: { data: 'test' },
fetchedAt: new Date().toISOString(),
});

const wrongTenant = await getCacheEntry(db)({
conversationId,
contextConfigId,
contextVariableKey,
scopes: { tenantId: tenantB, projectId: projectA },
});
expect(wrongTenant).toBeNull();

const correctTenant = await getCacheEntry(db)({
conversationId,
contextConfigId,
contextVariableKey,
scopes: { tenantId: tenantA, projectId: projectA },
});
expect(correctTenant).not.toBeNull();
expect(correctTenant?.conversationId).toBe(conversationId);
});

it('getCacheEntry should not return a cache entry belonging to a different project', async () => {
await setCacheEntry(db)({
id: generateId(),
tenantId: tenantA,
projectId: projectA,
conversationId,
contextConfigId,
contextVariableKey,
ref: { type: 'branch', name: 'main', hash: 'abc' },
value: { data: 'test' },
fetchedAt: new Date().toISOString(),
});

const wrongProject = await getCacheEntry(db)({
conversationId,
contextConfigId,
contextVariableKey,
scopes: { tenantId: tenantA, projectId: projectB },
});
expect(wrongProject).toBeNull();

const correctProject = await getCacheEntry(db)({
conversationId,
contextConfigId,
contextVariableKey,
scopes: { tenantId: tenantA, projectId: projectA },
});
expect(correctProject).not.toBeNull();
expect(correctProject?.conversationId).toBe(conversationId);
});
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test only verifies cross-tenant isolation. Unlike the tasks scoping test which has a dedicated cross-project case, there's no test that inserts a cache entry for projectA and queries with projectB. Add one to verify project-level isolation.

Loading
Loading