-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathchecks.controller.ts
More file actions
346 lines (314 loc) · 11 KB
/
checks.controller.ts
File metadata and controls
346 lines (314 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import {
Controller,
Get,
Post,
Param,
Body,
HttpException,
HttpStatus,
Logger,
UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiSecurity } from '@nestjs/swagger';
import type { Prisma } from '@prisma/client';
import { HybridAuthGuard } from '../../auth/hybrid-auth.guard';
import { PermissionGuard } from '../../auth/permission.guard';
import { RequirePermission } from '../../auth/require-permission.decorator';
import { OrganizationId } from '../../auth/auth-context.decorator';
import {
getManifest,
getAvailableChecks,
runAllChecks,
} from '@trycompai/integration-platform';
import { ConnectionRepository } from '../repositories/connection.repository';
import { ConnectionService } from '../services/connection.service';
import { CredentialVaultService } from '../services/credential-vault.service';
import { ProviderRepository } from '../repositories/provider.repository';
import { CheckRunRepository } from '../repositories/check-run.repository';
import { getStringValue, toStringCredentials } from '../utils/credential-utils';
interface RunChecksDto {
checkId?: string;
}
@Controller({ path: 'integrations/checks', version: '1' })
@ApiTags('Integrations')
@UseGuards(HybridAuthGuard, PermissionGuard)
@ApiSecurity('apikey')
export class ChecksController {
private readonly logger = new Logger(ChecksController.name);
constructor(
private readonly connectionRepository: ConnectionRepository,
private readonly providerRepository: ProviderRepository,
private readonly credentialVaultService: CredentialVaultService,
private readonly checkRunRepository: CheckRunRepository,
private readonly connectionService: ConnectionService,
) {}
/**
* List available checks for a provider
*/
@Get('providers/:providerSlug')
@RequirePermission('integration', 'read')
async listProviderChecks(@Param('providerSlug') providerSlug: string) {
const manifest = getManifest(providerSlug);
if (!manifest) {
throw new HttpException(
`Provider ${providerSlug} not found`,
HttpStatus.NOT_FOUND,
);
}
return {
providerSlug,
providerName: manifest.name,
checks: getAvailableChecks(manifest),
};
}
/**
* List available checks for a connection
*/
@Get('connections/:connectionId')
@RequirePermission('integration', 'read')
async listConnectionChecks(
@Param('connectionId') connectionId: string,
@OrganizationId() organizationId: string,
) {
await this.connectionService.getConnectionForOrg(connectionId, organizationId);
const connection = await this.connectionRepository.findById(connectionId);
if (!connection) {
throw new HttpException('Connection not found', HttpStatus.NOT_FOUND);
}
const provider = await this.providerRepository.findById(
connection.providerId,
);
if (!provider) {
throw new HttpException('Provider not found', HttpStatus.NOT_FOUND);
}
const manifest = getManifest(provider.slug);
if (!manifest) {
throw new HttpException(
`Manifest for ${provider.slug} not found`,
HttpStatus.NOT_FOUND,
);
}
return {
connectionId,
providerSlug: provider.slug,
providerName: manifest.name,
connectionStatus: connection.status,
checks: getAvailableChecks(manifest),
};
}
/**
* Run checks for a connection
*/
@Post('connections/:connectionId/run')
@RequirePermission('integration', 'update')
async runConnectionChecks(
@Param('connectionId') connectionId: string,
@Body() body: RunChecksDto,
@OrganizationId() organizationId: string,
) {
await this.connectionService.getConnectionForOrg(connectionId, organizationId);
const connection = await this.connectionRepository.findById(connectionId);
if (!connection) {
throw new HttpException('Connection not found', HttpStatus.NOT_FOUND);
}
if (connection.status !== 'active') {
throw new HttpException(
`Connection is not active (status: ${connection.status})`,
HttpStatus.BAD_REQUEST,
);
}
const provider = await this.providerRepository.findById(
connection.providerId,
);
if (!provider) {
throw new HttpException('Provider not found', HttpStatus.NOT_FOUND);
}
const manifest = getManifest(provider.slug);
if (!manifest) {
throw new HttpException(
`Manifest for ${provider.slug} not found`,
HttpStatus.NOT_FOUND,
);
}
if (!manifest.checks || manifest.checks.length === 0) {
throw new HttpException(
`No checks defined for ${provider.slug}`,
HttpStatus.BAD_REQUEST,
);
}
// Get decrypted credentials
const credentials =
await this.credentialVaultService.getDecryptedCredentials(connectionId);
if (!credentials) {
throw new HttpException(
'No credentials found for connection',
HttpStatus.BAD_REQUEST,
);
}
// Validate credentials based on auth type
if (manifest.auth.type === 'oauth2' && !credentials.access_token) {
throw new HttpException(
'No valid OAuth credentials found. Please reconnect.',
HttpStatus.BAD_REQUEST,
);
}
if (manifest.auth.type === 'api_key') {
const apiKeyField = manifest.auth.config.name;
if (!credentials[apiKeyField] && !credentials.api_key) {
throw new HttpException(
'API key not found. Please reconnect the integration.',
HttpStatus.BAD_REQUEST,
);
}
}
if (manifest.auth.type === 'basic') {
const usernameField = manifest.auth.config.usernameField || 'username';
const passwordField = manifest.auth.config.passwordField || 'password';
if (!credentials[usernameField] || !credentials[passwordField]) {
throw new HttpException(
'Username and password required. Please reconnect the integration.',
HttpStatus.BAD_REQUEST,
);
}
}
if (
manifest.auth.type === 'custom' &&
Object.keys(credentials).length === 0
) {
throw new HttpException(
'No valid credentials found for custom integration',
HttpStatus.BAD_REQUEST,
);
}
// Get user-configured variables
const variables =
(connection.variables as Record<
string,
string | number | boolean | string[] | undefined
>) || {};
this.logger.log(
`Running checks for connection ${connectionId} (${provider.slug})${body.checkId ? ` - check: ${body.checkId}` : ''}`,
);
// Create a check run record
const checkRun = await this.checkRunRepository.create({
connectionId,
checkId: body.checkId || 'all',
checkName: body.checkId || 'All Checks',
});
try {
// Run checks
const accessToken = getStringValue(credentials.access_token);
const stringCredentials = toStringCredentials(credentials);
const result = await runAllChecks({
manifest,
accessToken,
credentials: stringCredentials,
variables,
connectionId,
organizationId: connection.organizationId,
checkId: body.checkId,
logger: {
info: (msg, data) => this.logger.log(msg, data),
warn: (msg, data) => this.logger.warn(msg, data),
error: (msg, data) => this.logger.error(msg, data),
},
});
this.logger.log(
`Checks completed for ${connectionId}: ${result.totalFindings} findings, ${result.totalPassing} passing`,
);
// Store all results (findings and passing)
const resultsToStore = result.results.flatMap((checkResult) => [
...checkResult.result.findings.map((finding) => ({
checkRunId: checkRun.id,
passed: false,
title: finding.title,
description: finding.description || '',
resourceType: finding.resourceType,
resourceId: finding.resourceId,
severity: finding.severity,
remediation: finding.remediation,
evidence: JSON.parse(JSON.stringify(finding.evidence || {})),
})),
...checkResult.result.passingResults.map((passing) => ({
checkRunId: checkRun.id,
passed: true,
title: passing.title,
description: passing.description || '',
resourceType: passing.resourceType,
resourceId: passing.resourceId,
severity: 'info' as const,
remediation: undefined,
evidence: JSON.parse(JSON.stringify(passing.evidence || {})),
})),
]);
if (resultsToStore.length > 0) {
await this.checkRunRepository.addResults(resultsToStore);
}
// Collect execution logs from all check results
const allLogs = result.results.flatMap((checkResult) =>
checkResult.result.logs.map((log) => ({
check: checkResult.checkName,
level: log.level,
message: log.message,
...(log.data ? { data: log.data } : {}),
timestamp: log.timestamp.toISOString(),
})),
);
// Update the check run status with logs
const startTime = checkRun.startedAt?.getTime() || Date.now();
await this.checkRunRepository.complete(checkRun.id, {
status: result.totalFindings > 0 ? 'failed' : 'success',
durationMs: Date.now() - startTime,
totalChecked: result.results.length,
passedCount: result.totalPassing,
failedCount: result.totalFindings,
logs: allLogs.length > 0
? (allLogs as unknown as Prisma.InputJsonValue)
: undefined,
});
return {
connectionId,
providerSlug: provider.slug,
checkRunId: checkRun.id,
...result,
};
} catch (error) {
// Mark the check run as failed with error details
const startTime = checkRun.startedAt?.getTime() || Date.now();
const errorMessage = error instanceof Error ? error.message : String(error);
const errorStack = error instanceof Error ? error.stack : undefined;
await this.checkRunRepository.complete(checkRun.id, {
status: 'failed',
durationMs: Date.now() - startTime,
totalChecked: 0,
passedCount: 0,
failedCount: 0,
errorMessage,
logs: [{
check: body.checkId || 'all',
level: 'error',
message: errorMessage,
...(errorStack ? { data: { stack: errorStack } } : {}),
timestamp: new Date().toISOString(),
}] as unknown as Prisma.InputJsonValue,
});
this.logger.error(`Check execution failed: ${error}`);
throw new HttpException(
`Check execution failed: ${errorMessage}`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Run a specific check for a connection
*/
@Post('connections/:connectionId/run/:checkId')
@RequirePermission('integration', 'update')
async runSingleCheck(
@Param('connectionId') connectionId: string,
@Param('checkId') checkId: string,
@OrganizationId() organizationId: string,
) {
return this.runConnectionChecks(connectionId, { checkId }, organizationId);
}
}