Skip to content

Commit 4e39196

Browse files
authored
Merge pull request #2973 from trycompai/main
[comp] Production Deploy
2 parents 2a6a150 + 25f4d11 commit 4e39196

52 files changed

Lines changed: 1681 additions & 516 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/api/src/admin-organizations/admin-policies.controller.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export class AdminPoliciesController {
4444
@Get(':orgId/policies')
4545
@ApiOperation({ summary: 'List all policies for an organization (admin)' })
4646
async list(@Param('orgId') orgId: string) {
47-
return this.policiesService.findAll(orgId);
47+
return this.policiesService.findAll({ organizationId: orgId });
4848
}
4949

5050
@Post(':orgId/policies')

‎apps/api/src/auth/acting-user.service.spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,29 @@ describe('ActingUserResolver', () => {
122122
);
123123
});
124124

125+
it('filters out deactivated / inactive members so uploads cannot be attributed to offboarded owners', async () => {
126+
// Regression guard — without these filters, the oldest "owner"-role
127+
// Member would win even if the user has been deactivated/offboarded,
128+
// attributing API-driven mutations to someone who no longer has access.
129+
mockDb.member.findFirst.mockResolvedValueOnce({ userId: 'usr_owner' });
130+
const req = makeReq({
131+
userId: undefined,
132+
isApiKey: true,
133+
apiKeyName: 'X',
134+
});
135+
136+
await resolver.resolve(req, 'org_1');
137+
138+
expect(mockDb.member.findFirst).toHaveBeenCalledWith(
139+
expect.objectContaining({
140+
where: expect.objectContaining({
141+
deactivated: false,
142+
isActive: true,
143+
}),
144+
}),
145+
);
146+
});
147+
125148
it('picks the OLDEST owner deterministically (orderBy createdAt asc)', async () => {
126149
// Determinism matters — re-running the same automation should always
127150
// attribute to the same user, even if newer owners are added/removed.

‎apps/api/src/auth/acting-user.service.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,21 +91,26 @@ export class ActingUserResolver {
9191
}
9292

9393
/**
94-
* Find the oldest owner of an organization. Oldest is deterministic and
95-
* stable: removing a recently-added owner doesn't change the attribution
94+
* Find the oldest ACTIVE owner of an organization. Oldest is deterministic
95+
* and stable: removing a recently-added owner doesn't change the attribution
9696
* target, removing the oldest one just promotes the next one. Matches the
97-
* pattern used elsewhere (e.g. tasks/task-notifier.service.ts).
97+
* pattern used elsewhere (e.g. tasks/tasks.service.ts:getApiKeyActorUserId).
9898
*
9999
* Member.role is a comma-separated string (e.g. "owner,admin"), so we use
100100
* Prisma's `contains` filter — same query shape as the 19+ other owner
101101
* lookups in this codebase.
102+
*
103+
* `deactivated: false` + `isActive: true` excludes offboarded owners so we
104+
* don't attribute new mutations to a user who no longer has org access.
102105
*/
103106
private async findOrgOwnerUserId(
104107
organizationId: string,
105108
): Promise<string | null> {
106109
const owner = await db.member.findFirst({
107110
where: {
108111
organizationId,
112+
deactivated: false,
113+
isActive: true,
109114
role: { contains: 'owner' },
110115
},
111116
orderBy: { createdAt: 'asc' },
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
jest.mock('@db', () => ({
2+
db: {
3+
device: {
4+
findUnique: jest.fn(),
5+
findFirst: jest.fn(),
6+
update: jest.fn(),
7+
create: jest.fn(),
8+
},
9+
},
10+
}));
11+
12+
import { db } from '@db';
13+
import {
14+
registerWithSerial,
15+
registerWithoutSerial,
16+
} from './device-registration.helpers';
17+
import type { RegisterDeviceDto } from './dto/register-device.dto';
18+
19+
const mockDb = db as jest.Mocked<typeof db>;
20+
21+
const orgId = 'org_test';
22+
const member = { id: 'mem_test' };
23+
24+
function makeDto(
25+
overrides: Partial<RegisterDeviceDto> = {},
26+
): RegisterDeviceDto {
27+
return {
28+
organizationId: orgId,
29+
hostname: 'my-laptop.local',
30+
name: 'My Laptop',
31+
platform: 'macos',
32+
osVersion: '15.0',
33+
serialNumber: 'ABC123',
34+
hardwareModel: 'MacBookPro18,1',
35+
agentVersion: '1.0.0',
36+
...overrides,
37+
};
38+
}
39+
40+
describe('registerWithSerial — orphan adoption', () => {
41+
beforeEach(() => {
42+
jest.clearAllMocks();
43+
});
44+
45+
it('adopts an existing serial-less row for the same hostname+member instead of creating a duplicate', async () => {
46+
// The bug scenario: agent first registered without a serial (e.g. cold-
47+
// boot `system_profiler` returned empty), creating a row with
48+
// serialNumber=null. A later registration succeeds in reading the
49+
// serial. Without adoption, registerWithSerial would create a brand-new
50+
// row and the old one would stay orphaned.
51+
(mockDb.device.findUnique as jest.Mock).mockResolvedValue(null);
52+
(mockDb.device.findFirst as jest.Mock).mockResolvedValue({
53+
id: 'dev_orphan',
54+
});
55+
(mockDb.device.update as jest.Mock).mockResolvedValue({
56+
id: 'dev_orphan',
57+
});
58+
59+
const dto = makeDto();
60+
await registerWithSerial({ member, dto });
61+
62+
expect(mockDb.device.findFirst).toHaveBeenCalledWith({
63+
where: {
64+
hostname: dto.hostname,
65+
memberId: member.id,
66+
organizationId: orgId,
67+
serialNumber: null,
68+
},
69+
select: { id: true },
70+
});
71+
expect(mockDb.device.update).toHaveBeenCalledWith({
72+
where: { id: 'dev_orphan' },
73+
data: expect.objectContaining({
74+
serialNumber: dto.serialNumber,
75+
hostname: dto.hostname,
76+
}),
77+
});
78+
expect(mockDb.device.create).not.toHaveBeenCalled();
79+
});
80+
81+
it('creates a fresh row when no orphan exists', async () => {
82+
(mockDb.device.findUnique as jest.Mock).mockResolvedValue(null);
83+
(mockDb.device.findFirst as jest.Mock).mockResolvedValue(null);
84+
(mockDb.device.create as jest.Mock).mockResolvedValue({ id: 'dev_new' });
85+
86+
const dto = makeDto();
87+
await registerWithSerial({ member, dto });
88+
89+
expect(mockDb.device.update).not.toHaveBeenCalled();
90+
expect(mockDb.device.create).toHaveBeenCalledWith({
91+
data: expect.objectContaining({
92+
serialNumber: dto.serialNumber,
93+
memberId: member.id,
94+
organizationId: orgId,
95+
}),
96+
});
97+
});
98+
99+
it('updates the existing serial-match row without looking for an orphan', async () => {
100+
// Plain re-registration of an already-known device — must not trigger
101+
// the orphan lookup or do anything other than an in-place update.
102+
(mockDb.device.findUnique as jest.Mock).mockResolvedValue({
103+
id: 'dev_existing',
104+
memberId: member.id,
105+
});
106+
(mockDb.device.update as jest.Mock).mockResolvedValue({
107+
id: 'dev_existing',
108+
});
109+
110+
const dto = makeDto();
111+
await registerWithSerial({ member, dto });
112+
113+
expect(mockDb.device.findFirst).not.toHaveBeenCalled();
114+
expect(mockDb.device.create).not.toHaveBeenCalled();
115+
expect(mockDb.device.update).toHaveBeenCalledWith({
116+
where: { id: 'dev_existing' },
117+
data: expect.objectContaining({ hostname: dto.hostname }),
118+
});
119+
});
120+
121+
it('only adopts an orphan that belongs to the same member', async () => {
122+
// Safety: the orphan lookup is scoped by memberId, so another member's
123+
// serial-less row for the same hostname must not be hijacked.
124+
(mockDb.device.findUnique as jest.Mock).mockResolvedValue(null);
125+
(mockDb.device.findFirst as jest.Mock).mockResolvedValue(null);
126+
(mockDb.device.create as jest.Mock).mockResolvedValue({ id: 'dev_new' });
127+
128+
const dto = makeDto();
129+
await registerWithSerial({ member, dto });
130+
131+
const call = (mockDb.device.findFirst as jest.Mock).mock.calls[0]?.[0];
132+
expect(call?.where.memberId).toBe(member.id);
133+
expect(call?.where.serialNumber).toBeNull();
134+
});
135+
});
136+
137+
describe('registerWithoutSerial — unchanged behavior', () => {
138+
beforeEach(() => {
139+
jest.clearAllMocks();
140+
});
141+
142+
it('updates the matching null-serial row when one exists', async () => {
143+
(mockDb.device.findFirst as jest.Mock).mockResolvedValue({
144+
id: 'dev_null',
145+
});
146+
(mockDb.device.update as jest.Mock).mockResolvedValue({ id: 'dev_null' });
147+
148+
const dto = makeDto({ serialNumber: undefined });
149+
await registerWithoutSerial({ member, dto });
150+
151+
expect(mockDb.device.update).toHaveBeenCalledWith({
152+
where: { id: 'dev_null' },
153+
data: expect.any(Object),
154+
});
155+
expect(mockDb.device.create).not.toHaveBeenCalled();
156+
});
157+
});

‎apps/api/src/device-agent/device-registration.helpers.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,33 @@ export async function registerWithSerial({
4646
});
4747
}
4848

49+
// Adopt any prior serial-less registration for the same physical device
50+
// before creating a new row. The agent's serial extraction can return
51+
// undefined on a cold boot (e.g. macOS `system_profiler` cache not yet
52+
// built) and a real value on a subsequent boot — without this, the second
53+
// registration creates a duplicate while the first row stays orphaned and
54+
// never receives another check-in (frozen at its old compliance state).
55+
const orphan = await db.device.findFirst({
56+
where: {
57+
hostname: dto.hostname,
58+
memberId: member.id,
59+
organizationId: dto.organizationId,
60+
serialNumber: null,
61+
},
62+
select: { id: true },
63+
});
64+
65+
if (orphan) {
66+
return db.device.update({
67+
where: { id: orphan.id },
68+
data: {
69+
...updateData,
70+
hostname: dto.hostname,
71+
serialNumber: dto.serialNumber!,
72+
},
73+
});
74+
}
75+
4976
return db.device.create({
5077
data: {
5178
...updateData,

‎apps/api/src/evidence-forms/evidence-forms.controller.spec.ts‎

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
import { Test, TestingModule } from '@nestjs/testing';
2+
import { BadRequestException } from '@nestjs/common';
23
import { EvidenceFormsController } from './evidence-forms.controller';
34
import { EvidenceFormsService } from './evidence-forms.service';
5+
import { ActingUserResolver } from '../auth/acting-user.service';
46
import { HybridAuthGuard } from '../auth/hybrid-auth.guard';
57
import { PermissionGuard } from '../auth/permission.guard';
6-
import type { AuthContext as AuthContextType } from '../auth/types';
8+
import type {
9+
AuthContext as AuthContextType,
10+
AuthenticatedRequest,
11+
} from '../auth/types';
12+
13+
jest.mock('@db', () => ({ db: {} }));
714

815
jest.mock('../auth/auth.server', () => ({
916
auth: { api: { getSession: jest.fn() } },
@@ -61,10 +68,17 @@ describe('EvidenceFormsController', () => {
6168
userRoles: ['admin'],
6269
};
6370

71+
const mockActingUser = {
72+
resolve: jest.fn(),
73+
};
74+
6475
beforeEach(async () => {
6576
const module: TestingModule = await Test.createTestingModule({
6677
controllers: [EvidenceFormsController],
67-
providers: [{ provide: EvidenceFormsService, useValue: mockService }],
78+
providers: [
79+
{ provide: EvidenceFormsService, useValue: mockService },
80+
{ provide: ActingUserResolver, useValue: mockActingUser },
81+
],
6882
})
6983
.overrideGuard(HybridAuthGuard)
7084
.useValue(mockGuard)
@@ -298,26 +312,71 @@ describe('EvidenceFormsController', () => {
298312
});
299313

300314
describe('uploadSubmission', () => {
301-
it('should call service.uploadSubmission with correct params', async () => {
315+
it('should call service.uploadSubmission with the session userId', async () => {
302316
const body = { fileUrl: 'https://example.com/file.pdf' };
303317
const mockResult = { id: 'sub_upload' };
304318
mockService.uploadSubmission.mockResolvedValue(mockResult);
319+
mockActingUser.resolve.mockResolvedValue({
320+
userId: 'user_1',
321+
source: 'session',
322+
});
305323

324+
const req = {} as AuthenticatedRequest;
306325
const result = await controller.uploadSubmission(
307326
'org_1',
308-
mockAuthContext,
309327
'security-awareness',
310328
body,
329+
req,
311330
);
312331

313332
expect(result).toEqual(mockResult);
333+
expect(mockActingUser.resolve).toHaveBeenCalledWith(req, 'org_1');
314334
expect(service.uploadSubmission).toHaveBeenCalledWith({
315335
organizationId: 'org_1',
316336
formType: 'security-awareness',
317-
authContext: mockAuthContext,
337+
userId: 'user_1',
318338
payload: body,
319339
});
320340
});
341+
342+
it('should attribute to the org owner when called with API key auth', async () => {
343+
const body = { fileUrl: 'https://example.com/file.pdf' };
344+
const mockResult = { id: 'sub_upload' };
345+
mockService.uploadSubmission.mockResolvedValue(mockResult);
346+
mockActingUser.resolve.mockResolvedValue({
347+
userId: 'owner_user',
348+
source: 'org-owner-fallback',
349+
callerLabel: 'via API key "CI"',
350+
});
351+
352+
const req = {} as AuthenticatedRequest;
353+
await controller.uploadSubmission('org_1', 'meeting', body, req);
354+
355+
expect(service.uploadSubmission).toHaveBeenCalledWith({
356+
organizationId: 'org_1',
357+
formType: 'meeting',
358+
userId: 'owner_user',
359+
payload: body,
360+
});
361+
});
362+
363+
it('should throw BadRequestException when no owner can be resolved', async () => {
364+
mockActingUser.resolve.mockResolvedValue({
365+
userId: null,
366+
source: 'org-owner-fallback',
367+
callerLabel: 'via API key',
368+
});
369+
370+
await expect(
371+
controller.uploadSubmission(
372+
'org_1',
373+
'meeting',
374+
{ fileUrl: 'x' },
375+
{} as AuthenticatedRequest,
376+
),
377+
).rejects.toBeInstanceOf(BadRequestException);
378+
expect(service.uploadSubmission).not.toHaveBeenCalled();
379+
});
321380
});
322381

323382
describe('reviewSubmission', () => {

0 commit comments

Comments
 (0)