diff --git a/.gitignore b/.gitignore index ee424405..244ec89e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ coverage data/ .gitdb/ .env -.claude/.claude-md-review-state \ No newline at end of file +.claude/.claude-md-review-state +code-report-analysis/ \ No newline at end of file diff --git a/src/hooks.server.ts b/src/hooks.server.ts index b13b5402..ce903a3b 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -6,14 +6,17 @@ import { getGitDb } from '$lib/server/gitdb'; getGitDb(); export const handle: Handle = async ({ event, resolve }) => { - if (event.url.pathname === '/login' || event.url.pathname.startsWith('/api/auth/')) { + if ( + event.url.pathname === '/login' || + event.url.pathname.startsWith('/api/auth/') || + event.url.pathname === '/api/code-report/analyse-result' + ) { return resolve(event); } await ensureAuthReady(); await ensureOrganizationReady(); - const sessionCookie = event.cookies.get('pos_session'); const currentUser = await authService.resolveAuthenticatedUser(sessionCookie); @@ -28,7 +31,10 @@ export const handle: Handle = async ({ event, resolve }) => { const organizationSettingsMatch = event.url.pathname.match(/^\/org\/([^/]+)\/settings/); if (organizationSettingsMatch) { const organization = await organizationService.tryFindBySlug(organizationSettingsMatch[1]); - if (!organization || !(await cancanService.canManageOrganization(currentUser, organization.id))) { + if ( + !organization || + !(await cancanService.canManageOrganization(currentUser, organization.id)) + ) { return new Response(null, { status: 302, headers: { location: '/' } }); } } else if ( diff --git a/src/lib/code-report/analysis-summary.ts b/src/lib/code-report/analysis-summary.ts new file mode 100644 index 00000000..9a920315 --- /dev/null +++ b/src/lib/code-report/analysis-summary.ts @@ -0,0 +1,72 @@ +// Best-effort summary for Trivy-style JSON reports (top-level `Results[]`, each entry may +// carry `Vulnerabilities`/`Secrets`/`Packages`). Other tool formats simply yield all-zero counts. +export type AnalysisSummary = { + vulnerabilities: { + critical: number; + high: number; + medium: number; + low: number; + unknown: number; + }; + totalVulnerabilities: number; + exposedSecrets: number; + dependencies: number; + targetsScanned: number; +}; + +function emptySummary(): AnalysisSummary { + return { + vulnerabilities: { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 }, + totalVulnerabilities: 0, + exposedSecrets: 0, + dependencies: 0, + targetsScanned: 0, + }; +} + +export function summarizeAnalysisResult(result: unknown): AnalysisSummary { + const summary = emptySummary(); + + if (!result || typeof result !== 'object') return summary; + + const results = (result as Record).Results; + if (!Array.isArray(results)) return summary; + + const packageNames = new Set(); + summary.targetsScanned = results.length; + + for (const entry of results) { + if (!entry || typeof entry !== 'object') continue; + const row = entry as Record; + + const vulnerabilities = Array.isArray(row.Vulnerabilities) ? row.Vulnerabilities : []; + for (const vuln of vulnerabilities) { + if (!vuln || typeof vuln !== 'object') continue; + const vulnRow = vuln as Record; + summary.totalVulnerabilities += 1; + + const severity = String(vulnRow.Severity || '').toLowerCase(); + if (severity === 'critical') summary.vulnerabilities.critical += 1; + else if (severity === 'high') summary.vulnerabilities.high += 1; + else if (severity === 'medium') summary.vulnerabilities.medium += 1; + else if (severity === 'low') summary.vulnerabilities.low += 1; + else summary.vulnerabilities.unknown += 1; + + if (vulnRow.PkgName) packageNames.add(String(vulnRow.PkgName)); + } + + const secrets = Array.isArray(row.Secrets) ? row.Secrets : []; + summary.exposedSecrets += secrets.length; + + const packages = Array.isArray(row.Packages) ? row.Packages : []; + for (const pkg of packages) { + if (pkg && typeof pkg === 'object' && (pkg as Record).Name) { + packageNames.add(String((pkg as Record).Name)); + } + } + } + + summary.dependencies = packageNames.size; + + return summary; +} diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 2f07d9bf..cad34325 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -35,7 +35,7 @@ export let organizationName: string | null = null; export let projects: { slug: string; - modules?: { vault: boolean; openreport: boolean; stateiac: boolean }; + modules?: { vault: boolean; codereport: boolean; stateiac: boolean }; }[] = []; let currentPath = pathname; @@ -88,7 +88,7 @@ }, ] : []), - ...(currentProject?.modules?.openreport + ...(currentProject?.modules?.codereport ? [ { name: 'Analisis', @@ -97,10 +97,10 @@ name: 'Code Report', icon: BarChart3, items: [ - { label: 'Services', href: `${projectBase}/report/services`, icon: Layers }, - { label: 'History', href: `${projectBase}/report/history`, icon: GitBranch }, - { label: 'GitOps Report Bot', href: `${projectBase}/report/bot`, icon: Bot }, - { label: 'Settings', href: `${projectBase}/report/settings`, icon: Settings }, + { label: 'Services', href: `${projectBase}/code-report/services`, icon: Layers }, + { label: 'History', href: `${projectBase}/code-report/history`, icon: GitBranch }, + { label: 'GitOps Report Bot', href: `${projectBase}/code-report/bot`, icon: Bot }, + { label: 'Settings', href: `${projectBase}/code-report/settings`, icon: Settings }, ], }, ], diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 16f199bc..c4b7f51d 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -41,6 +41,7 @@ export const RoleEntity = entity('roles', { export const ApiKeyEntity = entity('api_keys', { id: uuid().primaryKey(), userId: uuid().notNull(), + projectId: uuid(), name: text().notNull(), keyPrefix: text().notNull(), keyHash: text().notNull(), @@ -102,7 +103,41 @@ export const ProjectEntity = entity('projects', { status: text().notNull().default('active'), modules: json() .notNull() - .$defaultFn(() => ({ vault: true, openreport: true, stateiac: true })), + .$defaultFn(() => ({ vault: true, codereport: true, stateiac: true })), + createdAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), +}); + +export const CodeReportServiceEntity = entity('code_report_services', { + id: uuid().primaryKey(), + projectId: uuid().notNull(), + slug: text().notNull().unique(), + name: text().notNull(), + description: text(), + tags: json() + .notNull() + .$defaultFn(() => []), + createdAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), +}); + +export const CodeReportAnalysisEntity = entity('code_report_analyses', { + id: uuid().primaryKey(), + serviceId: uuid().notNull(), + tool: text().notNull(), + status: text().notNull().default('in_progress'), + result: json(), + summary: json(), + error: text(), + gitInfo: json(), createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), @@ -115,6 +150,19 @@ relations.for(ProjectEntity, ({ one, many }) => ({ roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }), organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), access: many(UserAccessEntity, { fields: ['id'], references: ['projectId'] }), + codeReportServices: many(CodeReportServiceEntity, { + fields: ['id'], + references: ['projectId'], + }), +})); + +relations.for(CodeReportServiceEntity, ({ one, many }) => ({ + project: one(ProjectEntity, { fields: ['projectId'], references: ['id'] }), + analyses: many(CodeReportAnalysisEntity, { fields: ['id'], references: ['serviceId'] }), +})); + +relations.for(CodeReportAnalysisEntity, ({ one }) => ({ + service: one(CodeReportServiceEntity, { fields: ['serviceId'], references: ['id'] }), })); relations.for(RoleEntity, ({ one, many }) => ({ diff --git a/src/modules/auth/application/apikeys.service.test.ts b/src/modules/auth/application/apikeys.service.test.ts index 1ddb7a97..b3e0a0cc 100644 --- a/src/modules/auth/application/apikeys.service.test.ts +++ b/src/modules/auth/application/apikeys.service.test.ts @@ -5,10 +5,14 @@ import type { ApiKeyView } from '../domain/entities'; function createRepositoryMock(): any { return { listByUser: vi.fn(), + listByProject: vi.fn(), findValidByHash: vi.fn(), create: vi.fn(), findById: vi.fn(), + findByIdAny: vi.fn(), revoke: vi.fn(), + revokeAny: vi.fn(), + touchLastUsed: vi.fn(), updateKeyMaterial: vi.fn(), }; } @@ -25,6 +29,7 @@ describe('ApiKeysService', () => { id: 'key-1', name: 'Deploy', keyPrefix: 'gvs_12', + projectId: null, expiresAt: null, lastUsedAt: null, revokedAt: null, @@ -46,6 +51,7 @@ describe('ApiKeysService', () => { id: 'key-1', name: 'Deploy', keyPrefix: 'gvs_12', + projectId: null, expiresAt: null, lastUsedAt: null, revokedAt: null, @@ -95,6 +101,7 @@ describe('ApiKeysService', () => { expect(repository.create).toHaveBeenCalledWith({ id: expect.any(String), userId: 'user-1', + projectId: null, name: 'Deploy', keyPrefix: result.token.slice(0, 6), keyHash: expect.any(String), @@ -109,6 +116,7 @@ describe('ApiKeysService', () => { id: 'key-1', name: 'Deploy', keyPrefix: 'gvs_12', + projectId: null, expiresAt: null, lastUsedAt: null, revokedAt: null, @@ -118,6 +126,7 @@ describe('ApiKeysService', () => { id: 'key-1', name: 'Deploy', keyPrefix: 'gvs_12', + projectId: null, expiresAt: null, lastUsedAt: null, revokedAt: '2026-08-18T00:10:00.000Z', @@ -127,7 +136,9 @@ describe('ApiKeysService', () => { const service = new ApiKeysService(repository); await service.revokeApiKey('user-1', 'key-1'); - await expect(service.revokeApiKey('user-1', 'key-1')).rejects.toThrow('API key is already revoked'); + await expect(service.revokeApiKey('user-1', 'key-1')).rejects.toThrow( + 'API key is already revoked', + ); expect(repository.revoke).toHaveBeenCalledTimes(1); }); @@ -137,6 +148,7 @@ describe('ApiKeysService', () => { id: 'key-1', name: 'Deploy', keyPrefix: 'gvs_old', + projectId: null, expiresAt: '2026-12-31T00:00:00.000Z', lastUsedAt: null, revokedAt: null, @@ -168,6 +180,7 @@ describe('ApiKeysService', () => { id: 'key-1', name: 'Deploy', keyPrefix: 'gvs_old', + projectId: null, expiresAt: null, lastUsedAt: null, revokedAt: '2026-08-18T00:10:00.000Z', @@ -179,4 +192,4 @@ describe('ApiKeysService', () => { await expect(service.regenerateApiKey('user-1', 'key-1')).rejects.toThrow('API key is revoked'); expect(repository.updateKeyMaterial).not.toHaveBeenCalled(); }); -}); \ No newline at end of file +}); diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index dd990ca3..bbc21669 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -1,4 +1,3 @@ - import crypto from 'crypto'; import type { ApiKeyView } from '../domain/entities'; import { ApiKeyRepository } from '../infrastructure/repositories/apikey.repository'; @@ -7,16 +6,17 @@ function hashApiKey(token: string): string { return crypto.createHash('sha256').update(token).digest('hex'); } - export class ApiKeysService { - constructor( - private readonly apiKeyRepository: ApiKeyRepository, - ) {} + constructor(private readonly apiKeyRepository: ApiKeyRepository) {} async listActiveApiKeys(userId: string): Promise { return this.apiKeyRepository.listByUser(userId); } + async listActiveApiKeysByProject(projectId: string): Promise { + return this.apiKeyRepository.listByProject(projectId); + } + async validateApiKey(token: string): Promise { if (!token.trim()) { return false; @@ -26,7 +26,26 @@ export class ApiKeysService { return key !== null; } - async createApiKey(userId: string, name: string, expiresAt: string | null): Promise<{ token: string; key: ApiKeyView }> { + // returns the full key (with projectId) for machine-to-machine endpoints that need to know + // which project issued the key, e.g. POST /api/code-report/analyse-result + async resolveApiKey(token: string): Promise { + if (!token.trim()) { + return null; + } + + const key = await this.apiKeyRepository.findValidByHash(hashApiKey(token)); + if (key) { + await this.apiKeyRepository.touchLastUsed(key.id); + } + return key; + } + + async createApiKey( + userId: string, + name: string, + expiresAt: string | null, + projectId: string | null = null, + ): Promise<{ token: string; key: ApiKeyView }> { const token = `gvs_${crypto.randomBytes(24).toString('hex')}`; const id = crypto.randomUUID(); const keyPrefix = token.slice(0, 6); @@ -34,6 +53,7 @@ export class ApiKeysService { await this.apiKeyRepository.create({ id, userId, + projectId, name, keyPrefix, keyHash: hashApiKey(token), @@ -46,6 +66,7 @@ export class ApiKeysService { id, name, keyPrefix, + projectId, expiresAt, lastUsedAt: null, revokedAt: null, @@ -54,6 +75,16 @@ export class ApiKeysService { }; } + // convenience wrapper for project-scoped server access keys (used by CI/CD integrations) + async createProjectApiKey( + userId: string, + projectId: string, + name: string, + expiresAt: string | null, + ): Promise<{ token: string; key: ApiKeyView }> { + return this.createApiKey(userId, name, expiresAt, projectId); + } + async revokeApiKey(userId: string, keyId: string): Promise { const existing = await this.apiKeyRepository.findById(userId, keyId); @@ -68,7 +99,24 @@ export class ApiKeysService { await this.apiKeyRepository.revoke(userId, keyId); } - async regenerateApiKey(userId: string, keyId: string): Promise<{ token: string; key: ApiKeyView }> { + async revokeProjectApiKey(projectId: string, keyId: string): Promise { + const existing = await this.apiKeyRepository.findByIdAny(keyId); + + if (!existing || existing.projectId !== projectId) { + throw new Error('API key not found'); + } + + if (existing.revokedAt) { + throw new Error('API key is already revoked'); + } + + await this.apiKeyRepository.revokeAny(keyId); + } + + async regenerateApiKey( + userId: string, + keyId: string, + ): Promise<{ token: string; key: ApiKeyView }> { const existing = await this.apiKeyRepository.findById(userId, keyId); if (!existing) { @@ -94,6 +142,7 @@ export class ApiKeysService { id: keyId, name: existing.name, keyPrefix, + projectId: existing.projectId, expiresAt: existing.expiresAt, lastUsedAt: null, revokedAt: null, @@ -101,5 +150,4 @@ export class ApiKeysService { }, }; } - -} \ No newline at end of file +} diff --git a/src/modules/auth/application/profile.service.test.ts b/src/modules/auth/application/profile.service.test.ts index f044c102..daf85c45 100644 --- a/src/modules/auth/application/profile.service.test.ts +++ b/src/modules/auth/application/profile.service.test.ts @@ -122,8 +122,10 @@ describe('ProfileService', () => { userRepository.findById.mockResolvedValue(null); - await expect(service.changePassword('missing-user', 'current-pass', 'new-pass')).resolves.toBe(false); + await expect(service.changePassword('missing-user', 'current-pass', 'new-pass')).resolves.toBe( + false, + ); expect(passwordService.verifyPassword).not.toHaveBeenCalled(); expect(userRepository.updatePassword).not.toHaveBeenCalled(); }); -}); \ No newline at end of file +}); diff --git a/src/modules/auth/application/profile.service.ts b/src/modules/auth/application/profile.service.ts index 9922b503..17165f4f 100644 --- a/src/modules/auth/application/profile.service.ts +++ b/src/modules/auth/application/profile.service.ts @@ -20,7 +20,11 @@ export class ProfileService { await this.userRepository.updateEmail(userId, email); } - async changePassword(userId: string, currentPassword: string, newPassword: string): Promise { + async changePassword( + userId: string, + currentPassword: string, + newPassword: string, + ): Promise { const user = await this.userRepository.findById(userId); if (!user) { return false; @@ -30,7 +34,10 @@ export class ProfileService { return false; } - await this.userRepository.updatePassword(userId, this.passwordService.hashPassword(newPassword)); + await this.userRepository.updatePassword( + userId, + this.passwordService.hashPassword(newPassword), + ); return true; } } diff --git a/src/modules/auth/application/user.service.ts b/src/modules/auth/application/user.service.ts index 34c50d8b..73ff404d 100644 --- a/src/modules/auth/application/user.service.ts +++ b/src/modules/auth/application/user.service.ts @@ -58,11 +58,9 @@ export class UserService { // if (input.targetUserId === input.actorUserId && input.role !== 'admin') { // throw new Error('You cannot remove your own admin role.'); // } - // if (input.role !== 'admin') { // await this.ensureNotRemovingLastAdmin(input.targetUserId); // } - // await this.userRepository.updateRole(input.targetUserId, input.role); } } diff --git a/src/modules/auth/domain/apikey.domain.ts b/src/modules/auth/domain/apikey.domain.ts index dd402ada..6f209b60 100644 --- a/src/modules/auth/domain/apikey.domain.ts +++ b/src/modules/auth/domain/apikey.domain.ts @@ -1,25 +1,25 @@ import { Domain } from './domain'; export class ApiKeyDomain extends Domain { - public name: string = '' - public slug: string = '' - public permissions: object = {} + public name: string = ''; + public slug: string = ''; + public permissions: object = {}; - constructor(data: any) { - super(data); - this.name = data.name - this.slug = data.slug - this.permissions = data.permissions - } + constructor(data: any) { + super(data); + this.name = data.name; + this.slug = data.slug; + this.permissions = data.permissions; + } - toJson() { - return { - id: this.id, - name: this.name, - slug: this.slug, - permissions: this.permissions, - createdAt: this.createdAt, - updatedAt: this.updatedAt - } - } -} \ No newline at end of file + toJson() { + return { + id: this.id, + name: this.name, + slug: this.slug, + permissions: this.permissions, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} diff --git a/src/modules/auth/domain/domain.ts b/src/modules/auth/domain/domain.ts index f4c2fc6c..e49efe22 100644 --- a/src/modules/auth/domain/domain.ts +++ b/src/modules/auth/domain/domain.ts @@ -1,15 +1,14 @@ - export class Domain { - public id: string = '' - public createdAt: Date = new Date() - public updatedAt: Date = new Date() + public id: string = ''; + public createdAt: Date = new Date(); + public updatedAt: Date = new Date(); - constructor(data: any) { - this.id = data.id - this.createdAt = new Date(data.createdAt) - this.updatedAt = new Date(data.updatedAt) - } - toJson() { - return JSON.parse(JSON.stringify(this)); - } -} \ No newline at end of file + constructor(data: any) { + this.id = data.id; + this.createdAt = new Date(data.createdAt); + this.updatedAt = new Date(data.updatedAt); + } + toJson() { + return JSON.parse(JSON.stringify(this)); + } +} diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index 3a36053f..b9a637b6 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -66,6 +66,7 @@ export type ApiKeyView = { id: string; name: string; keyPrefix: string; + projectId: string | null; expiresAt: string | null; lastUsedAt: string | null; revokedAt: string | null; diff --git a/src/modules/auth/domain/repositories.ts b/src/modules/auth/domain/repositories.ts index 37874fce..2d60bb7c 100644 --- a/src/modules/auth/domain/repositories.ts +++ b/src/modules/auth/domain/repositories.ts @@ -15,13 +15,15 @@ export interface AuthUserRepository { updateRole(userId: string, role: Role): Promise; deleteById(userId: string): Promise; countAdmins(): Promise; - listActiveApiKeys(userId: string): Promise>; + listActiveApiKeys(userId: string): Promise< + Array<{ + id: string; + name: string; + keyPrefix: string; + lastUsedAt: string | null; + createdAt: string; + }> + >; createApiKey(input: { id: string; userId: string; diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.ts index 160a575b..eb8c4f0e 100644 --- a/src/modules/auth/infrastructure/repositories/apikey.repository.ts +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.ts @@ -3,102 +3,151 @@ import { ApiKeyEntity } from '$lib/database/schemas'; import type { ApiKeyView } from '../../domain/entities'; type ApiKeyRow = { - id: string; - userId: string; - name: string; - keyPrefix: string; - keyHash: string; - expiresAt: string | null; - lastUsedAt: string | null; - revokedAt: string | null; - createdAt: string; + id: string; + userId: string; + projectId: string | null; + name: string; + keyPrefix: string; + keyHash: string; + expiresAt: string | null; + lastUsedAt: string | null; + revokedAt: string | null; + createdAt: string; }; export class ApiKeyRepository extends Repository { + async listByUser(userId: string): Promise { + const result = await this.db + .select() + .from(ApiKeyEntity) + .where({ userId }) + .orderBy('createdAt', 'desc'); - async listByUser(userId: string): Promise { - const result = await this.db.select().from(ApiKeyEntity).where({ userId }).orderBy('createdAt', 'desc'); - - return (result.rows as ApiKeyRow[]).map((row) => this.toJSON(row)); - } - - async findById(userId: string, keyId: string): Promise { - const result = await this.db.select().from(ApiKeyEntity).where({ id: keyId, userId }).limit(1); - const row = result.rows[0] as ApiKeyRow | undefined; - - if (!row) { - return null; - } - - return this.toJSON(row); - } - - async findValidByHash(keyHash: string): Promise { - const result = await this.db.select().from(ApiKeyEntity).where({ keyHash }).limit(1); - const row = result.rows[0] as ApiKeyRow | undefined; - - if (!row || row.revokedAt) { - return null; - } - - if (row.expiresAt && row.expiresAt <= new Date().toISOString()) { - return null; - } - - return this.toJSON(row); - } - - async create(input: { - id: string; - userId: string; - name: string; - keyPrefix: string; - keyHash: string; - expiresAt: string | null; - }): Promise { - await this.db.insert(ApiKeyEntity).values({ - id: input.id, - userId: input.userId, - name: input.name, - keyPrefix: input.keyPrefix, - keyHash: input.keyHash, - expiresAt: input.expiresAt, - lastUsedAt: null, - revokedAt: null, - createdAt: new Date().toISOString(), - }); - } - - async revoke(userId: string, keyId: string): Promise { - await this.db.update(ApiKeyEntity).set({ revokedAt: new Date().toISOString() }).where({ id: keyId, userId }); - } - - async updateKeyMaterial(userId: string, keyId: string, input: { - keyPrefix: string; - keyHash: string; - expiresAt: string | null; - }): Promise { - await this.db - .update(ApiKeyEntity) - .set({ - keyPrefix: input.keyPrefix, - keyHash: input.keyHash, - expiresAt: input.expiresAt, - revokedAt: null, - lastUsedAt: null, - }) - .where({ id: keyId, userId }); - } - - override protected toJSON(row: ApiKeyRow): ApiKeyView { - return { - id: row.id, - name: row.name, - keyPrefix: row.keyPrefix.slice(0, 6), - expiresAt: row.expiresAt, - lastUsedAt: row.lastUsedAt, - revokedAt: row.revokedAt, - createdAt: row.createdAt, - }; - } -} \ No newline at end of file + return (result.rows as ApiKeyRow[]).map((row) => this.toJSON(row)); + } + + async findById(userId: string, keyId: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ id: keyId, userId }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + + if (!row) { + return null; + } + + return this.toJSON(row); + } + + async findByIdAny(keyId: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ id: keyId }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + + if (!row) { + return null; + } + + return this.toJSON(row); + } + + async listByProject(projectId: string): Promise { + const result = await this.db + .select() + .from(ApiKeyEntity) + .where({ projectId }) + .orderBy('createdAt', 'desc'); + + return (result.rows as ApiKeyRow[]).map((row) => this.toJSON(row)); + } + + async findValidByHash(keyHash: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ keyHash }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + + if (!row || row.revokedAt) { + return null; + } + + if (row.expiresAt && row.expiresAt <= new Date().toISOString()) { + return null; + } + + return this.toJSON(row); + } + + async create(input: { + id: string; + userId: string; + projectId: string | null; + name: string; + keyPrefix: string; + keyHash: string; + expiresAt: string | null; + }): Promise { + await this.db.insert(ApiKeyEntity).values({ + id: input.id, + userId: input.userId, + projectId: input.projectId, + name: input.name, + keyPrefix: input.keyPrefix, + keyHash: input.keyHash, + expiresAt: input.expiresAt, + lastUsedAt: null, + revokedAt: null, + createdAt: new Date().toISOString(), + }); + } + + async revoke(userId: string, keyId: string): Promise { + await this.db + .update(ApiKeyEntity) + .set({ revokedAt: new Date().toISOString() }) + .where({ id: keyId, userId }); + } + + async revokeAny(keyId: string): Promise { + await this.db + .update(ApiKeyEntity) + .set({ revokedAt: new Date().toISOString() }) + .where({ id: keyId }); + } + + async touchLastUsed(keyId: string): Promise { + await this.db + .update(ApiKeyEntity) + .set({ lastUsedAt: new Date().toISOString() }) + .where({ id: keyId }); + } + + async updateKeyMaterial( + userId: string, + keyId: string, + input: { + keyPrefix: string; + keyHash: string; + expiresAt: string | null; + }, + ): Promise { + await this.db + .update(ApiKeyEntity) + .set({ + keyPrefix: input.keyPrefix, + keyHash: input.keyHash, + expiresAt: input.expiresAt, + revokedAt: null, + lastUsedAt: null, + }) + .where({ id: keyId, userId }); + } + + protected override toJSON(row: ApiKeyRow): ApiKeyView { + return { + id: row.id, + name: row.name, + keyPrefix: row.keyPrefix.slice(0, 6), + projectId: row.projectId ?? null, + expiresAt: row.expiresAt, + lastUsedAt: row.lastUsedAt, + revokedAt: row.revokedAt, + createdAt: row.createdAt, + }; + } +} diff --git a/src/modules/auth/infrastructure/repositories/repository.ts b/src/modules/auth/infrastructure/repositories/repository.ts index 6105e33c..497a9cc0 100644 --- a/src/modules/auth/infrastructure/repositories/repository.ts +++ b/src/modules/auth/infrastructure/repositories/repository.ts @@ -1,12 +1,12 @@ import { getGitDb } from '$lib/server/gitdb'; export class Repository { - protected readonly db = getGitDb(); + protected readonly db = getGitDb(); - protected toDomain(row: any): any { - return row; - } + protected toDomain(row: any): any { + return row; + } - protected toJSON(row: any): any { - return row; - } -} \ No newline at end of file + protected toJSON(row: any): any { + return row; + } +} diff --git a/src/modules/auth/infrastructure/repositories/sqlite-auth-user.repository.ts b/src/modules/auth/infrastructure/repositories/sqlite-auth-user.repository.ts index 9fcd68a8..10446c81 100644 --- a/src/modules/auth/infrastructure/repositories/sqlite-auth-user.repository.ts +++ b/src/modules/auth/infrastructure/repositories/sqlite-auth-user.repository.ts @@ -87,18 +87,22 @@ export class SqliteAuthUserRepository implements AuthUserRepository { } async countAdmins(): Promise { - const row = this.db.get<{ count: number }>("SELECT COUNT(*) AS count FROM users WHERE role = 'admin'"); + const row = this.db.get<{ count: number }>( + "SELECT COUNT(*) AS count FROM users WHERE role = 'admin'", + ); return row?.count ?? 0; } - async listActiveApiKeys(userId: string): Promise> { + async listActiveApiKeys(userId: string): Promise< + Array<{ + id: string; + name: string; + keyPrefix: string; + lastUsedAt: string | null; + createdAt: string; + }> + > { const rows = this.db.all( ` SELECT id, name, key_prefix, last_used_at, created_at diff --git a/src/modules/code-report/application/code-report-analysis.service.ts b/src/modules/code-report/application/code-report-analysis.service.ts new file mode 100644 index 00000000..4c3aadc1 --- /dev/null +++ b/src/modules/code-report/application/code-report-analysis.service.ts @@ -0,0 +1,156 @@ +import crypto from 'crypto'; +import { CodeReportAnalysisRepository } from '../infrastructure/repositories/code-report-analysis.repository'; +import type { CodeReportGitInfo } from '../domain/code-report-analysis.domain'; + +type ServiceLookup = { + findById(id: string): Promise<{ id: string } | null>; +}; + +export class CodeReportAnalysisService { + constructor( + private readonly repository: CodeReportAnalysisRepository, + private readonly serviceLookup: ServiceLookup, + ) {} + + async listByService(serviceId: string) { + const analyses = await this.repository.findByServiceId(serviceId); + return analyses.map((analysis) => analysis.toJson()); + } + + async getById(id: string) { + const analysis = await this.repository.findById(id); + if (!analysis) { + throw new Error('Analysis not found'); + } + return analysis.toJson(); + } + + // called when a scan tool starts running against a service, reports 'in_progress' with no result yet + async startAnalysis(input: { serviceId: string; tool: string; gitInfo?: CodeReportGitInfo }) { + const serviceId = input.serviceId?.trim(); + if (!serviceId) { + throw new Error('Service is required'); + } + + const service = await this.serviceLookup.findById(serviceId); + if (!service) { + throw new Error('Service not found'); + } + + const tool = input.tool?.trim(); + if (!tool) { + throw new Error('Tool is required'); + } + + const id = crypto.randomUUID(); + await this.repository.create({ + id, + serviceId, + tool, + status: 'in_progress', + gitInfo: input.gitInfo, + }); + + return this.getById(id); + } + + // called when the tool finishes successfully with the raw JSON result + async completeAnalysis( + id: string, + input: { result: unknown; summary?: unknown; gitInfo?: CodeReportGitInfo }, + ) { + const analysis = await this.repository.findById(id); + if (!analysis) { + throw new Error('Analysis not found'); + } + + if (input.result === undefined || input.result === null) { + throw new Error('Result is required to complete an analysis'); + } + + await this.repository.update(id, { + status: 'completed', + result: input.result, + summary: input.summary, + gitInfo: input.gitInfo, + error: null, + }); + + return this.getById(id); + } + + // called when the tool could not run/complete, records the reason instead of a result + async failAnalysis(id: string, input: { error: string; gitInfo?: CodeReportGitInfo }) { + const analysis = await this.repository.findById(id); + if (!analysis) { + throw new Error('Analysis not found'); + } + + const error = input.error?.trim(); + if (!error) { + throw new Error('Error reason is required to fail an analysis'); + } + + await this.repository.update(id, { + status: 'failed', + error, + gitInfo: input.gitInfo, + }); + + return this.getById(id); + } + + async deleteAnalysis(id: string) { + const analysis = await this.repository.findById(id); + if (!analysis) { + throw new Error('Analysis not found'); + } + await this.repository.deleteById(id); + } + + async deleteAllByService(serviceId: string) { + const analyses = await this.repository.findByServiceId(serviceId); + for (const analysis of analyses) { + await this.repository.deleteById(analysis.id); + } + } + + // manual upload path: paste/drop an already-finished report, skips the in_progress step + async uploadAnalysis(input: { serviceId: string; tool?: string; result: unknown }) { + const created = await this.startAnalysis({ + serviceId: input.serviceId, + tool: input.tool?.trim() || 'manual-upload', + }); + return this.completeAnalysis(created.id, { result: input.result }); + } + + // single entry point for the CI/CD-facing API: always creates a new analysis event + // (each call is one report, not a resumable transition of a previous one) + async reportAnalysis(input: { + serviceId: string; + status: 'in_progress' | 'completed' | 'failed'; + tool?: string; + gitInfo?: CodeReportGitInfo; + result?: unknown; + error?: string; + }) { + const created = await this.startAnalysis({ + serviceId: input.serviceId, + tool: input.tool?.trim() || 'api', + gitInfo: input.gitInfo, + }); + + if (input.status === 'completed') { + return this.completeAnalysis(created.id, { result: input.result, gitInfo: input.gitInfo }); + } + + if (input.status === 'failed') { + return this.failAnalysis(created.id, { + error: input.error || 'Unknown error', + gitInfo: input.gitInfo, + }); + } + + return created; + } +} diff --git a/src/modules/code-report/application/code-report.service.ts b/src/modules/code-report/application/code-report.service.ts new file mode 100644 index 00000000..186ed36b --- /dev/null +++ b/src/modules/code-report/application/code-report.service.ts @@ -0,0 +1,151 @@ +import crypto from 'crypto'; +import { CodeReportServiceRepository } from '../infrastructure/repositories/code-report-service.repository'; + +type AnalysisCleanup = { + deleteAllByService(serviceId: string): Promise; +}; + +export class CodeReportService { + constructor( + private readonly repository: CodeReportServiceRepository, + private readonly analysisCleanup?: AnalysisCleanup, + ) {} + + async listByProject(projectId: string) { + const services = await this.repository.findByProjectId(projectId); + return services.map((service) => service.toJson()); + } + + async getById(id: string) { + const service = await this.repository.findById(id); + if (!service) { + throw new Error('Service not found'); + } + return service.toJson(); + } + + async getByProjectAndSlug(projectId: string, slug: string) { + const service = await this.repository.findBySlug(projectId, slug); + if (!service) { + throw new Error('Service not found'); + } + return service.toJson(); + } + + // slug is globally unique, used by machine-to-machine endpoints that only know the project + // via the API key (not passed explicitly in the request body) + async findBySlugGlobal(slug: string) { + const service = await this.repository.findBySlugGlobal(slug); + return service ? service.toJson() : null; + } + + async createService(input: { + projectId: string; + name: string; + slug?: string; + description?: string; + tags?: string[]; + }) { + const projectId = input.projectId?.trim(); + if (!projectId) { + throw new Error('Project is required'); + } + + const name = input.name?.trim(); + if (!name) { + throw new Error('Service name is required'); + } + + const slug = this.normalizeSlug(input.slug || name); + if (!slug) { + throw new Error('Service slug is required'); + } + + const existing = await this.repository.findBySlug(projectId, slug); + if (existing) { + throw new Error('A service with this slug already exists in this project'); + } + + await this.repository.create({ + id: crypto.randomUUID(), + projectId, + slug, + name, + description: input.description?.trim() || undefined, + tags: this.normalizeTags(input.tags), + }); + + const created = await this.repository.findBySlug(projectId, slug); + if (!created) { + throw new Error('Failed to create service'); + } + + return created.toJson(); + } + + async updateService( + id: string, + changes: { name?: string; slug?: string; description?: string; tags?: string[] }, + ) { + const service = await this.repository.findById(id); + if (!service) { + throw new Error('Service not found'); + } + + const patch: { name?: string; slug?: string; description?: string; tags?: string[] } = {}; + + if (changes.name !== undefined) { + const name = changes.name.trim(); + if (!name) { + throw new Error('Service name is required'); + } + patch.name = name; + } + + if (changes.slug !== undefined) { + const slug = this.normalizeSlug(changes.slug); + if (!slug) { + throw new Error('Service slug is required'); + } + + const existing = await this.repository.findBySlug(service.projectId, slug); + if (existing && existing.id !== id) { + throw new Error('A service with this slug already exists in this project'); + } + patch.slug = slug; + } + + if (changes.description !== undefined) { + patch.description = changes.description.trim(); + } + + if (changes.tags !== undefined) { + patch.tags = this.normalizeTags(changes.tags); + } + + await this.repository.update(id, patch); + return this.getById(id); + } + + async deleteService(id: string) { + const service = await this.repository.findById(id); + if (!service) { + throw new Error('Service not found'); + } + await this.analysisCleanup?.deleteAllByService(id); + await this.repository.deleteById(id); + } + + private normalizeTags(tags?: string[]): string[] { + if (!Array.isArray(tags)) return []; + return [...new Set(tags.map((tag) => tag.trim()).filter((tag) => tag.length > 0))]; + } + + private normalizeSlug(value: string): string { + return value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + } +} diff --git a/src/modules/code-report/domain/code-report-analysis.domain.ts b/src/modules/code-report/domain/code-report-analysis.domain.ts new file mode 100644 index 00000000..a0fe708a --- /dev/null +++ b/src/modules/code-report/domain/code-report-analysis.domain.ts @@ -0,0 +1,47 @@ +import { Domain } from '$lib/server/domain/domain'; + +export type CodeReportAnalysisStatus = 'in_progress' | 'completed' | 'failed'; + +export interface CodeReportGitInfo { + repositoryUrl?: string | null; + branch?: string | null; + commit?: string | null; + commitMessage?: string | null; + author?: string | null; +} + +export class CodeReportAnalysisDomain extends Domain { + public serviceId: string = ''; + public tool: string = ''; + public status: CodeReportAnalysisStatus = 'in_progress'; + public result: unknown = null; + public summary?: unknown = null; + public error?: string | null = null; + public gitInfo?: CodeReportGitInfo | null = null; + + constructor(data: any) { + super(data); + this.serviceId = data.serviceId; + this.tool = data.tool; + this.status = data.status; + this.result = data.result ?? null; + this.summary = data.summary ?? null; + this.error = data.error ?? null; + this.gitInfo = data.gitInfo ?? null; + } + + toJson() { + return { + id: this.id, + serviceId: this.serviceId, + tool: this.tool, + status: this.status, + result: this.result, + summary: this.summary, + error: this.error, + gitInfo: this.gitInfo, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} diff --git a/src/modules/code-report/domain/code-report-service.domain.ts b/src/modules/code-report/domain/code-report-service.domain.ts new file mode 100644 index 00000000..46ae1af7 --- /dev/null +++ b/src/modules/code-report/domain/code-report-service.domain.ts @@ -0,0 +1,35 @@ +import { Domain } from '$lib/server/domain/domain'; +import { ProjectDomain } from '../../projects/domain/project.domain'; + +export class CodeReportServiceDomain extends Domain { + public projectId: string = ''; + public slug: string = ''; + public name: string = ''; + public description?: string | null = null; + public tags: string[] = []; + public project: ProjectDomain | null = null; + + constructor(data: any) { + super(data); + this.projectId = data.projectId; + this.slug = data.slug; + this.name = data.name; + this.description = data.description; + this.tags = Array.isArray(data.tags) ? data.tags : []; + this.project = data.project ? new ProjectDomain(data.project) : null; + } + + toJson() { + return { + id: this.id, + projectId: this.projectId, + slug: this.slug, + name: this.name, + description: this.description, + tags: this.tags, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + project: this.project ? this.project.toJson() : null, + }; + } +} diff --git a/src/modules/code-report/index.ts b/src/modules/code-report/index.ts new file mode 100644 index 00000000..009684ff --- /dev/null +++ b/src/modules/code-report/index.ts @@ -0,0 +1,16 @@ +import { CodeReportService } from './application/code-report.service'; +import { CodeReportAnalysisService } from './application/code-report-analysis.service'; +import { CodeReportServiceRepository } from './infrastructure/repositories/code-report-service.repository'; +import { CodeReportAnalysisRepository } from './infrastructure/repositories/code-report-analysis.repository'; + +const codeReportServiceRepository = new CodeReportServiceRepository(); +const codeReportAnalysisRepository = new CodeReportAnalysisRepository(); + +export const codeReportAnalysisService = new CodeReportAnalysisService( + codeReportAnalysisRepository, + codeReportServiceRepository, +); +export const codeReportService = new CodeReportService( + codeReportServiceRepository, + codeReportAnalysisService, +); diff --git a/src/modules/code-report/infrastructure/repositories/code-report-analysis.repository.ts b/src/modules/code-report/infrastructure/repositories/code-report-analysis.repository.ts new file mode 100644 index 00000000..ff0fb08a --- /dev/null +++ b/src/modules/code-report/infrastructure/repositories/code-report-analysis.repository.ts @@ -0,0 +1,62 @@ +import { Repository } from '$lib/server/infra/repository'; +import { + CodeReportAnalysisDomain, + type CodeReportAnalysisStatus, + type CodeReportGitInfo, +} from '../../domain/code-report-analysis.domain'; +import { CodeReportAnalysisEntity } from '$lib/database/schemas'; + +export class CodeReportAnalysisRepository extends Repository { + async findByServiceId(serviceId: string): Promise { + const result = await this.db + .select() + .from(CodeReportAnalysisEntity) + .where({ serviceId }) + .orderBy('createdAt', 'desc'); + return result.rows.map((row: any) => new CodeReportAnalysisDomain(row)); + } + + async findById(id: string): Promise { + const result = await this.db.select().from(CodeReportAnalysisEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new CodeReportAnalysisDomain(row) : null; + } + + async create(input: { + id: string; + serviceId: string; + tool: string; + status: CodeReportAnalysisStatus; + gitInfo?: CodeReportGitInfo; + }): Promise { + await this.db.insert(CodeReportAnalysisEntity).values({ + id: input.id, + serviceId: input.serviceId, + tool: input.tool, + status: input.status, + gitInfo: input.gitInfo, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + } + + async update( + id: string, + changes: { + status?: CodeReportAnalysisStatus; + result?: unknown; + summary?: unknown; + error?: string | null; + gitInfo?: CodeReportGitInfo; + }, + ): Promise { + await this.db + .update(CodeReportAnalysisEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async deleteById(id: string): Promise { + await this.db.delete(CodeReportAnalysisEntity).where({ id }); + } +} diff --git a/src/modules/code-report/infrastructure/repositories/code-report-service.repository.ts b/src/modules/code-report/infrastructure/repositories/code-report-service.repository.ts new file mode 100644 index 00000000..0f6a5326 --- /dev/null +++ b/src/modules/code-report/infrastructure/repositories/code-report-service.repository.ts @@ -0,0 +1,92 @@ +import { Repository } from '$lib/server/infra/repository'; +import { CodeReportServiceDomain } from '../../domain/code-report-service.domain'; +import { CodeReportServiceEntity } from '$lib/database/schemas'; + +export class CodeReportServiceRepository extends Repository { + async findAll(): Promise { + const result = await this.db + .with({ project: true }) + .select() + .from(CodeReportServiceEntity) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new CodeReportServiceDomain(row)); + } + + async findByProjectId(projectId: string): Promise { + const result = await this.db + .with({ project: true }) + .select() + .from(CodeReportServiceEntity) + .where({ projectId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new CodeReportServiceDomain(row)); + } + + async findById(id: string): Promise { + const result = await this.db + .with({ project: true }) + .select() + .from(CodeReportServiceEntity) + .where({ id }) + .limit(1); + const row = result.rows[0]; + return row ? new CodeReportServiceDomain(row) : null; + } + + async findBySlug(projectId: string, slug: string): Promise { + const result = await this.db + .with({ project: true }) + .select() + .from(CodeReportServiceEntity) + .where({ projectId, slug }) + .limit(1); + const row = result.rows[0]; + return row ? new CodeReportServiceDomain(row) : null; + } + + // slug is unique across the whole entity (see schema), so this looks it up regardless of project + async findBySlugGlobal(slug: string): Promise { + const result = await this.db + .with({ project: true }) + .select() + .from(CodeReportServiceEntity) + .where({ slug }) + .limit(1); + const row = result.rows[0]; + return row ? new CodeReportServiceDomain(row) : null; + } + + async create(input: { + id: string; + projectId: string; + slug: string; + name: string; + description?: string; + tags?: string[]; + }): Promise { + await this.db.insert(CodeReportServiceEntity).values({ + id: input.id, + projectId: input.projectId, + slug: input.slug, + name: input.name, + description: input.description, + tags: input.tags ?? [], + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + } + + async update( + id: string, + changes: { name?: string; slug?: string; description?: string; tags?: string[] }, + ): Promise { + await this.db + .update(CodeReportServiceEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async deleteById(id: string): Promise { + await this.db.delete(CodeReportServiceEntity).where({ id }); + } +} diff --git a/src/modules/projects/application/project.service.test.ts b/src/modules/projects/application/project.service.test.ts index 4bd1bc41..429a657e 100644 --- a/src/modules/projects/application/project.service.test.ts +++ b/src/modules/projects/application/project.service.test.ts @@ -26,7 +26,7 @@ class FakeProjectRepository { name: string; description?: string; status: string; - modules: { vault: boolean; openreport: boolean; stateiac: boolean }; + modules: { vault: boolean; codereport: boolean; stateiac: boolean }; }) { this.rows.push( new ProjectDomain({ @@ -50,7 +50,7 @@ class FakeProjectRepository { slug?: string; description?: string; status?: string; - modules?: { vault: boolean; openreport: boolean; stateiac: boolean }; + modules?: { vault: boolean; codereport: boolean; stateiac: boolean }; organizationId?: string; }, ) { @@ -156,7 +156,7 @@ describe('ProjectService', () => { it('defaults all modules to enabled when none are provided', async () => { const project = await createProject({ name: 'Project C' }); - expect(project.modules).toEqual({ vault: true, openreport: true, stateiac: true }); + expect(project.modules).toEqual({ vault: true, codereport: true, stateiac: true }); }); it('accepts a partial modules override, defaulting the rest to enabled', async () => { @@ -164,7 +164,7 @@ describe('ProjectService', () => { name: 'Project D', modules: { vault: false }, }); - expect(project.modules).toEqual({ vault: false, openreport: true, stateiac: true }); + expect(project.modules).toEqual({ vault: false, codereport: true, stateiac: true }); }); }); @@ -213,12 +213,12 @@ describe('ProjectService', () => { const created = await createProject({ name: 'Project A' }); const updated = await service.updateProject(created.id, { modules: { vault: false } }); - expect(updated.modules).toEqual({ vault: false, openreport: true, stateiac: true }); + expect(updated.modules).toEqual({ vault: false, codereport: true, stateiac: true }); const updatedAgain = await service.updateProject(created.id, { - modules: { openreport: false }, + modules: { codereport: false }, }); - expect(updatedAgain.modules).toEqual({ vault: false, openreport: false, stateiac: true }); + expect(updatedAgain.modules).toEqual({ vault: false, codereport: false, stateiac: true }); }); it('updates the status', async () => { diff --git a/src/modules/projects/application/project.service.ts b/src/modules/projects/application/project.service.ts index 87f346a1..2dec5b88 100644 --- a/src/modules/projects/application/project.service.ts +++ b/src/modules/projects/application/project.service.ts @@ -188,7 +188,7 @@ export class ProjectService { private sanitizeModules(modules?: Partial): ProjectModules { return { vault: modules?.vault ?? DEFAULT_PROJECT_MODULES.vault, - openreport: modules?.openreport ?? DEFAULT_PROJECT_MODULES.openreport, + codereport: modules?.codereport ?? DEFAULT_PROJECT_MODULES.codereport, stateiac: modules?.stateiac ?? DEFAULT_PROJECT_MODULES.stateiac, }; } diff --git a/src/modules/projects/domain/project.domain.ts b/src/modules/projects/domain/project.domain.ts index 8dfef0a6..115ffdbc 100644 --- a/src/modules/projects/domain/project.domain.ts +++ b/src/modules/projects/domain/project.domain.ts @@ -8,13 +8,13 @@ export interface ProjectStatus { export interface ProjectModules { vault: boolean; - openreport: boolean; + codereport: boolean; stateiac: boolean; } export const DEFAULT_PROJECT_MODULES: ProjectModules = { vault: true, - openreport: true, + codereport: true, stateiac: true, }; diff --git a/src/routes/api/code-report/analyse-result/+server.ts b/src/routes/api/code-report/analyse-result/+server.ts new file mode 100644 index 00000000..b0f0ff62 --- /dev/null +++ b/src/routes/api/code-report/analyse-result/+server.ts @@ -0,0 +1,113 @@ +import { json } from '@sveltejs/kit'; +import { codeReportService, codeReportAnalysisService } from '../../../../modules/code-report'; +import { apiKeysService } from '../../../../modules/auth'; + +type AnalyseResultBody = { + service?: string; + createService?: boolean; + gitInfo?: { + repository?: string; + repositoryUrl?: string; + branch?: string; + commit?: string; + commitMessage?: string; + author?: string; + }; + status?: string; + error?: unknown; + result?: unknown; +}; + +const STATUS_MAP: Record = { + 'in progress': 'in_progress', + in_progress: 'in_progress', + completed: 'completed', + failed: 'failed', +}; + +function normalizeGitInfo(gitInfo: AnalyseResultBody['gitInfo']) { + if (!gitInfo) return undefined; + return { + repositoryUrl: gitInfo.repositoryUrl || gitInfo.repository || null, + branch: gitInfo.branch ?? null, + commit: gitInfo.commit ?? null, + commitMessage: gitInfo.commitMessage ?? null, + author: gitInfo.author ?? null, + }; +} + +function normalizeError(error: unknown): string | undefined { + if (error === undefined || error === null) return undefined; + if (typeof error === 'string') return error; + try { + return JSON.stringify(error); + } catch { + return String(error); + } +} + +// single machine-to-machine endpoint for CI/CD tools: authenticates via a project-scoped +// server access key (Authorization: Bearer gvs_...), not a browser session +export async function POST({ request }) { + const authHeader = request.headers.get('authorization') || ''; + const token = authHeader.replace(/^Bearer\s+/i, '').trim(); + + if (!token) { + return json({ error: 'Missing API key' }, { status: 401 }); + } + + const apiKey = await apiKeysService.resolveApiKey(token); + if (!apiKey || !apiKey.projectId) { + return json({ error: 'Invalid or unscoped API key' }, { status: 401 }); + } + + const body = (await request.json()) as AnalyseResultBody; + + const slug = String(body.service || '').trim(); + if (!slug) { + return json({ error: 'service is required' }, { status: 400 }); + } + + const status = + STATUS_MAP[ + String(body.status || '') + .toLowerCase() + .trim() + ]; + if (!status) { + return json( + { error: "status must be 'in progress', 'completed' or 'failed'" }, + { status: 400 }, + ); + } + + try { + let service = await codeReportService.findBySlugGlobal(slug); + + if (!service) { + if (!body.createService) { + return json({ error: 'Service not found' }, { status: 404 }); + } + service = await codeReportService.createService({ + projectId: apiKey.projectId, + name: slug, + slug, + }); + } else if (service.projectId !== apiKey.projectId) { + return json({ error: 'Service does not belong to this API key project' }, { status: 403 }); + } + + const analysis = await codeReportAnalysisService.reportAnalysis({ + serviceId: service.id, + status, + gitInfo: normalizeGitInfo(body.gitInfo), + result: body.result, + error: normalizeError(body.error), + }); + + return json({ success: true, service: { id: service.id, slug: service.slug }, analysis }); + } catch (err) { + const message = err instanceof Error ? err.message : 'Unknown error'; + return json({ error: message }, { status: 400 }); + } +} diff --git a/src/routes/org/[org]/projects/[slug]/+layout.svelte b/src/routes/org/[org]/projects/[slug]/+layout.svelte index 3e884476..e3a06569 100644 --- a/src/routes/org/[org]/projects/[slug]/+layout.svelte +++ b/src/routes/org/[org]/projects/[slug]/+layout.svelte @@ -5,6 +5,7 @@ ChevronRight, GitBranch, Info, + KeyRound, LayoutDashboard, ScrollText, Shield, @@ -33,7 +34,7 @@ }, { label: 'Open Report', - href: `/org/${orgSlug}/projects/${project.slug}/report`, + href: `/org/${orgSlug}/projects/${project.slug}/code-report/services`, icon: BarChart3, subtitle: 'Reportes de vulnerabilidades y dependencias del proyecto.', }, @@ -61,6 +62,12 @@ icon: Shield, subtitle: 'Define roles y permisos específicos para este proyecto.', }, + { + label: 'Server Access Keys', + href: `/org/${orgSlug}/projects/${project.slug}/settings/server-access-keys`, + icon: KeyRound, + subtitle: 'Credenciales para que herramientas externas reporten análisis a este proyecto.', + }, { label: 'Auditoría', href: `/org/${orgSlug}/projects/${project.slug}/settings/audit`, diff --git a/src/routes/org/[org]/projects/[slug]/code-report/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/+page.server.ts new file mode 100644 index 00000000..a81e7d24 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/code-report/+page.server.ts @@ -0,0 +1,5 @@ +import { redirect } from '@sveltejs/kit'; + +export function load({ params }) { + throw redirect(302, `/org/${params.org}/projects/${params.slug}/code-report/services`); +} diff --git a/src/routes/org/[org]/projects/[slug]/code-report/services/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/services/+page.server.ts new file mode 100644 index 00000000..3e1d10f0 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/code-report/services/+page.server.ts @@ -0,0 +1,61 @@ +import { error, fail } from '@sveltejs/kit'; +import { codeReportService } from '../../../../../../../modules/code-report'; +import { projectService } from '../../../../../../../modules/projects'; +import { cancanService } from '../../../../../../../modules/auth'; + +export async function load({ parent, locals }) { + const { project } = await parent(); + + const canRead = await cancanService.canSessionUser(locals.user, 'openreport:read', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canRead) { + throw error(403, 'Forbidden'); + } + + const services = await codeReportService.listByProject(project.id); + + return { services }; +} + +export const actions = { + create: async ({ request, params, locals }) => { + const project = await projectService.getProjectBySlug(params.slug); + + const canCreate = await cancanService.canSessionUser(locals.user, 'openreport:create', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canCreate) { + return fail(403, { error: 'Forbidden' }); + } + + const formData = await request.formData(); + const name = String(formData.get('name') || '').trim(); + const slug = String(formData.get('slug') || '').trim(); + const description = String(formData.get('description') || '').trim(); + const tags = formData + .getAll('tags') + .map((tag) => String(tag).trim()) + .filter((tag) => tag.length > 0); + + try { + await codeReportService.createService({ + projectId: project.id, + name, + slug: slug || undefined, + description: description || undefined, + tags, + }); + return { success: true }; + } catch (err) { + const message = err instanceof Error ? err.message : 'Failed to create service'; + return fail(400, { error: message, name, slug, description, tags }); + } + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte new file mode 100644 index 00000000..c93e06f1 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte @@ -0,0 +1,262 @@ + + + + Code Report - Services - GitVault Suite + + +
+
+
+ + +
+ +
+ + {#if filteredServices.length === 0} +
+ +

+ {data.services.length === 0 + ? 'Todavía no hay servicios en este proyecto.' + : 'Sin resultados para tu búsqueda.'} +

+
+ {:else} + + {/if} +
+ +{#if modalOpen} +
+
+
+

Add Service

+ +
+ +
{ + submitting = true; + return async ({ update }) => { + await update(); + submitting = false; + }; + }} + class="mt-4 space-y-4" + > + {#if form?.error} +

{form.error}

+ {/if} + +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ {#each tags as tag (tag)} + + {tag} + + + {/each} + +
+ {#each tags as tag (tag)} + + {/each} +
+ +
+ + +
+
+
+
+{/if} diff --git a/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.server.ts new file mode 100644 index 00000000..c4f5054c --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.server.ts @@ -0,0 +1,95 @@ +import { error, fail, redirect } from '@sveltejs/kit'; +import { + codeReportService, + codeReportAnalysisService, +} from '../../../../../../../../modules/code-report'; +import { projectService } from '../../../../../../../../modules/projects'; +import { cancanService } from '../../../../../../../../modules/auth'; + +export async function load({ parent, params, locals }) { + const { project } = await parent(); + + const canRead = await cancanService.canSessionUser(locals.user, 'openreport:read', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canRead) { + throw error(403, 'Forbidden'); + } + + try { + const service = await codeReportService.getByProjectAndSlug(project.id, params.serviceSlug); + const analyses = await codeReportAnalysisService.listByService(service.id); + const latestAnalysis = analyses[0] ?? null; + + return { service, latestAnalysis }; + } catch { + throw error(404, 'Service not found'); + } +} + +export const actions = { + deleteService: async ({ params, locals }) => { + const project = await projectService.getProjectBySlug(params.slug); + + const canDelete = await cancanService.canSessionUser(locals.user, 'openreport:delete', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canDelete) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const service = await codeReportService.getByProjectAndSlug(project.id, params.serviceSlug); + await codeReportService.deleteService(service.id); + } catch (err) { + const message = err instanceof Error ? err.message : 'Failed to delete service'; + return fail(400, { error: message }); + } + + throw redirect(303, `/org/${params.org}/projects/${params.slug}/code-report/services`); + }, + + uploadAnalysis: async ({ request, params, locals }) => { + const project = await projectService.getProjectBySlug(params.slug); + + const canCreate = await cancanService.canSessionUser(locals.user, 'openreport:create', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canCreate) { + return fail(403, { uploadError: 'Forbidden' }); + } + + const formData = await request.formData(); + const raw = String(formData.get('json') || '').trim(); + + if (!raw) { + return fail(400, { uploadError: 'Pega o sube un archivo JSON.', json: raw }); + } + + let result: unknown; + try { + result = JSON.parse(raw); + } catch { + return fail(400, { uploadError: 'El contenido no es un JSON válido.', json: raw }); + } + + try { + const service = await codeReportService.getByProjectAndSlug(project.id, params.serviceSlug); + await codeReportAnalysisService.uploadAnalysis({ serviceId: service.id, result }); + } catch (err) { + const message = err instanceof Error ? err.message : 'Failed to upload analysis'; + return fail(400, { uploadError: message, json: raw }); + } + + return { uploadSuccess: true }; + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte new file mode 100644 index 00000000..25907004 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte @@ -0,0 +1,488 @@ + + + + {data.service.name} - Code Report - GitVault Suite + + +
+
+ + + Volver a servicios + + +
+ + + Ver histórico + + + +
+
+ +
+
+

{data.service.name}

+

+ Slug: + {data.service.slug} +

+ {#if data.service.description} +

Description

+

+ {data.service.description} +

+ {/if} + {#if data.service.tags.length > 0} +
+ {#each data.service.tags as tag} + + {tag} + + {/each} +
+ {/if} + + {#if repositoryUrl && repositoryIcon} + + + + {/if} +
+ +
+

+ + Vulnerabilidades detectadas +

+ {#if analysisSummary} +
+
+

{analysisSummary.vulnerabilities.critical}

+

Critical

+
+
+

{analysisSummary.vulnerabilities.high}

+

High

+
+
+

{analysisSummary.vulnerabilities.medium}

+

Medium

+
+
+

{analysisSummary.vulnerabilities.low}

+

Low

+
+
+ {:else} +

Sin datos todavía.

+ {/if} +
+ +
+

Resumen

+ {#if analysisSummary} +
+
+
+ Total vulnerabilidades +
+
+ {analysisSummary.totalVulnerabilities} +
+
+
+
+ Secretos expuestos +
+
{analysisSummary.exposedSecrets}
+
+
+
+ Dependencias +
+
{analysisSummary.dependencies}
+
+
+
+ Archivos analizados +
+
{analysisSummary.targetsScanned}
+
+
+ {:else} +

Sin datos todavía.

+ {/if} +
+
+ +
+

Último análisis

+ + {#if !data.latestAnalysis} +

Todavía no se ha ejecutado ningún análisis.

+ {:else} +
+ + {data.latestAnalysis.status} + + {data.latestAnalysis.tool} + + + {new Date(data.latestAnalysis.createdAt).toLocaleString()} + +
+ + {#if data.latestAnalysis.gitInfo} +
+ + {#if data.latestAnalysis.gitInfo.repositoryUrl} + {data.latestAnalysis.gitInfo.repositoryUrl} + {/if} + {#if data.latestAnalysis.gitInfo.branch} + @ {data.latestAnalysis.gitInfo.branch} + {/if} + {#if data.latestAnalysis.gitInfo.commit} + {data.latestAnalysis.gitInfo.commit.slice(0, 7)} + {/if} +
+ {/if} + + {#if data.latestAnalysis.status === 'failed' && data.latestAnalysis.error} +
+ + {data.latestAnalysis.error} +
+ {:else} +
{JSON.stringify(
+            data.latestAnalysis.result ?? {},
+            null,
+            2,
+          )}
+ {/if} + {/if} +
+
+ +{#if deleteModalOpen} +
+
+
+

Borrar servicio

+ +
+ +

+ Vas a borrar {data.service.name} y + todos sus análisis. Esta acción no se + puede deshacer. +

+ + {#if deleteError} +

{deleteError}

+ {/if} + +
{ + deleting = true; + return async ({ update }) => { + await update(); + deleting = false; + }; + }} + class="mt-5 flex justify-end gap-2" + > + + +
+
+
+{/if} + +{#if uploadModalOpen} +
+
+
+

Subir análisis

+ +
+ +
{ + uploading = true; + return async ({ update }) => { + await update(); + uploading = false; + }; + }} + class="mt-4 space-y-4" + > + {#if uploadError} +

{uploadError}

+ {/if} + + + + + +
+ + +
+
+
+
+{/if} diff --git a/src/routes/org/[org]/projects/[slug]/overview/+page.svelte b/src/routes/org/[org]/projects/[slug]/overview/+page.svelte index 320c149c..905242c6 100644 --- a/src/routes/org/[org]/projects/[slug]/overview/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/overview/+page.svelte @@ -12,7 +12,7 @@ type ProjectModules = { vault: boolean; - openreport: boolean; + codereport: boolean; stateiac: boolean; }; @@ -47,10 +47,10 @@ icon: Shield, }, { - key: 'openreport', - label: 'Open Report', + key: 'codereport', + label: 'Code Report', description: 'Reportes de vulnerabilidades y dependencias.', - href: `/org/${orgSlug}/projects/${project.slug}/report`, + href: `/org/${orgSlug}/projects/${project.slug}/code-report`, icon: BarChart3, }, { diff --git a/src/routes/org/[org]/projects/[slug]/report/+page.svelte b/src/routes/org/[org]/projects/[slug]/report/+page.svelte deleted file mode 100644 index ef839adf..00000000 --- a/src/routes/org/[org]/projects/[slug]/report/+page.svelte +++ /dev/null @@ -1,59 +0,0 @@ - - - - Open Report - GitVault Suite - - -
-
-
-
-
-

Analisis

-

Open Report

-

- Panel base para reportes, indicadores y exploración rápida de señales del sistema. -

-
- {#if canCreate} - - {/if} -
-
- -
-
- -

Metrics

-

KPIs y resúmenes de actividad.

-
-
- -

Trends

-

Cambios a lo largo del tiempo.

-
-
- -

Explorer

-

Búsqueda y filtrado de reportes.

-
-
-
- -
-

Próximo paso

-

- Esta es la base visual para el módulo de analítica. Después conectaremos datos reales y vistas más densas. -

-
-
\ No newline at end of file diff --git a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte index 62ab8d9a..ef5fdbd6 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte @@ -19,7 +19,7 @@ type ProjectModules = { vault: boolean; - openreport: boolean; + codereport: boolean; stateiac: boolean; }; @@ -63,10 +63,10 @@ href: `/org/${$page.params.org}/projects/${data.project.slug}/vault`, }, { - key: 'openreport', - label: 'Open Report', + key: 'codereport', + label: 'Code Report', icon: BarChart3, - href: `/org/${$page.params.org}/projects/${data.project.slug}/report`, + href: `/org/${$page.params.org}/projects/${data.project.slug}/code-report`, }, { key: 'stateiac', diff --git a/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.server.ts new file mode 100644 index 00000000..0a1c4c0f --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.server.ts @@ -0,0 +1,84 @@ +import { error, fail } from '@sveltejs/kit'; +import { apiKeysService, cancanService } from '../../../../../../../modules/auth'; +import { projectService } from '../../../../../../../modules/projects'; + +export async function load({ parent, locals }) { + const { project } = await parent(); + + const canRead = await cancanService.canSessionUser(locals.user, 'openreport:read', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canRead) { + throw error(403, 'Forbidden'); + } + + const apiKeys = await apiKeysService.listActiveApiKeysByProject(project.id); + + return { apiKeys }; +} + +export const actions = { + create: async ({ request, params, locals }) => { + const project = await projectService.getProjectBySlug(params.slug); + + const canCreate = await cancanService.canSessionUser(locals.user, 'openreport:create', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canCreate) { + return fail(403, { error: 'Forbidden' }); + } + + const formData = await request.formData(); + const name = String(formData.get('name') || '').trim(); + const expiresInDays = String(formData.get('expiresInDays') || '').trim(); + + if (!name) { + return fail(400, { error: 'Key name is required.' }); + } + + const expiresAt = expiresInDays + ? new Date(Date.now() + Number(expiresInDays) * 24 * 60 * 60 * 1000).toISOString() + : null; + + const { token } = await apiKeysService.createProjectApiKey( + locals.user!.id, + project.id, + name, + expiresAt, + ); + + return { success: true, createdKey: token }; + }, + + revoke: async ({ request, params, locals }) => { + const project = await projectService.getProjectBySlug(params.slug); + + const canDelete = await cancanService.canSessionUser(locals.user, 'openreport:delete', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + + if (!canDelete) { + return fail(403, { error: 'Forbidden' }); + } + + const formData = await request.formData(); + const keyId = String(formData.get('keyId') || ''); + + try { + await apiKeysService.revokeProjectApiKey(project.id, keyId); + } catch (err) { + const message = err instanceof Error ? err.message : 'Failed to revoke key'; + return fail(400, { error: message }); + } + + return { success: true }; + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte new file mode 100644 index 00000000..c2d4f9e7 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte @@ -0,0 +1,216 @@ + + + + Server Access Keys - Project Settings + + +
+
+
+
+

Server Access Keys

+

+ Credenciales para que herramientas externas (CI/CD) reporten análisis de Code Report a + este proyecto vía POST /api/code-report/analyse-result. +

+
+ +
+
+ + {#if form?.error} +

{form.error}

+ {/if} + + {#if form?.createdKey} +
+
+
+

Copia este token ahora. No se volverá a mostrar.

+ {form.createdKey} +
+ +
+
+ {/if} + +
+ {#if data.apiKeys.length === 0} +
+ +

Todavía no hay keys para este proyecto.

+
+ {:else} + {#each data.apiKeys as key (key.id)} +
+
+

{key.name}

+

+ Prefix: {key.keyPrefix} · Creada {formatDateTime(key.createdAt)} · Expira {formatDateTime( + key.expiresAt, + )} +

+

+ Estado: {keyState(key)} +

+
+ + {#if !key.revokedAt} +
+ + +
+ {/if} +
+ {/each} + {/if} +
+
+ +{#if createModalOpen} +
+
+

Crear server access key

+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+
+
+{/if}