@open-mercato/scheduler 0.6.8-develop.7016.1.4ed7b1e49d → 0.6.8-develop.7020.1.d14d757582

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- [build:scheduler] found 55 entry points
1
+ [build:scheduler] found 57 entry points
2
2
  [build:scheduler] built successfully
@@ -0,0 +1,66 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import {
5
+ SCHEDULER_JOBS_PATH,
6
+ SCHEDULER_TRIGGER_PATH,
7
+ createScheduleJob,
8
+ deleteScheduleJob,
9
+ uniqueScheduleName
10
+ } from "./helpers/scheduler.js";
11
+ const isAsyncQueueStrategy = (process.env.QUEUE_STRATEGY || "local") === "async";
12
+ test.describe("TC-SCHED-008: system-scoped schedule access on trigger and executions", () => {
13
+ test("super admin reaches the schedule on both routes; a non-super-admin is forbidden", async ({ request }) => {
14
+ const superToken = await getAuthToken(request, "superadmin");
15
+ const adminToken = await getAuthToken(request, "admin");
16
+ let scheduleId = null;
17
+ try {
18
+ scheduleId = await createScheduleJob(request, superToken, {
19
+ name: uniqueScheduleName("System-Trigger-Test"),
20
+ scopeType: "system",
21
+ scheduleType: "interval",
22
+ scheduleValue: "1h"
23
+ });
24
+ const superResponse = await apiRequest(request, "POST", SCHEDULER_TRIGGER_PATH, {
25
+ token: superToken,
26
+ data: { id: scheduleId }
27
+ });
28
+ const superBody = await readJsonSafe(superResponse);
29
+ expect(
30
+ superResponse.status(),
31
+ "a super admin must not be told a system-scoped schedule does not exist"
32
+ ).not.toBe(404);
33
+ if (isAsyncQueueStrategy) {
34
+ expect(superResponse.status()).toBe(200);
35
+ expect(superBody?.ok).toBe(true);
36
+ expect(typeof superBody?.jobId === "string" && superBody.jobId.length > 0).toBe(true);
37
+ } else {
38
+ expect(superResponse.status()).toBe(400);
39
+ expect(superBody?.error ?? "").toMatch(/async/i);
40
+ }
41
+ const adminResponse = await apiRequest(request, "POST", SCHEDULER_TRIGGER_PATH, {
42
+ token: adminToken,
43
+ data: { id: scheduleId }
44
+ });
45
+ expect(
46
+ adminResponse.status(),
47
+ "a non-super-admin must be forbidden from triggering a system-scoped schedule"
48
+ ).toBe(403);
49
+ const executionsPath = `${SCHEDULER_JOBS_PATH}/${scheduleId}/executions`;
50
+ const superExecutions = await apiRequest(request, "GET", executionsPath, { token: superToken });
51
+ expect(
52
+ superExecutions.status(),
53
+ "a super admin must not be told a system-scoped schedule has no execution history route"
54
+ ).not.toBe(404);
55
+ expect(superExecutions.status()).toBe(isAsyncQueueStrategy ? 200 : 400);
56
+ const adminExecutions = await apiRequest(request, "GET", executionsPath, { token: adminToken });
57
+ expect(
58
+ adminExecutions.status(),
59
+ "a non-super-admin must be forbidden from reading a system-scoped execution history"
60
+ ).toBe(403);
61
+ } finally {
62
+ await deleteScheduleJob(request, superToken, scheduleId);
63
+ }
64
+ });
65
+ });
66
+ //# sourceMappingURL=TC-SCHED-008.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/__integration__/TC-SCHED-008.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport {\n SCHEDULER_JOBS_PATH,\n SCHEDULER_TRIGGER_PATH,\n createScheduleJob,\n deleteScheduleJob,\n uniqueScheduleName,\n} from './helpers/scheduler'\n\nconst isAsyncQueueStrategy = (process.env.QUEUE_STRATEGY || 'local') === 'async'\n\ntype TriggerBody = { ok?: boolean; jobId?: string; error?: string; message?: string }\n\n/**\n * TC-SCHED-008: POST /api/scheduler/trigger and GET /api/scheduler/jobs/[id]/executions\n * resolve the scope of a system-scoped schedule on the loaded row, not in the lookup.\n *\n * A system-scoped schedule has `tenantId === null` and `organizationId === null`. When both\n * routes folded the caller's tenant/org into the `where` clause, no such row could ever match\n * and every caller \u2014 super admins included \u2014 got 404, which also masked each route's own\n * super-admin gate. A super admin must now reach the schedule, and a non-super-admin must be\n * told 403 rather than 404.\n *\n * The super-admin assertions hold under either queue strategy: each route's\n * `QUEUE_STRATEGY=async` check sits after the lookup, so `local` yields the pre-existing\n * 400 \u2014 never 404.\n */\ntest.describe('TC-SCHED-008: system-scoped schedule access on trigger and executions', () => {\n test('super admin reaches the schedule on both routes; a non-super-admin is forbidden', async ({ request }) => {\n const superToken = await getAuthToken(request, 'superadmin')\n const adminToken = await getAuthToken(request, 'admin')\n let scheduleId: string | null = null\n\n try {\n // Creating a system-scoped schedule is itself super-admin only.\n scheduleId = await createScheduleJob(request, superToken, {\n name: uniqueScheduleName('System-Trigger-Test'),\n scopeType: 'system',\n scheduleType: 'interval',\n scheduleValue: '1h',\n })\n\n const superResponse = await apiRequest(request, 'POST', SCHEDULER_TRIGGER_PATH, {\n token: superToken,\n data: { id: scheduleId },\n })\n const superBody = await readJsonSafe<TriggerBody>(superResponse)\n expect(\n superResponse.status(),\n 'a super admin must not be told a system-scoped schedule does not exist',\n ).not.toBe(404)\n\n if (isAsyncQueueStrategy) {\n expect(superResponse.status()).toBe(200)\n expect(superBody?.ok).toBe(true)\n expect(typeof superBody?.jobId === 'string' && superBody.jobId.length > 0).toBe(true)\n } else {\n // The strategy check runs after the scope check, so this 400 is the response the\n // 404 used to mask.\n expect(superResponse.status()).toBe(400)\n expect(superBody?.error ?? '').toMatch(/async/i)\n }\n\n // The same schedule is visible enough to be refused, not hidden, from a tenant admin.\n const adminResponse = await apiRequest(request, 'POST', SCHEDULER_TRIGGER_PATH, {\n token: adminToken,\n data: { id: scheduleId },\n })\n expect(\n adminResponse.status(),\n 'a non-super-admin must be forbidden from triggering a system-scoped schedule',\n ).toBe(403)\n\n // The execution-history route carried the same lookup and needs the same guarantees.\n const executionsPath = `${SCHEDULER_JOBS_PATH}/${scheduleId}/executions`\n const superExecutions = await apiRequest(request, 'GET', executionsPath, { token: superToken })\n expect(\n superExecutions.status(),\n 'a super admin must not be told a system-scoped schedule has no execution history route',\n ).not.toBe(404)\n expect(superExecutions.status()).toBe(isAsyncQueueStrategy ? 200 : 400)\n\n const adminExecutions = await apiRequest(request, 'GET', executionsPath, { token: adminToken })\n expect(\n adminExecutions.status(),\n 'a non-super-admin must be forbidden from reading a system-scoped execution history',\n ).toBe(403)\n } finally {\n await deleteScheduleJob(request, superToken, scheduleId)\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,wBAAwB,QAAQ,IAAI,kBAAkB,aAAa;AAkBzE,KAAK,SAAS,yEAAyE,MAAM;AAC3F,OAAK,mFAAmF,OAAO,EAAE,QAAQ,MAAM;AAC7G,UAAM,aAAa,MAAM,aAAa,SAAS,YAAY;AAC3D,UAAM,aAAa,MAAM,aAAa,SAAS,OAAO;AACtD,QAAI,aAA4B;AAEhC,QAAI;AAEF,mBAAa,MAAM,kBAAkB,SAAS,YAAY;AAAA,QACxD,MAAM,mBAAmB,qBAAqB;AAAA,QAC9C,WAAW;AAAA,QACX,cAAc;AAAA,QACd,eAAe;AAAA,MACjB,CAAC;AAED,YAAM,gBAAgB,MAAM,WAAW,SAAS,QAAQ,wBAAwB;AAAA,QAC9E,OAAO;AAAA,QACP,MAAM,EAAE,IAAI,WAAW;AAAA,MACzB,CAAC;AACD,YAAM,YAAY,MAAM,aAA0B,aAAa;AAC/D;AAAA,QACE,cAAc,OAAO;AAAA,QACrB;AAAA,MACF,EAAE,IAAI,KAAK,GAAG;AAEd,UAAI,sBAAsB;AACxB,eAAO,cAAc,OAAO,CAAC,EAAE,KAAK,GAAG;AACvC,eAAO,WAAW,EAAE,EAAE,KAAK,IAAI;AAC/B,eAAO,OAAO,WAAW,UAAU,YAAY,UAAU,MAAM,SAAS,CAAC,EAAE,KAAK,IAAI;AAAA,MACtF,OAAO;AAGL,eAAO,cAAc,OAAO,CAAC,EAAE,KAAK,GAAG;AACvC,eAAO,WAAW,SAAS,EAAE,EAAE,QAAQ,QAAQ;AAAA,MACjD;AAGA,YAAM,gBAAgB,MAAM,WAAW,SAAS,QAAQ,wBAAwB;AAAA,QAC9E,OAAO;AAAA,QACP,MAAM,EAAE,IAAI,WAAW;AAAA,MACzB,CAAC;AACD;AAAA,QACE,cAAc,OAAO;AAAA,QACrB;AAAA,MACF,EAAE,KAAK,GAAG;AAGV,YAAM,iBAAiB,GAAG,mBAAmB,IAAI,UAAU;AAC3D,YAAM,kBAAkB,MAAM,WAAW,SAAS,OAAO,gBAAgB,EAAE,OAAO,WAAW,CAAC;AAC9F;AAAA,QACE,gBAAgB,OAAO;AAAA,QACvB;AAAA,MACF,EAAE,IAAI,KAAK,GAAG;AACd,aAAO,gBAAgB,OAAO,CAAC,EAAE,KAAK,uBAAuB,MAAM,GAAG;AAEtE,YAAM,kBAAkB,MAAM,WAAW,SAAS,OAAO,gBAAgB,EAAE,OAAO,WAAW,CAAC;AAC9F;AAAA,QACE,gBAAgB,OAAO;AAAA,QACvB;AAAA,MACF,EAAE,KAAK,GAAG;AAAA,IACZ,UAAE;AACA,YAAM,kBAAkB,SAAS,YAAY,UAAU;AAAA,IACzD;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { ScheduledJob } from "../../../../data/entities.js";
6
+ import { resolveScheduleAccess } from "../../../../lib/scheduleAccess.js";
6
7
  import { getRedisUrlOrThrow, parseRedisUrl } from "@open-mercato/shared/lib/redis/connection";
7
8
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
8
9
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -21,22 +22,15 @@ async function GET(req, { params }) {
21
22
  const em = container.resolve("em");
22
23
  const scheduleId = params.id;
23
24
  try {
24
- const findFilter = {
25
- id: scheduleId,
26
- deletedAt: null
27
- };
28
- if (auth.tenantId) {
29
- findFilter.tenantId = auth.tenantId;
30
- }
31
- if (auth.orgId) {
32
- findFilter.organizationId = auth.orgId;
33
- }
34
- const schedule = await em.findOne(ScheduledJob, findFilter);
25
+ const schedule = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null });
35
26
  if (!schedule) {
36
27
  return NextResponse.json({ error: translate("scheduler.error.not_found", "Schedule not found") }, { status: 404 });
37
28
  }
38
- const isSuperAdmin = auth.isSuperAdmin === true;
39
- if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
29
+ const access = resolveScheduleAccess(schedule, auth);
30
+ if (access === "not_found") {
31
+ return NextResponse.json({ error: translate("scheduler.error.not_found", "Schedule not found") }, { status: 404 });
32
+ }
33
+ if (access === "forbidden") {
40
34
  return NextResponse.json({ error: translate("scheduler.error.access_denied", "Access denied") }, { status: 403 });
41
35
  }
42
36
  const queueStrategy = process.env.QUEUE_STRATEGY || "local";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/scheduler/api/jobs/%5Bid%5D/executions/route.ts"],
4
- "sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { ScheduledJob } from '../../../../data/entities.js'\nimport { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'executions' })\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/jobs/[id]/executions\n * Fetch execution history for a schedule from BullMQ\n * \n * Returns jobs from the scheduler-execution queue filtered by scheduleId.\n * This replaces the old /api/scheduler/runs endpoint that used the database table.\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { id: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n const scheduleId = params.id\n\n try {\n // Verify schedule exists and user has access (with tenant/org scope filter)\n const findFilter: Record<string, unknown> = {\n id: scheduleId,\n deletedAt: null,\n }\n\n // Apply tenant isolation: scope the query to the user's tenant/org\n if (auth.tenantId) {\n findFilter.tenantId = auth.tenantId\n }\n if (auth.orgId) {\n findFilter.organizationId = auth.orgId\n }\n\n const schedule = await em.findOne(ScheduledJob, findFilter)\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n // System-scoped schedules (no tenantId/orgId) require super-admin. Use the\n // immutable `isSuperAdmin` flag \u2014 never compare mutable/spoofable role names.\n const isSuperAdmin = auth.isSuperAdmin === true\n if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.async_strategy_required', 'Execution history requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.async_strategy_hint', 'Please set QUEUE_STRATEGY=async to view execution history'),\n items: [],\n }, { status: 400 })\n }\n\n // Fetch jobs from BullMQ scheduler-execution queue\n const { Queue } = await import('bullmq')\n const queue = new Queue('scheduler-execution', {\n connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),\n })\n\n try {\n // Validate query params with Zod schema\n const queryResult = executionsQuerySchema.safeParse({\n pageSize: req.nextUrl.searchParams.get('pageSize') ?? undefined,\n })\n const limit = queryResult.success ? queryResult.data.pageSize : 20\n\n const [completed, failed, active, waiting, delayed] = await Promise.all([\n queue.getCompleted(0, limit - 1),\n queue.getFailed(0, limit - 1),\n queue.getActive(0, limit - 1),\n queue.getWaiting(0, limit - 1),\n queue.getDelayed(0, limit - 1),\n ])\n\n // Combine all jobs and filter by scheduleId\n const allJobs = [...completed, ...failed, ...active, ...waiting, ...delayed]\n type BullJobData = { payload?: { scheduleId?: string; triggerType?: string; triggeredByUserId?: string }; scheduleId?: string; triggerType?: string; triggeredByUserId?: string }\n\n const filteredJobs = allJobs\n .filter(job => {\n const data = job.data as BullJobData | undefined\n return data?.payload?.scheduleId === scheduleId || data?.scheduleId === scheduleId\n })\n .slice(0, limit)\n\n // Get state for each job (parallel)\n const jobsWithState = await Promise.all(\n filteredJobs.map(async (job) => {\n const state = await job.getState()\n const data = job.data as BullJobData | undefined\n \n return {\n id: job.id,\n scheduleId: data?.payload?.scheduleId || data?.scheduleId,\n startedAt: job.processedOn ? new Date(job.processedOn).toISOString() : new Date(job.timestamp).toISOString(),\n finishedAt: job.finishedOn ? new Date(job.finishedOn).toISOString() : null,\n status: state === 'completed' ? 'completed' : state === 'failed' ? 'failed' : state === 'active' ? 'running' : 'waiting',\n triggerType: data?.payload?.triggerType || data?.triggerType || 'scheduled',\n triggeredByUserId: data?.payload?.triggeredByUserId || data?.triggeredByUserId || null,\n errorMessage: job.failedReason || null,\n errorStack: job.stacktrace ? job.stacktrace.join('\\n') : null,\n durationMs: (job.finishedOn && job.processedOn) ? (job.finishedOn - job.processedOn) : null,\n queueJobId: job.id,\n queueName: 'scheduler-execution',\n attemptsMade: job.attemptsMade,\n result: job.returnvalue,\n }\n })\n )\n\n // Sort by startedAt descending (most recent first)\n jobsWithState.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())\n\n return NextResponse.json({\n items: jobsWithState,\n total: jobsWithState.length,\n page: 1,\n pageSize: limit,\n })\n } finally {\n await queue.close()\n }\n\n } catch (error: unknown) {\n logger.error('Error fetching execution history', { err: error })\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_executions_failed', 'Failed to fetch execution history') },\n { status: 500 }\n )\n }\n}\n\n// Query schemas\nconst executionsQuerySchema = z.object({\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n})\n\n// Response schemas\nconst executionItemSchema = z.object({\n id: z.string(),\n scheduleId: z.string().uuid(),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n status: z.enum(['running', 'completed', 'failed', 'waiting']),\n triggerType: z.enum(['scheduled', 'manual']),\n triggeredByUserId: z.string().uuid().nullable(),\n errorMessage: z.string().nullable(),\n errorStack: z.string().nullable(),\n durationMs: z.number().nullable(),\n queueJobId: z.string(),\n queueName: z.string(),\n attemptsMade: z.number(),\n result: z.unknown().nullable(),\n})\n\nconst executionsResponseSchema = z.object({\n items: z.array(executionItemSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n items: z.array(z.any()).optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Get execution history',\n description: 'Fetches recent execution history for a scheduled job from BullMQ.',\n methods: {\n GET: {\n operationId: 'getScheduleExecutions',\n summary: 'Get execution history for a schedule',\n description: 'Fetch recent executions from BullMQ for a scheduled job. Requires QUEUE_STRATEGY=async.',\n query: executionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Execution history',\n schema: executionsResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Schedule not found', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,qBAAqB;AAClD,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,aAAa,CAAC;AAGnE,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AASA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,KAAK;AACd,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,gCAAgC,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAChH;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAuB,IAAI;AAEhD,QAAM,aAAa,OAAO;AAE1B,MAAI;AAEF,UAAM,aAAsC;AAAA,MAC1C,IAAI;AAAA,MACJ,WAAW;AAAA,IACb;AAGA,QAAI,KAAK,UAAU;AACjB,iBAAW,WAAW,KAAK;AAAA,IAC7B;AACA,QAAI,KAAK,OAAO;AACd,iBAAW,iBAAiB,KAAK;AAAA,IACnC;AAEA,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,UAAU;AAE1D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,6BAA6B,oBAAoB,EAAE,GAAG,EAAE,QAAQ,IAAI,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;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAAA,EAChB,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,SAAS;AACnC,CAAC;AAGM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS;AAAA,IACP,KAAK;AAAA,MACH,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,oBAAoB;AAAA,QACxF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { ScheduledJob } from '../../../../data/entities.js'\nimport { resolveScheduleAccess } from '../../../../lib/scheduleAccess.js'\nimport { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'executions' })\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/jobs/[id]/executions\n * Fetch execution history for a schedule from BullMQ\n * \n * Returns jobs from the scheduler-execution queue filtered by scheduleId.\n * This replaces the old /api/scheduler/runs endpoint that used the database table.\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { id: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n const scheduleId = params.id\n\n try {\n // Load by id alone, then apply isolation to the loaded row. Folding the actor's\n // tenant/org into the lookup would make every system-scoped schedule unmatchable.\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n const access = resolveScheduleAccess(schedule, auth)\n if (access === 'not_found') {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n if (access === 'forbidden') {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.async_strategy_required', 'Execution history requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.async_strategy_hint', 'Please set QUEUE_STRATEGY=async to view execution history'),\n items: [],\n }, { status: 400 })\n }\n\n // Fetch jobs from BullMQ scheduler-execution queue\n const { Queue } = await import('bullmq')\n const queue = new Queue('scheduler-execution', {\n connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),\n })\n\n try {\n // Validate query params with Zod schema\n const queryResult = executionsQuerySchema.safeParse({\n pageSize: req.nextUrl.searchParams.get('pageSize') ?? undefined,\n })\n const limit = queryResult.success ? queryResult.data.pageSize : 20\n\n const [completed, failed, active, waiting, delayed] = await Promise.all([\n queue.getCompleted(0, limit - 1),\n queue.getFailed(0, limit - 1),\n queue.getActive(0, limit - 1),\n queue.getWaiting(0, limit - 1),\n queue.getDelayed(0, limit - 1),\n ])\n\n // Combine all jobs and filter by scheduleId\n const allJobs = [...completed, ...failed, ...active, ...waiting, ...delayed]\n type BullJobData = { payload?: { scheduleId?: string; triggerType?: string; triggeredByUserId?: string }; scheduleId?: string; triggerType?: string; triggeredByUserId?: string }\n\n const filteredJobs = allJobs\n .filter(job => {\n const data = job.data as BullJobData | undefined\n return data?.payload?.scheduleId === scheduleId || data?.scheduleId === scheduleId\n })\n .slice(0, limit)\n\n // Get state for each job (parallel)\n const jobsWithState = await Promise.all(\n filteredJobs.map(async (job) => {\n const state = await job.getState()\n const data = job.data as BullJobData | undefined\n \n return {\n id: job.id,\n scheduleId: data?.payload?.scheduleId || data?.scheduleId,\n startedAt: job.processedOn ? new Date(job.processedOn).toISOString() : new Date(job.timestamp).toISOString(),\n finishedAt: job.finishedOn ? new Date(job.finishedOn).toISOString() : null,\n status: state === 'completed' ? 'completed' : state === 'failed' ? 'failed' : state === 'active' ? 'running' : 'waiting',\n triggerType: data?.payload?.triggerType || data?.triggerType || 'scheduled',\n triggeredByUserId: data?.payload?.triggeredByUserId || data?.triggeredByUserId || null,\n errorMessage: job.failedReason || null,\n errorStack: job.stacktrace ? job.stacktrace.join('\\n') : null,\n durationMs: (job.finishedOn && job.processedOn) ? (job.finishedOn - job.processedOn) : null,\n queueJobId: job.id,\n queueName: 'scheduler-execution',\n attemptsMade: job.attemptsMade,\n result: job.returnvalue,\n }\n })\n )\n\n // Sort by startedAt descending (most recent first)\n jobsWithState.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())\n\n return NextResponse.json({\n items: jobsWithState,\n total: jobsWithState.length,\n page: 1,\n pageSize: limit,\n })\n } finally {\n await queue.close()\n }\n\n } catch (error: unknown) {\n logger.error('Error fetching execution history', { err: error })\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_executions_failed', 'Failed to fetch execution history') },\n { status: 500 }\n )\n }\n}\n\n// Query schemas\nconst executionsQuerySchema = z.object({\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n})\n\n// Response schemas\nconst executionItemSchema = z.object({\n id: z.string(),\n scheduleId: z.string().uuid(),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n status: z.enum(['running', 'completed', 'failed', 'waiting']),\n triggerType: z.enum(['scheduled', 'manual']),\n triggeredByUserId: z.string().uuid().nullable(),\n errorMessage: z.string().nullable(),\n errorStack: z.string().nullable(),\n durationMs: z.number().nullable(),\n queueJobId: z.string(),\n queueName: z.string(),\n attemptsMade: z.number(),\n result: z.unknown().nullable(),\n})\n\nconst executionsResponseSchema = z.object({\n items: z.array(executionItemSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n items: z.array(z.any()).optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Get execution history',\n description: 'Fetches recent execution history for a scheduled job from BullMQ.',\n methods: {\n GET: {\n operationId: 'getScheduleExecutions',\n summary: 'Get execution history for a schedule',\n description: 'Fetch recent executions from BullMQ for a scheduled job. Requires QUEUE_STRATEGY=async.',\n query: executionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Execution history',\n schema: executionsResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Schedule not found', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8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b,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,oBAAoB;AAAA,QACxF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { createQueue } from "@open-mercato/queue";
6
6
  import { getRedisUrlOrThrow } from "@open-mercato/shared/lib/redis/connection";
7
7
  import { ScheduledJob } from "../../data/entities.js";
8
+ import { resolveScheduleAccess } from "../../lib/scheduleAccess.js";
8
9
  import { scheduleTriggerSchema } from "../../data/validators.js";
9
10
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
10
11
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -24,22 +25,15 @@ async function POST(req) {
24
25
  try {
25
26
  const body = await req.json();
26
27
  const input = scheduleTriggerSchema.parse(body);
27
- const findFilter = {
28
- id: input.id,
29
- deletedAt: null
30
- };
31
- if (auth.tenantId) {
32
- findFilter.tenantId = auth.tenantId;
33
- }
34
- if (auth.orgId) {
35
- findFilter.organizationId = auth.orgId;
36
- }
37
- const schedule = await em.findOne(ScheduledJob, findFilter);
28
+ const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null });
38
29
  if (!schedule) {
39
30
  return NextResponse.json({ error: translate("scheduler.error.not_found", "Schedule not found") }, { status: 404 });
40
31
  }
41
- const isSuperAdmin = auth.isSuperAdmin === true;
42
- if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
32
+ const access = resolveScheduleAccess(schedule, auth);
33
+ if (access === "not_found") {
34
+ return NextResponse.json({ error: translate("scheduler.error.not_found", "Schedule not found") }, { status: 404 });
35
+ }
36
+ if (access === "forbidden") {
43
37
  return NextResponse.json({ error: translate("scheduler.error.access_denied", "Access denied") }, { status: 403 });
44
38
  }
45
39
  const queueStrategy = process.env.QUEUE_STRATEGY || "local";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/scheduler/api/trigger/route.ts"],
4
- "sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { ScheduledJob } from '../../data/entities.js'\nimport { scheduleTriggerSchema } from '../../data/validators.js'\nimport type { ExecuteSchedulePayload } from '../../workers/execute-schedule.worker.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'trigger' })\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.trigger'],\n}\n\n/**\n * POST /api/scheduler/trigger\n * Manually trigger a schedule\n * \n * This enqueues the schedule execution job in BullMQ.\n * Execution history is tracked in BullMQ job state.\n */\nexport async function POST(req: NextRequest) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n try {\n const body = await req.json()\n const input = scheduleTriggerSchema.parse(body)\n\n // Find the schedule with tenant/org scope filter\n const findFilter: Record<string, unknown> = {\n id: input.id,\n deletedAt: null,\n }\n\n // Apply tenant isolation: scope the query to the user's tenant/org\n if (auth.tenantId) {\n findFilter.tenantId = auth.tenantId\n }\n if (auth.orgId) {\n findFilter.organizationId = auth.orgId\n }\n\n const schedule = await em.findOne(ScheduledJob, findFilter)\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n // System-scoped schedules (no tenantId/orgId) require super-admin. Use the\n // immutable `isSuperAdmin` flag \u2014 never compare mutable/spoofable role names.\n const isSuperAdmin = auth.isSuperAdmin === true\n if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async queue strategy\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n \n if (queueStrategy !== 'async') {\n return NextResponse.json(\n { \n error: translate('scheduler.error.trigger_async_required', 'Manual trigger requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.trigger_async_hint', 'Execution history and manual triggers are only available with BullMQ (async strategy)')\n },\n { status: 400 }\n )\n }\n\n // Enqueue execution job to scheduler-execution queue\n const executionQueue = createQueue<ExecuteSchedulePayload>('scheduler-execution', queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n const payload: ExecuteSchedulePayload = {\n scheduleId: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scopeType: schedule.scopeType,\n triggerType: 'manual',\n triggeredByUserId: auth.sub,\n }\n\n const jobId = await executionQueue.enqueue(payload)\n await executionQueue.close()\n\n logger.info('Manually triggered schedule', {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n jobId,\n triggeredBy: auth.sub,\n })\n\n return NextResponse.json({\n ok: true,\n jobId, // BullMQ job ID\n message: translate('scheduler.success.triggered', 'Schedule queued for execution'),\n })\n\n } catch (error) {\n logger.error('Manual trigger failed', { err: error })\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.trigger_failed', 'Failed to trigger schedule') },\n { status: 400 }\n )\n }\n}\n\n// Response schemas\nconst triggerResponseSchema = z.object({\n ok: z.boolean(),\n jobId: z.string(),\n message: z.string(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Manually trigger a schedule',\n description: 'Execute a schedule immediately by enqueueing it in the scheduler-execution queue. Requires QUEUE_STRATEGY=async.',\n methods: {\n POST: {\n operationId: 'triggerScheduledJob',\n summary: 'Manually trigger a schedule',\n description: 'Executes a scheduled job immediately, bypassing the scheduled time. Only works with async queue strategy.',\n requestBody: {\n schema: scheduleTriggerSchema,\n contentType: 'application/json',\n },\n responses: [\n {\n status: 200,\n description: 'Schedule triggered successfully',\n schema: triggerResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request or local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Schedule not found', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AAEtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAEhE,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,wBAAwB;AAC5C;AASA,eAAsB,KAAK,KAAk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;AAAA,QACX,QAAQ;AAAA,QACR,aAAa;AAAA,MACf;AAAA,MACA,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,oBAAoB;AAAA,QAC3G,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { ScheduledJob } from '../../data/entities.js'\nimport { resolveScheduleAccess } from '../../lib/scheduleAccess.js'\nimport { scheduleTriggerSchema } from '../../data/validators.js'\nimport type { ExecuteSchedulePayload } from '../../workers/execute-schedule.worker.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'trigger' })\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.trigger'],\n}\n\n/**\n * POST /api/scheduler/trigger\n * Manually trigger a schedule\n * \n * This enqueues the schedule execution job in BullMQ.\n * Execution history is tracked in BullMQ job state.\n */\nexport async function POST(req: NextRequest) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n try {\n const body = await req.json()\n const input = scheduleTriggerSchema.parse(body)\n\n // Load by id alone, then apply isolation to the loaded row. Folding the actor's\n // tenant/org into the lookup would make every system-scoped schedule unmatchable.\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n const access = resolveScheduleAccess(schedule, auth)\n if (access === 'not_found') {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n if (access === 'forbidden') {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async queue strategy\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n \n if (queueStrategy !== 'async') {\n return NextResponse.json(\n { \n error: translate('scheduler.error.trigger_async_required', 'Manual trigger requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.trigger_async_hint', 'Execution history and manual triggers are only available with BullMQ (async strategy)')\n },\n { status: 400 }\n )\n }\n\n // Enqueue execution job to scheduler-execution queue\n const executionQueue = createQueue<ExecuteSchedulePayload>('scheduler-execution', queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n const payload: ExecuteSchedulePayload = {\n scheduleId: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scopeType: schedule.scopeType,\n triggerType: 'manual',\n triggeredByUserId: auth.sub,\n }\n\n const jobId = await executionQueue.enqueue(payload)\n await executionQueue.close()\n\n logger.info('Manually triggered schedule', {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n jobId,\n triggeredBy: auth.sub,\n })\n\n return NextResponse.json({\n ok: true,\n jobId, // BullMQ job ID\n message: translate('scheduler.success.triggered', 'Schedule queued for execution'),\n })\n\n } catch (error) {\n logger.error('Manual trigger failed', { err: error })\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.trigger_failed', 'Failed to trigger schedule') },\n { status: 400 }\n )\n }\n}\n\n// Response schemas\nconst triggerResponseSchema = z.object({\n ok: z.boolean(),\n jobId: z.string(),\n message: z.string(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Manually trigger a schedule',\n description: 'Execute a schedule immediately by enqueueing it in the scheduler-execution queue. Requires QUEUE_STRATEGY=async.',\n methods: {\n POST: {\n operationId: 'triggerScheduledJob',\n summary: 'Manually trigger a schedule',\n description: 'Executes a scheduled job immediately, bypassing the scheduled time. Only works with async queue strategy.',\n requestBody: {\n schema: scheduleTriggerSchema,\n contentType: 'application/json',\n },\n responses: [\n {\n status: 200,\n description: 'Schedule triggered successfully',\n schema: triggerResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request or local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Schedule not found', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AAEtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAEhE,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,wBAAwB;AAC5C;AASA,eAAsB,KAAK,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A,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,oBAAoB;AAAA,QAC3G,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,22 @@
1
+ function resolveScheduleAccess(schedule, actor) {
2
+ const isSuperAdmin = actor?.isSuperAdmin === true;
3
+ const scheduleTenantId = schedule.tenantId ?? null;
4
+ const actorTenantId = actor?.tenantId ?? null;
5
+ if (schedule.scopeType === "system" || scheduleTenantId === null) {
6
+ if (isSuperAdmin) return "allowed";
7
+ if (scheduleTenantId !== null && scheduleTenantId !== actorTenantId) return "not_found";
8
+ return "forbidden";
9
+ }
10
+ if (actorTenantId === null) return "not_found";
11
+ if (scheduleTenantId !== actorTenantId) return "not_found";
12
+ const scheduleOrganizationId = schedule.organizationId ?? null;
13
+ const actorOrganizationId = actor?.orgId ?? null;
14
+ if (scheduleOrganizationId !== null && actorOrganizationId !== null && scheduleOrganizationId !== actorOrganizationId) {
15
+ return "not_found";
16
+ }
17
+ return "allowed";
18
+ }
19
+ export {
20
+ resolveScheduleAccess
21
+ };
22
+ //# sourceMappingURL=scheduleAccess.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/lib/scheduleAccess.ts"],
4
+ "sourcesContent": ["export type ScheduleScopeActor = {\n tenantId?: string | null\n orgId?: string | null\n isSuperAdmin?: boolean\n}\n\nexport type ScheduleScopeType = 'system' | 'organization' | 'tenant'\n\n/**\n * The scope columns of a loaded `ScheduledJob` row. Every field is optional because the\n * entity declares them that way (`tenantId?: string | null`), so a required shape here\n * could not accept the row the routes actually load.\n *\n * `undefined` is therefore normalized to `null` on read. That is fail-closed where it\n * matters: an absent `tenantId` classifies the row as system-scoped, which restricts it to\n * super admins rather than widening it. An absent `organizationId` reads as \"not bound to an\n * organization\", the same as an explicit null, which is what the list endpoint's tenant\n * branch already treats as tenant-wide.\n */\nexport type ScheduleScopeSubject = {\n scopeType?: ScheduleScopeType | null\n tenantId?: string | null\n organizationId?: string | null\n}\n\nexport type ScheduleAccessDecision = 'allowed' | 'not_found' | 'forbidden'\n\n/**\n * Decides whether an actor may act on a single schedule that was loaded by id alone.\n *\n * Isolation belongs here, on the loaded row, and never in the `where` clause: a\n * system-scoped schedule carries a null `tenantId`, so folding the actor's tenant into the\n * lookup makes that row unmatchable and turns every system-scope check below into dead code.\n * `commands/jobs.ts` (update/delete) and `api/jobs/buildFilters.ts` (list) already model\n * visibility this way.\n *\n * System scope is classified exactly as `ensureCanManageSystemScopedJob` classifies it \u2014\n * `scopeType === 'system' || tenantId == null` \u2014 so update, delete, trigger and executions\n * cannot disagree about what a system-scoped row is. `organizationId` deliberately plays no\n * part in that test: a row with a null tenant is system-scoped whether or not an\n * organization is set, which is how the create validator's scope refinement and the two\n * command guards already read it.\n *\n * `not_found` vs `forbidden` is deliberate. Another tenant's or another organization's\n * schedule answers `not_found`, because a 403 would confirm that the id exists. Only a\n * system-scoped schedule answers `forbidden` \u2014 its existence is a property of the\n * deployment, not of a tenant.\n *\n * An unresolved actor tenant fails closed for everyone, super admins included, matching\n * `buildSchedulerJobsFilters`, which returns an unmatchable filter when the tenant is\n * falsy. Such an actor cannot see a tenant-bound schedule in the list either.\n *\n * Super-admin status reads the immutable `isSuperAdmin` flag derived from RoleAcl/UserAcl at\n * session resolution. Never compare role names, which are tenant-mutable and spoofable.\n *\n * Organization isolation compares the actor's single `orgId`, where the list endpoint uses\n * the resolved organization scope (`filterIds`: the selected organization plus its\n * descendants). The two diverge in **both** directions, and the second is the permissive one:\n *\n * - Narrower: an actor whose scope spans several organizations sees those rows in the list\n * but is answered `not_found` here.\n * - Wider: an actor carrying no `orgId` at all reaches any org-bound row inside its tenant,\n * because the organization comparison below short-circuits \u2014 while the list hides those\n * rows entirely, emitting its organization branch only when at least one id is known.\n *\n * Both directions are inherited from the lookup this helper replaces, which compared the same\n * single id and omitted the clause entirely when it was absent. They are preserved rather\n * than corrected here, because widening or narrowing silently would change access the\n * previous lookup granted; reconciling the two paths is tracked separately.\n */\nexport function resolveScheduleAccess(\n schedule: ScheduleScopeSubject,\n actor: ScheduleScopeActor | null | undefined,\n): ScheduleAccessDecision {\n const isSuperAdmin = actor?.isSuperAdmin === true\n const scheduleTenantId = schedule.tenantId ?? null\n\n const actorTenantId = actor?.tenantId ?? null\n\n if (schedule.scopeType === 'system' || scheduleTenantId === null) {\n if (isSuperAdmin) return 'allowed'\n // A row mislabelled `system` while still bound to a tenant must not confirm its\n // existence across a tenant boundary \u2014 answering 403 there would tell an actor in one\n // tenant that the id exists in another, which is the disclosure the `not_found`\n // decisions below exist to prevent. Only a genuinely tenant-less row answers 403.\n if (scheduleTenantId !== null && scheduleTenantId !== actorTenantId) return 'not_found'\n return 'forbidden'\n }\n\n if (actorTenantId === null) return 'not_found'\n if (scheduleTenantId !== actorTenantId) return 'not_found'\n\n // Unlike the list endpoint's equivalent branch, which pins `scope_type = 'tenant'`\n // (buildFilters.ts), an org-null row is reachable here whatever its `scopeType`. Same\n // scope-inconsistent-row class as above and equally not producible by the create path;\n // left loose deliberately rather than diverging from the pre-existing lookup.\n const scheduleOrganizationId = schedule.organizationId ?? null\n const actorOrganizationId = actor?.orgId ?? null\n if (scheduleOrganizationId !== null && actorOrganizationId !== null && scheduleOrganizationId !== actorOrganizationId) {\n return 'not_found'\n }\n\n return 'allowed'\n}\n"],
5
+ "mappings": "AAsEO,SAAS,sBACd,UACA,OACwB;AACxB,QAAM,eAAe,OAAO,iBAAiB;AAC7C,QAAM,mBAAmB,SAAS,YAAY;AAE9C,QAAM,gBAAgB,OAAO,YAAY;AAEzC,MAAI,SAAS,cAAc,YAAY,qBAAqB,MAAM;AAChE,QAAI,aAAc,QAAO;AAKzB,QAAI,qBAAqB,QAAQ,qBAAqB,cAAe,QAAO;AAC5E,WAAO;AAAA,EACT;AAEA,MAAI,kBAAkB,KAAM,QAAO;AACnC,MAAI,qBAAqB,cAAe,QAAO;AAM/C,QAAM,yBAAyB,SAAS,kBAAkB;AAC1D,QAAM,sBAAsB,OAAO,SAAS;AAC5C,MAAI,2BAA2B,QAAQ,wBAAwB,QAAQ,2BAA2B,qBAAqB;AACrH,WAAO;AAAA,EACT;AAEA,SAAO;AACT;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.6.8-develop.7016.1.4ed7b1e49d",
3
+ "version": "0.6.8-develop.7020.1.d14d757582",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,13 +59,13 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.6.8-develop.7016.1.4ed7b1e49d",
63
- "@open-mercato/queue": "0.6.8-develop.7016.1.4ed7b1e49d",
62
+ "@open-mercato/events": "0.6.8-develop.7020.1.d14d757582",
63
+ "@open-mercato/queue": "0.6.8-develop.7020.1.d14d757582",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.6.8-develop.7016.1.4ed7b1e49d",
68
+ "@open-mercato/shared": "0.6.8-develop.7020.1.d14d757582",
69
69
  "bullmq": "^5.0.0 || ^6.0.0",
70
70
  "ioredis": "^5.0.0 || ^6.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.6.8-develop.7016.1.4ed7b1e49d",
82
+ "@open-mercato/shared": "0.6.8-develop.7020.1.d14d757582",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.1.2",
85
85
  "jest": "^30.4.2",
@@ -0,0 +1,94 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+ import {
5
+ SCHEDULER_JOBS_PATH,
6
+ SCHEDULER_TRIGGER_PATH,
7
+ createScheduleJob,
8
+ deleteScheduleJob,
9
+ uniqueScheduleName,
10
+ } from './helpers/scheduler'
11
+
12
+ const isAsyncQueueStrategy = (process.env.QUEUE_STRATEGY || 'local') === 'async'
13
+
14
+ type TriggerBody = { ok?: boolean; jobId?: string; error?: string; message?: string }
15
+
16
+ /**
17
+ * TC-SCHED-008: POST /api/scheduler/trigger and GET /api/scheduler/jobs/[id]/executions
18
+ * resolve the scope of a system-scoped schedule on the loaded row, not in the lookup.
19
+ *
20
+ * A system-scoped schedule has `tenantId === null` and `organizationId === null`. When both
21
+ * routes folded the caller's tenant/org into the `where` clause, no such row could ever match
22
+ * and every caller — super admins included — got 404, which also masked each route's own
23
+ * super-admin gate. A super admin must now reach the schedule, and a non-super-admin must be
24
+ * told 403 rather than 404.
25
+ *
26
+ * The super-admin assertions hold under either queue strategy: each route's
27
+ * `QUEUE_STRATEGY=async` check sits after the lookup, so `local` yields the pre-existing
28
+ * 400 — never 404.
29
+ */
30
+ test.describe('TC-SCHED-008: system-scoped schedule access on trigger and executions', () => {
31
+ test('super admin reaches the schedule on both routes; a non-super-admin is forbidden', async ({ request }) => {
32
+ const superToken = await getAuthToken(request, 'superadmin')
33
+ const adminToken = await getAuthToken(request, 'admin')
34
+ let scheduleId: string | null = null
35
+
36
+ try {
37
+ // Creating a system-scoped schedule is itself super-admin only.
38
+ scheduleId = await createScheduleJob(request, superToken, {
39
+ name: uniqueScheduleName('System-Trigger-Test'),
40
+ scopeType: 'system',
41
+ scheduleType: 'interval',
42
+ scheduleValue: '1h',
43
+ })
44
+
45
+ const superResponse = await apiRequest(request, 'POST', SCHEDULER_TRIGGER_PATH, {
46
+ token: superToken,
47
+ data: { id: scheduleId },
48
+ })
49
+ const superBody = await readJsonSafe<TriggerBody>(superResponse)
50
+ expect(
51
+ superResponse.status(),
52
+ 'a super admin must not be told a system-scoped schedule does not exist',
53
+ ).not.toBe(404)
54
+
55
+ if (isAsyncQueueStrategy) {
56
+ expect(superResponse.status()).toBe(200)
57
+ expect(superBody?.ok).toBe(true)
58
+ expect(typeof superBody?.jobId === 'string' && superBody.jobId.length > 0).toBe(true)
59
+ } else {
60
+ // The strategy check runs after the scope check, so this 400 is the response the
61
+ // 404 used to mask.
62
+ expect(superResponse.status()).toBe(400)
63
+ expect(superBody?.error ?? '').toMatch(/async/i)
64
+ }
65
+
66
+ // The same schedule is visible enough to be refused, not hidden, from a tenant admin.
67
+ const adminResponse = await apiRequest(request, 'POST', SCHEDULER_TRIGGER_PATH, {
68
+ token: adminToken,
69
+ data: { id: scheduleId },
70
+ })
71
+ expect(
72
+ adminResponse.status(),
73
+ 'a non-super-admin must be forbidden from triggering a system-scoped schedule',
74
+ ).toBe(403)
75
+
76
+ // The execution-history route carried the same lookup and needs the same guarantees.
77
+ const executionsPath = `${SCHEDULER_JOBS_PATH}/${scheduleId}/executions`
78
+ const superExecutions = await apiRequest(request, 'GET', executionsPath, { token: superToken })
79
+ expect(
80
+ superExecutions.status(),
81
+ 'a super admin must not be told a system-scoped schedule has no execution history route',
82
+ ).not.toBe(404)
83
+ expect(superExecutions.status()).toBe(isAsyncQueueStrategy ? 200 : 400)
84
+
85
+ const adminExecutions = await apiRequest(request, 'GET', executionsPath, { token: adminToken })
86
+ expect(
87
+ adminExecutions.status(),
88
+ 'a non-super-admin must be forbidden from reading a system-scoped execution history',
89
+ ).toBe(403)
90
+ } finally {
91
+ await deleteScheduleJob(request, superToken, scheduleId)
92
+ }
93
+ })
94
+ })
@@ -5,6 +5,7 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
5
5
  import type { EntityManager } from '@mikro-orm/core'
6
6
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
7
7
  import { ScheduledJob } from '../../../../data/entities.js'
8
+ import { resolveScheduleAccess } from '../../../../lib/scheduleAccess.js'
8
9
  import { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'
9
10
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
10
11
  import { createLogger } from '@open-mercato/shared/lib/logger'
@@ -40,30 +41,19 @@ export async function GET(
40
41
  const scheduleId = params.id
41
42
 
42
43
  try {
43
- // Verify schedule exists and user has access (with tenant/org scope filter)
44
- const findFilter: Record<string, unknown> = {
45
- id: scheduleId,
46
- deletedAt: null,
47
- }
48
-
49
- // Apply tenant isolation: scope the query to the user's tenant/org
50
- if (auth.tenantId) {
51
- findFilter.tenantId = auth.tenantId
52
- }
53
- if (auth.orgId) {
54
- findFilter.organizationId = auth.orgId
55
- }
56
-
57
- const schedule = await em.findOne(ScheduledJob, findFilter)
44
+ // Load by id alone, then apply isolation to the loaded row. Folding the actor's
45
+ // tenant/org into the lookup would make every system-scoped schedule unmatchable.
46
+ const schedule = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })
58
47
 
59
48
  if (!schedule) {
60
49
  return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })
61
50
  }
62
51
 
63
- // System-scoped schedules (no tenantId/orgId) require super-admin. Use the
64
- // immutable `isSuperAdmin` flag — never compare mutable/spoofable role names.
65
- const isSuperAdmin = auth.isSuperAdmin === true
66
- if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
52
+ const access = resolveScheduleAccess(schedule, auth)
53
+ if (access === 'not_found') {
54
+ return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })
55
+ }
56
+ if (access === 'forbidden') {
67
57
  return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })
68
58
  }
69
59
 
@@ -7,6 +7,7 @@ import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
7
7
  import { createQueue } from '@open-mercato/queue'
8
8
  import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
9
9
  import { ScheduledJob } from '../../data/entities.js'
10
+ import { resolveScheduleAccess } from '../../lib/scheduleAccess.js'
10
11
  import { scheduleTriggerSchema } from '../../data/validators.js'
11
12
  import type { ExecuteSchedulePayload } from '../../workers/execute-schedule.worker.js'
12
13
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
@@ -40,30 +41,19 @@ export async function POST(req: NextRequest) {
40
41
  const body = await req.json()
41
42
  const input = scheduleTriggerSchema.parse(body)
42
43
 
43
- // Find the schedule with tenant/org scope filter
44
- const findFilter: Record<string, unknown> = {
45
- id: input.id,
46
- deletedAt: null,
47
- }
48
-
49
- // Apply tenant isolation: scope the query to the user's tenant/org
50
- if (auth.tenantId) {
51
- findFilter.tenantId = auth.tenantId
52
- }
53
- if (auth.orgId) {
54
- findFilter.organizationId = auth.orgId
55
- }
56
-
57
- const schedule = await em.findOne(ScheduledJob, findFilter)
44
+ // Load by id alone, then apply isolation to the loaded row. Folding the actor's
45
+ // tenant/org into the lookup would make every system-scoped schedule unmatchable.
46
+ const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })
58
47
 
59
48
  if (!schedule) {
60
49
  return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })
61
50
  }
62
51
 
63
- // System-scoped schedules (no tenantId/orgId) require super-admin. Use the
64
- // immutable `isSuperAdmin` flag — never compare mutable/spoofable role names.
65
- const isSuperAdmin = auth.isSuperAdmin === true
66
- if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
52
+ const access = resolveScheduleAccess(schedule, auth)
53
+ if (access === 'not_found') {
54
+ return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })
55
+ }
56
+ if (access === 'forbidden') {
67
57
  return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })
68
58
  }
69
59
 
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Regression test for the manual-trigger 404 on system-scoped schedules.
3
+ *
4
+ * `POST /api/scheduler/trigger` and `GET /api/scheduler/jobs/[id]/executions` used to fold
5
+ * the actor's tenant/org into the lookup, so a schedule with `tenantId === null` and
6
+ * `organizationId === null` never matched and both routes answered 404 — for a super admin
7
+ * too — leaving their own system-scope branch unreachable. This exercises the real
8
+ * `resolveScheduleAccess` both routes now call.
9
+ */
10
+
11
+ import { describe, it, expect } from '@jest/globals'
12
+ import { resolveScheduleAccess, type ScheduleScopeSubject } from '../scheduleAccess'
13
+
14
+ const systemSchedule: ScheduleScopeSubject = { scopeType: 'system', tenantId: null, organizationId: null }
15
+ const tenantSchedule: ScheduleScopeSubject = { scopeType: 'tenant', tenantId: 't1', organizationId: null }
16
+ const orgSchedule: ScheduleScopeSubject = { scopeType: 'organization', tenantId: 't1', organizationId: 'o1' }
17
+
18
+ describe('resolveScheduleAccess — system-scoped schedules', () => {
19
+ it('allows a super admin whose session carries a tenant and an organization', () => {
20
+ expect(
21
+ resolveScheduleAccess(systemSchedule, { tenantId: 't1', orgId: 'o1', isSuperAdmin: true }),
22
+ ).toBe('allowed')
23
+ })
24
+
25
+ it('allows a super admin whose session carries no tenant', () => {
26
+ expect(
27
+ resolveScheduleAccess(systemSchedule, { tenantId: null, orgId: null, isSuperAdmin: true }),
28
+ ).toBe('allowed')
29
+ })
30
+
31
+ it('forbids a non-super-admin instead of hiding the schedule behind a 404', () => {
32
+ expect(
33
+ resolveScheduleAccess(systemSchedule, { tenantId: 't1', orgId: 'o1', isSuperAdmin: false }),
34
+ ).toBe('forbidden')
35
+ })
36
+
37
+ it('forbids an actor missing the isSuperAdmin flag even when a role is named "superadmin"', () => {
38
+ expect(
39
+ resolveScheduleAccess(systemSchedule, { tenantId: 't1', orgId: 'o1' }),
40
+ ).toBe('forbidden')
41
+ })
42
+
43
+ it('forbids an unauthenticated-shaped actor', () => {
44
+ expect(resolveScheduleAccess(systemSchedule, null)).toBe('forbidden')
45
+ })
46
+ })
47
+
48
+ /**
49
+ * `ensureCanManageSystemScopedJob` in commands/jobs.ts treats a row as system-scoped when
50
+ * `scopeType === 'system' || tenantId == null`. Update, delete, trigger and executions must
51
+ * not disagree about what a system-scoped row is, so the same test is applied here — including
52
+ * for the inconsistent rows the create validator's scope refinement should never produce.
53
+ */
54
+ describe('resolveScheduleAccess — system-scope classification matches commands/jobs.ts', () => {
55
+ it('treats a null tenant as system-scoped even when an organization is set', () => {
56
+ expect(
57
+ resolveScheduleAccess(
58
+ { scopeType: 'organization', tenantId: null, organizationId: 'o1' },
59
+ { tenantId: 't1', orgId: 'o1', isSuperAdmin: false },
60
+ ),
61
+ ).toBe('forbidden')
62
+ })
63
+
64
+ it('treats scopeType "system" as system-scoped even when a tenant is set', () => {
65
+ expect(
66
+ resolveScheduleAccess(
67
+ { scopeType: 'system', tenantId: 't1', organizationId: null },
68
+ { tenantId: 't1', orgId: 'o1', isSuperAdmin: false },
69
+ ),
70
+ ).toBe('forbidden')
71
+ })
72
+
73
+ // 403 here would tell an actor in t1 that the id exists in t2. Only a genuinely
74
+ // tenant-less row is allowed to answer `forbidden`.
75
+ it('does not disclose a tenant-bound "system" row across a tenant boundary', () => {
76
+ expect(
77
+ resolveScheduleAccess(
78
+ { scopeType: 'system', tenantId: 't2', organizationId: null },
79
+ { tenantId: 't1', orgId: 'o1', isSuperAdmin: false },
80
+ ),
81
+ ).toBe('not_found')
82
+ })
83
+
84
+ it('still classifies by nullability when scopeType is absent', () => {
85
+ expect(
86
+ resolveScheduleAccess({ tenantId: null, organizationId: null }, { tenantId: 't1', isSuperAdmin: false }),
87
+ ).toBe('forbidden')
88
+ })
89
+ })
90
+
91
+ describe('resolveScheduleAccess — tenant isolation', () => {
92
+ it('reports another tenant\'s schedule as not_found, never forbidden', () => {
93
+ expect(
94
+ resolveScheduleAccess(orgSchedule, { tenantId: 't2', orgId: 'o2', isSuperAdmin: false }),
95
+ ).toBe('not_found')
96
+ })
97
+
98
+ it('hides another tenant\'s schedule from a super admin scoped to a different tenant', () => {
99
+ expect(
100
+ resolveScheduleAccess(orgSchedule, { tenantId: 't2', orgId: 'o2', isSuperAdmin: true }),
101
+ ).toBe('not_found')
102
+ })
103
+
104
+ it('fails closed for a non-super-admin whose tenant could not be resolved', () => {
105
+ expect(
106
+ resolveScheduleAccess(orgSchedule, { tenantId: null, orgId: null, isSuperAdmin: false }),
107
+ ).toBe('not_found')
108
+ })
109
+
110
+ // The exact shape the replaced lookup leaked: with no tenant clause applied, the filter
111
+ // `{ id, deletedAt: null, organizationId: 'o1' }` matched org-bound rows in ANY tenant.
112
+ it('closes the cross-tenant leak for an actor with an org but no resolvable tenant', () => {
113
+ expect(
114
+ resolveScheduleAccess(
115
+ { scopeType: 'organization', tenantId: 't2', organizationId: 'o1' },
116
+ { tenantId: null, orgId: 'o1', isSuperAdmin: false },
117
+ ),
118
+ ).toBe('not_found')
119
+ })
120
+
121
+ // buildSchedulerJobsFilters returns an unmatchable filter when the tenant is falsy, for
122
+ // super admins too, so such an actor cannot see this row in the list either.
123
+ it('fails closed for a super admin whose tenant could not be resolved', () => {
124
+ expect(
125
+ resolveScheduleAccess(orgSchedule, { tenantId: null, orgId: null, isSuperAdmin: true }),
126
+ ).toBe('not_found')
127
+ })
128
+ })
129
+
130
+ describe('resolveScheduleAccess — organization isolation', () => {
131
+ it('reports another organization\'s schedule in the same tenant as not_found', () => {
132
+ expect(
133
+ resolveScheduleAccess(orgSchedule, { tenantId: 't1', orgId: 'o2', isSuperAdmin: false }),
134
+ ).toBe('not_found')
135
+ })
136
+
137
+ it('allows the owning organization', () => {
138
+ expect(
139
+ resolveScheduleAccess(orgSchedule, { tenantId: 't1', orgId: 'o1', isSuperAdmin: false }),
140
+ ).toBe('allowed')
141
+ })
142
+
143
+ // Inherited from the lookup this helper replaces, which omitted the organization clause
144
+ // entirely when the actor carried no orgId. The list endpoint hides the row in this case
145
+ // (its organization branch needs at least one id), so the two paths disagree. Pinned here
146
+ // to document the divergence, not to endorse it — narrowing it is a separate change.
147
+ it('allows an actor with no selected organization to reach an org-bound schedule in its tenant', () => {
148
+ expect(
149
+ resolveScheduleAccess(orgSchedule, { tenantId: 't1', orgId: null, isSuperAdmin: false }),
150
+ ).toBe('allowed')
151
+ })
152
+
153
+ it('keeps a tenant-scoped schedule visible to an org-bound actor in that tenant', () => {
154
+ expect(
155
+ resolveScheduleAccess(tenantSchedule, { tenantId: 't1', orgId: 'o1', isSuperAdmin: false }),
156
+ ).toBe('allowed')
157
+ })
158
+
159
+ it('does not treat an undefined organizationId as a distinct organization', () => {
160
+ expect(
161
+ resolveScheduleAccess({ scopeType: 'tenant', tenantId: 't1' }, { tenantId: 't1', orgId: 'o1', isSuperAdmin: false }),
162
+ ).toBe('allowed')
163
+ })
164
+ })
@@ -0,0 +1,104 @@
1
+ export type ScheduleScopeActor = {
2
+ tenantId?: string | null
3
+ orgId?: string | null
4
+ isSuperAdmin?: boolean
5
+ }
6
+
7
+ export type ScheduleScopeType = 'system' | 'organization' | 'tenant'
8
+
9
+ /**
10
+ * The scope columns of a loaded `ScheduledJob` row. Every field is optional because the
11
+ * entity declares them that way (`tenantId?: string | null`), so a required shape here
12
+ * could not accept the row the routes actually load.
13
+ *
14
+ * `undefined` is therefore normalized to `null` on read. That is fail-closed where it
15
+ * matters: an absent `tenantId` classifies the row as system-scoped, which restricts it to
16
+ * super admins rather than widening it. An absent `organizationId` reads as "not bound to an
17
+ * organization", the same as an explicit null, which is what the list endpoint's tenant
18
+ * branch already treats as tenant-wide.
19
+ */
20
+ export type ScheduleScopeSubject = {
21
+ scopeType?: ScheduleScopeType | null
22
+ tenantId?: string | null
23
+ organizationId?: string | null
24
+ }
25
+
26
+ export type ScheduleAccessDecision = 'allowed' | 'not_found' | 'forbidden'
27
+
28
+ /**
29
+ * Decides whether an actor may act on a single schedule that was loaded by id alone.
30
+ *
31
+ * Isolation belongs here, on the loaded row, and never in the `where` clause: a
32
+ * system-scoped schedule carries a null `tenantId`, so folding the actor's tenant into the
33
+ * lookup makes that row unmatchable and turns every system-scope check below into dead code.
34
+ * `commands/jobs.ts` (update/delete) and `api/jobs/buildFilters.ts` (list) already model
35
+ * visibility this way.
36
+ *
37
+ * System scope is classified exactly as `ensureCanManageSystemScopedJob` classifies it —
38
+ * `scopeType === 'system' || tenantId == null` — so update, delete, trigger and executions
39
+ * cannot disagree about what a system-scoped row is. `organizationId` deliberately plays no
40
+ * part in that test: a row with a null tenant is system-scoped whether or not an
41
+ * organization is set, which is how the create validator's scope refinement and the two
42
+ * command guards already read it.
43
+ *
44
+ * `not_found` vs `forbidden` is deliberate. Another tenant's or another organization's
45
+ * schedule answers `not_found`, because a 403 would confirm that the id exists. Only a
46
+ * system-scoped schedule answers `forbidden` — its existence is a property of the
47
+ * deployment, not of a tenant.
48
+ *
49
+ * An unresolved actor tenant fails closed for everyone, super admins included, matching
50
+ * `buildSchedulerJobsFilters`, which returns an unmatchable filter when the tenant is
51
+ * falsy. Such an actor cannot see a tenant-bound schedule in the list either.
52
+ *
53
+ * Super-admin status reads the immutable `isSuperAdmin` flag derived from RoleAcl/UserAcl at
54
+ * session resolution. Never compare role names, which are tenant-mutable and spoofable.
55
+ *
56
+ * Organization isolation compares the actor's single `orgId`, where the list endpoint uses
57
+ * the resolved organization scope (`filterIds`: the selected organization plus its
58
+ * descendants). The two diverge in **both** directions, and the second is the permissive one:
59
+ *
60
+ * - Narrower: an actor whose scope spans several organizations sees those rows in the list
61
+ * but is answered `not_found` here.
62
+ * - Wider: an actor carrying no `orgId` at all reaches any org-bound row inside its tenant,
63
+ * because the organization comparison below short-circuits — while the list hides those
64
+ * rows entirely, emitting its organization branch only when at least one id is known.
65
+ *
66
+ * Both directions are inherited from the lookup this helper replaces, which compared the same
67
+ * single id and omitted the clause entirely when it was absent. They are preserved rather
68
+ * than corrected here, because widening or narrowing silently would change access the
69
+ * previous lookup granted; reconciling the two paths is tracked separately.
70
+ */
71
+ export function resolveScheduleAccess(
72
+ schedule: ScheduleScopeSubject,
73
+ actor: ScheduleScopeActor | null | undefined,
74
+ ): ScheduleAccessDecision {
75
+ const isSuperAdmin = actor?.isSuperAdmin === true
76
+ const scheduleTenantId = schedule.tenantId ?? null
77
+
78
+ const actorTenantId = actor?.tenantId ?? null
79
+
80
+ if (schedule.scopeType === 'system' || scheduleTenantId === null) {
81
+ if (isSuperAdmin) return 'allowed'
82
+ // A row mislabelled `system` while still bound to a tenant must not confirm its
83
+ // existence across a tenant boundary — answering 403 there would tell an actor in one
84
+ // tenant that the id exists in another, which is the disclosure the `not_found`
85
+ // decisions below exist to prevent. Only a genuinely tenant-less row answers 403.
86
+ if (scheduleTenantId !== null && scheduleTenantId !== actorTenantId) return 'not_found'
87
+ return 'forbidden'
88
+ }
89
+
90
+ if (actorTenantId === null) return 'not_found'
91
+ if (scheduleTenantId !== actorTenantId) return 'not_found'
92
+
93
+ // Unlike the list endpoint's equivalent branch, which pins `scope_type = 'tenant'`
94
+ // (buildFilters.ts), an org-null row is reachable here whatever its `scopeType`. Same
95
+ // scope-inconsistent-row class as above and equally not producible by the create path;
96
+ // left loose deliberately rather than diverging from the pre-existing lookup.
97
+ const scheduleOrganizationId = schedule.organizationId ?? null
98
+ const actorOrganizationId = actor?.orgId ?? null
99
+ if (scheduleOrganizationId !== null && actorOrganizationId !== null && scheduleOrganizationId !== actorOrganizationId) {
100
+ return 'not_found'
101
+ }
102
+
103
+ return 'allowed'
104
+ }