Skip to content

Commit 4cd7685

Browse files
buzz-codeclaude
andauthored
Fix 500 on attendance_cleanup_rule "run now": scope job to the rule's own userId (#157)
* Fix 500 on attendance_cleanup_rule 'run now': scope job to the rule's own userId Production error: QueryFailedError: Field 'user_id' doesn't have a default value INSERT INTO `jobs`(..., `user_id`, ...) VALUES (..., DEFAULT, ...) runNow used getUserIdFromUser(req.auth) as the enqueued job's userId. That's wrong for this action: CrudAuthWithPermissionsFilter grants admins AND anyone with the attendanceCleanupRules permission full visibility (not just their own rows), so a requester can select rules owned by a different user - and for admin specifically, getUserIdFromUser always returns undefined (id -1 is a sentinel, not a real tenant), which is what produced the undefined user_id insert. Fix: load the selected rules and derive the job's userId from each rule's own userId, enqueuing one job per distinct owner so a multi-tenant selection is scoped correctly rather than crashing or silently misattributing the sweep. Reproduced the exact error against a real MySQL jobs table (enqueue(undefined, ...)) and confirmed the fix (enqueue(38, ...)) succeeds. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s * Close cross-tenant data exposure: use standard CrudAuthFilter, not permission-based full visibility Addresses Copilot review comment on this PR, and explicit user direction: CrudAuthWithPermissionsFilter granted ADMIN_FILTER (full visibility, not just-your-own-rows) to anyone with the attendanceCleanupRules permission - and doAction's runNow is a custom route that bypasses @dataui/crud's normal auth-filtered query building entirely, so it never consulted that filter in the first place. Together, any authenticated user could pass arbitrary rule ids to runNow and have jobs enqueued under other tenants' identities. Fix: - crudAuth is now the standard CrudAuthFilter (admin sees all, everyone else sees only their own rows) - same as most other entities. The attendanceCleanupRules permission remains a client-side visibility gate only; it no longer grants any server-side data access. - runNow explicitly applies crudAuth.filter(req.auth) to its id lookup, since this custom route doesn't go through the filtered query path - a non-owned id in the selection just doesn't resolve, instead of being trusted from the request. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s * Use the new BaseEntityService.getManyByIds for runNow's id lookup Simplifies the previous manual crudAuth.filter(req.auth) + raw find() into a call to the new shared helper (nra-server#43), which applies the same auth filtering through the real query-building path instead of duplicating it per action. bump server/shared to 24975d1 to pick up getManyByIds. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e61595e commit 4cd7685

3 files changed

Lines changed: 77 additions & 25 deletions

File tree

‎server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts‎

Lines changed: 56 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CrudRequest } from '@dataui/crud';
2-
import { ADMIN_FILTER, NO_DATA_FILTER } from '@shared/auth/crud-auth.filter';
2+
import { ADMIN_FILTER, CrudAuthFilter } from '@shared/auth/crud-auth.filter';
33
import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity';
44
import attendanceCleanupRuleConfig from '../attendance-cleanup-rule.config';
55

@@ -16,24 +16,21 @@ describe('AttendanceCleanupRuleConfig', () => {
1616
});
1717

1818
describe('crudAuth', () => {
19-
it('grants access to a user with the attendanceCleanupRules permission', () => {
20-
const user = { permissions: { attendanceCleanupRules: true } };
21-
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(ADMIN_FILTER);
19+
// Same as most entities: admin sees everything, everyone else sees only their own
20+
// rows. The attendanceCleanupRules permission gates client-side visibility only - it
21+
// must not grant one user's data to another.
22+
it('uses the standard CrudAuthFilter (admin sees all, others see only their own rows)', () => {
23+
expect(attendanceCleanupRuleConfig.crudAuth).toBe(CrudAuthFilter);
2224
});
2325

24-
it('grants access to an admin regardless of the dedicated permission', () => {
26+
it('grants an admin full visibility', () => {
2527
const user = { permissions: { admin: true } };
2628
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(ADMIN_FILTER);
2729
});
2830

29-
it('denies a user lacking the permission (no rows, not a 403)', () => {
30-
const user = { permissions: {} };
31-
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(NO_DATA_FILTER);
32-
});
33-
34-
it('denies a user with no permissions object at all', () => {
35-
const user = {};
36-
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(NO_DATA_FILTER);
31+
it('scopes a non-admin to their own rows', () => {
32+
const user = { id: 38, permissions: {} };
33+
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual({ userId: 38 });
3734
});
3835
});
3936

@@ -54,19 +51,60 @@ describe('AttendanceCleanupRuleConfig', () => {
5451
return { service, jobService };
5552
}
5653

57-
it('enqueues an attendance-cleanup-sweep job scoped to the selected rule ids', async () => {
58-
const { service, jobService } = makeService();
54+
function makeReq(ids: string, rules: Partial<AttendanceCleanupRule>[]) {
55+
// getManyByIds is what actually applies crudAuth's filter (via createBuilder) - it's
56+
// mocked here rather than re-testing that plumbing, which base-entity.service.spec.ts
57+
// already covers directly.
5958
const req = {
60-
auth: { id: 7 },
61-
parsed: { extra: { action: 'runNow', ids: '1,2' } },
59+
auth: { id: -1, permissions: { admin: true } },
60+
parsed: { extra: { action: 'runNow', ids } },
61+
options: {},
6262
} as unknown as CrudRequest;
63+
return req;
64+
}
65+
66+
it("enqueues a job scoped to the resolved rules' own userId", async () => {
67+
const { service, jobService } = makeService();
68+
jest.spyOn(service, 'getManyByIds').mockResolvedValue([
69+
{ id: 1, userId: 38 },
70+
{ id: 2, userId: 38 },
71+
] as any);
72+
const req = makeReq('1,2', []);
6373

6474
const message = await service.doAction(req, {});
6575

66-
expect(jobService.enqueue).toHaveBeenCalledWith(7, 'attendance-cleanup-sweep', { ruleIds: [1, 2] });
76+
expect(service.getManyByIds).toHaveBeenCalledWith(req, [1, 2]);
77+
expect(jobService.enqueue).toHaveBeenCalledTimes(1);
78+
expect(jobService.enqueue).toHaveBeenCalledWith(38, 'attendance-cleanup-sweep', { ruleIds: [1, 2] });
6779
expect(message).toContain('42');
6880
});
6981

82+
it('enqueues nothing when none of the selected ids resolve for this caller', async () => {
83+
const { service, jobService } = makeService();
84+
jest.spyOn(service, 'getManyByIds').mockResolvedValue([]);
85+
const req = makeReq('99', []); // e.g. owned by someone else, filtered out by crudAuth
86+
87+
const message = await service.doAction(req, {});
88+
89+
expect(jobService.enqueue).not.toHaveBeenCalled();
90+
expect(message).toContain('0');
91+
});
92+
93+
it('enqueues one job per distinct owner when the resolved rules span multiple users', async () => {
94+
const { service, jobService } = makeService();
95+
jest.spyOn(service, 'getManyByIds').mockResolvedValue([
96+
{ id: 1, userId: 38 },
97+
{ id: 2, userId: 39 },
98+
] as any);
99+
const req = makeReq('1,2', []);
100+
101+
await service.doAction(req, {});
102+
103+
expect(jobService.enqueue).toHaveBeenCalledTimes(2);
104+
expect(jobService.enqueue).toHaveBeenCalledWith(38, 'attendance-cleanup-sweep', { ruleIds: [1] });
105+
expect(jobService.enqueue).toHaveBeenCalledWith(39, 'attendance-cleanup-sweep', { ruleIds: [2] });
106+
});
107+
70108
it('falls through to the base doAction for unknown actions', async () => {
71109
const { service } = makeService();
72110
const req = {

‎server/src/entity-modules/attendance-cleanup-rule.config.ts‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { CrudRequest } from '@dataui/crud';
22
import { Repository } from 'typeorm';
3-
import { getUserIdFromUser } from '@shared/auth/auth.util';
4-
import { CrudAuthWithPermissionsFilter } from '@shared/auth/crud-auth.filter';
3+
import { CrudAuthFilter } from '@shared/auth/crud-auth.filter';
54
import { BaseEntityService } from '@shared/base-entity/base-entity.service';
65
import { BaseEntityModuleOptions, Entity, InjectEntityRepository } from '@shared/base-entity/interface';
76
import { MailSendService } from '@shared/utils/mail/mail-send.service';
@@ -22,10 +21,22 @@ class AttendanceCleanupRuleService<T extends Entity | AttendanceCleanupRule> ext
2221
const extra = req.parsed.extra as any;
2322
switch (extra.action) {
2423
case 'runNow': {
25-
const userId = getUserIdFromUser(req.auth);
2624
const ruleIds = getAsNumberArray(extra.ids) ?? [];
27-
const job = await this.jobService.enqueue(userId, 'attendance-cleanup-sweep', { ruleIds });
28-
return `נוצרה משימת ניקוי נוכחות (מזהה ${job.id})`;
25+
// getManyByIds applies crudAuth's filter (already merged into req.parsed.search
26+
// by CrudRequestInterceptor) - a non-owned id in the selection simply doesn't
27+
// come back, instead of being trusted from the request.
28+
const rules = (await this.getManyByIds(req, ruleIds)) as unknown as AttendanceCleanupRule[];
29+
// Admin sees everyone, so a selection can still span multiple owners - scope
30+
// each enqueued job to its own rule subset.
31+
const userIds = [...new Set(rules.map((rule) => rule.userId))];
32+
const jobs = await Promise.all(
33+
userIds.map((userId) =>
34+
this.jobService.enqueue(userId, 'attendance-cleanup-sweep', {
35+
ruleIds: rules.filter((rule) => rule.userId === userId).map((rule) => rule.id),
36+
}),
37+
),
38+
);
39+
return `נוצרו ${jobs.length} משימות ניקוי נוכחות (מזהים: ${jobs.map((job) => job.id).join(', ')})`;
2940
}
3041
}
3142
return super.doAction(req, body);
@@ -35,7 +46,10 @@ class AttendanceCleanupRuleService<T extends Entity | AttendanceCleanupRule> ext
3546
function getConfig(): BaseEntityModuleOptions {
3647
return {
3748
entity: AttendanceCleanupRule,
38-
crudAuth: CrudAuthWithPermissionsFilter(permissions => permissions?.attendanceCleanupRules),
49+
// Same auth as most entities: admin sees everything, everyone else sees only their
50+
// own rows. The attendanceCleanupRules permission only controls whether the client
51+
// shows the resource - it must not grant cross-tenant data visibility.
52+
crudAuth: CrudAuthFilter,
3953
query: {
4054
join: {
4155
lesson: { eager: false },

0 commit comments

Comments
 (0)