From 279de7f3c162dbc725990fd337329081d8a9899e Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 14:29:55 +0100 Subject: [PATCH] feat(events): access, invitation, role and API key domain events (#78) - access.granted/updated/revoked for cluster, organization and project access - user.invited and invitation.accepted (no token, URL or email) - role.updated with added/removed permissions - api_key.created/revoked with the public prefix only (never the key or its hash) - publishAfterWrite helper so events never fail a successful write - es/en translations and no-leak tests Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- src/lib/events/catalog/access.events.ts | 156 ++++++++++++ src/lib/events/catalog/index.ts | 3 + src/lib/events/domain-events.ts | 59 +++++ src/lib/i18n/locales/en.json | 83 +++++++ src/lib/i18n/locales/es.json | 83 +++++++ src/lib/server/events/index.ts | 1 + src/lib/server/events/publish.ts | 25 ++ src/lib/server/events/scope.ts | 2 +- .../auth/application/apikeys.service.test.ts | 88 +++++++ .../auth/application/apikeys.service.ts | 36 +++ .../application/invitation.service.test.ts | 77 ++++++ .../auth/application/invitation.service.ts | 26 +- .../auth/application/role.service.test.ts | 68 ++++++ src/modules/auth/application/role.service.ts | 33 +++ .../application/user-access.service.test.ts | 227 ++++++++++++++++++ .../auth/application/user-access.service.ts | 107 ++++++++- src/modules/auth/index.ts | 20 +- 18 files changed, 1090 insertions(+), 8 deletions(-) create mode 100644 src/lib/events/catalog/access.events.ts create mode 100644 src/lib/server/events/publish.ts diff --git a/CLAUDE.md b/CLAUDE.md index 50924f21..c2d670a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,7 +135,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`. (enforced by a test). - Publish only **after** the GitDB write succeeded, with the right `scope` (`organizationId` / `projectId`). `publish()` returns immediately; handlers run asynchronously, - in order per subscriber, and a failing handler is only logged. + in order per subscriber, and a failing handler is only logged. Use `publishAfterWrite` + (`#lib/server/events/publish`) so resolving the scope or publishing can never fail a write that + already succeeded; `resolveProjectScope` adds the organization to project events. - Delivery is at-most-once and per process; events are not persisted. - The actor comes from the request context (`userId` / `apiKeyId` set in `hooks.server.ts`), falling back to `system`. diff --git a/src/lib/events/catalog/access.events.ts b/src/lib/events/catalog/access.events.ts new file mode 100644 index 00000000..282824a8 --- /dev/null +++ b/src/lib/events/catalog/access.events.ts @@ -0,0 +1,156 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +export const ACCESS_SCOPES = ['cluster', 'organization', 'project'] as const; + +const READ_USERS = 'organization:users:read'; + +const GRANTED = 'access.granted'; +const UPDATED = 'access.updated'; +const REVOKED = 'access.revoked'; +const INVITED = 'user.invited'; +const ACCEPTED = 'invitation.accepted'; +const ROLE_UPDATED = 'role.updated'; +const KEY_CREATED = 'api_key.created'; +const KEY_REVOKED = 'api_key.revoked'; + +type AccessEvent = typeof GRANTED | typeof UPDATED | typeof REVOKED; +type InvitationEvent = typeof INVITED | typeof ACCEPTED; + +function userField(type: AccessEvent | InvitationEvent) { + return { + key: 'userId', + label: fieldLabel(type, 'userId'), + type: 'reference', + reference: 'user', + operators: OPERATORS.reference, + } as const; +} + +function roleField(type: AccessEvent | InvitationEvent | typeof ROLE_UPDATED) { + return { + key: 'roleId', + label: fieldLabel(type, 'roleId'), + type: 'reference', + reference: 'role', + operators: OPERATORS.reference, + } as const; +} + +function scopeField(type: AccessEvent | typeof ACCEPTED) { + return { + key: 'scope', + label: fieldLabel(type, 'scope'), + type: 'enum', + options: enumOptions('accessScope', ACCESS_SCOPES), + operators: OPERATORS.enum, + } as const; +} + +function accessFields(type: AccessEvent) { + return [userField(type), roleField(type), scopeField(type)] as const; +} + +function permissionsField(key: 'addedPermissions' | 'removedPermissions') { + return { + key, + label: fieldLabel(ROLE_UPDATED, key), + type: 'string', + operators: OPERATORS.list, + } as const; +} + +// access events also feed the fixed system notifications (#81) for the affected user +export const accessEvents: EventDefinitions< + AccessEvent | InvitationEvent | typeof ROLE_UPDATED | typeof KEY_CREATED | typeof KEY_REVOKED +> = { + [GRANTED]: { + ...eventText(GRANTED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(GRANTED), + }, + [UPDATED]: { + ...eventText(UPDATED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(UPDATED), + }, + [REVOKED]: { + ...eventText(REVOKED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(REVOKED), + }, + [INVITED]: { + ...eventText(INVITED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: [userField(INVITED), roleField(INVITED)], + }, + [ACCEPTED]: { + ...eventText(ACCEPTED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: [userField(ACCEPTED), roleField(ACCEPTED), scopeField(ACCEPTED)], + }, + [ROLE_UPDATED]: { + ...eventText(ROLE_UPDATED), + module: 'access', + scope: 'organization', + readPermission: 'organization:roles:read', + alertable: true, + fields: [ + roleField(ROLE_UPDATED), + permissionsField('addedPermissions'), + permissionsField('removedPermissions'), + ], + }, + [KEY_CREATED]: { + ...eventText(KEY_CREATED), + module: 'access', + scope: 'project', + readPermission: 'project:server-keys:read', + alertable: true, + fields: [ + { + key: 'name', + label: fieldLabel(KEY_CREATED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, + [KEY_REVOKED]: { + ...eventText(KEY_REVOKED), + module: 'access', + scope: 'project', + readPermission: 'project:server-keys:read', + alertable: true, + fields: [ + { + key: 'apiKeyId', + label: fieldLabel(KEY_REVOKED, 'apiKeyId'), + type: 'reference', + reference: 'api_key', + operators: OPERATORS.reference, + }, + { + key: 'name', + label: fieldLabel(KEY_REVOKED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts index 6cb95335..d22ce290 100644 --- a/src/lib/events/catalog/index.ts +++ b/src/lib/events/catalog/index.ts @@ -3,6 +3,7 @@ import { codeReportEvents } from './code-report.events'; import { vaultEvents } from './vault.events'; import { projectEvents } from './projects.events'; import { organizationEvents } from './organization.events'; +import { accessEvents } from './access.events'; import type { EventCatalog, EventDefinition, @@ -17,6 +18,7 @@ export { CODE_REPORT_TOOLS } from './code-report.events'; export { VAULT_SECRET_CHANGED_FIELDS } from './vault.events'; export { PROJECT_CHANGED_FIELDS } from './projects.events'; export { ORGANIZATION_CHANGED_FIELDS } from './organization.events'; +export { ACCESS_SCOPES } from './access.events'; /** * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a @@ -41,6 +43,7 @@ export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ ...vaultEvents, ...projectEvents, ...organizationEvents, + ...accessEvents, }); export function isEventType(value: string): value is EventType { diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts index bdf762d8..83d1e5bd 100644 --- a/src/lib/events/domain-events.ts +++ b/src/lib/events/domain-events.ts @@ -121,6 +121,57 @@ export type OrganizationUpdatedPayload = { changedFields: OrganizationChangedField[]; }; +export type AccessScope = 'cluster' | 'organization' | 'project'; + +export type AccessStatus = 'active' | 'invited'; + +/** A role assignment: a cluster account role, or a membership in an organization or project. */ +export type AccessPayload = { + /** The user-access entry id (the user id for cluster-level access). */ + accessId: string; + userId: string; + roleId: string | null; + scope: AccessScope; + status: AccessStatus; +}; + +export type AccessUpdatedPayload = AccessPayload & { + previousRoleId: string | null; + previousStatus: AccessStatus; +}; + +/** Never carries the invitation token, its URL or the invitee's email. */ +export type UserInvitedPayload = { + userId: string; + roleId: string; + organizationId: string; +}; + +export type InvitationAcceptedPayload = { + userId: string; + accessId: string; + roleId: string | null; + scope: AccessScope; +}; + +export type RoleUpdatedPayload = { + roleId: string; + name: string; + scope: AccessScope; + nameChanged: boolean; + addedPermissions: string[]; + removedPermissions: string[]; +}; + +/** Never carries the key or its hash: `keyPrefix` is the public, non-secret identifier. */ +export type ApiKeyPayload = { + apiKeyId: string; + name: string; + keyPrefix: string; + projectId: string | null; + userId: string | null; +}; + export interface DomainEventMap { 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; @@ -137,6 +188,14 @@ export interface DomainEventMap { 'project.updated': ProjectUpdatedPayload; 'project.deleted': ProjectPayload; 'organization.updated': OrganizationUpdatedPayload; + 'access.granted': AccessPayload; + 'access.updated': AccessUpdatedPayload; + 'access.revoked': AccessPayload; + 'user.invited': UserInvitedPayload; + 'invitation.accepted': InvitationAcceptedPayload; + 'role.updated': RoleUpdatedPayload; + 'api_key.created': ApiKeyPayload; + 'api_key.revoked': ApiKeyPayload; } export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 76dfcc59..484fad22 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1056,6 +1056,11 @@ "name": "Name", "slug": "Slug", "description": "Description" + }, + "accessScope": { + "cluster": "GitOps", + "organization": "Organization", + "project": "Project" } }, "vault": { @@ -1154,6 +1159,84 @@ "changedFields": "Changed fields" } } + }, + "access": { + "granted": { + "label": "Access granted", + "description": "A user was given access with a role.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + }, + "updated": { + "label": "Access changed", + "description": "The role or status of a user access changed.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + }, + "revoked": { + "label": "Access revoked", + "description": "A user access was removed.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + } + }, + "user": { + "invited": { + "label": "User invited", + "description": "A user was invited to the organization.", + "fields": { + "userId": "User", + "roleId": "Role" + } + } + }, + "invitation": { + "accepted": { + "label": "Invitation accepted", + "description": "A user accepted their invitation.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + } + }, + "role": { + "updated": { + "label": "Role updated", + "description": "The name or permissions of a role changed.", + "fields": { + "roleId": "Role", + "addedPermissions": "Added permissions", + "removedPermissions": "Removed permissions" + } + } + }, + "api_key": { + "created": { + "label": "API key created", + "description": "An API key was created.", + "fields": { + "name": "Name" + } + }, + "revoked": { + "label": "API key revoked", + "description": "An API key was revoked.", + "fields": { + "apiKeyId": "API key", + "name": "Name" + } + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 5def0db7..72b5deb9 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1056,6 +1056,11 @@ "name": "Nombre", "slug": "Slug", "description": "Descripción" + }, + "accessScope": { + "cluster": "GitOps", + "organization": "Organización", + "project": "Proyecto" } }, "vault": { @@ -1154,6 +1159,84 @@ "changedFields": "Campos modificados" } } + }, + "access": { + "granted": { + "label": "Acceso concedido", + "description": "Se ha dado acceso a un usuario con un rol.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + }, + "updated": { + "label": "Acceso modificado", + "description": "Ha cambiado el rol o el estado del acceso de un usuario.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + }, + "revoked": { + "label": "Acceso retirado", + "description": "Se ha retirado el acceso de un usuario.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + } + }, + "user": { + "invited": { + "label": "Usuario invitado", + "description": "Se ha invitado a un usuario a la organización.", + "fields": { + "userId": "Usuario", + "roleId": "Rol" + } + } + }, + "invitation": { + "accepted": { + "label": "Invitación aceptada", + "description": "Un usuario ha aceptado su invitación.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + } + }, + "role": { + "updated": { + "label": "Rol modificado", + "description": "Han cambiado el nombre o los permisos de un rol.", + "fields": { + "roleId": "Rol", + "addedPermissions": "Permisos añadidos", + "removedPermissions": "Permisos retirados" + } + } + }, + "api_key": { + "created": { + "label": "API key creada", + "description": "Se ha creado una API key.", + "fields": { + "name": "Nombre" + } + }, + "revoked": { + "label": "API key revocada", + "description": "Se ha revocado una API key.", + "fields": { + "apiKeyId": "API key", + "name": "Nombre" + } + } } } } diff --git a/src/lib/server/events/index.ts b/src/lib/server/events/index.ts index 6e0f1c2c..1e384a6b 100644 --- a/src/lib/server/events/index.ts +++ b/src/lib/server/events/index.ts @@ -4,6 +4,7 @@ export { InProcessEventBus, actorFromRequest } from './event-bus'; export type { EventBus, InProcessEventBusOptions } from './event-bus'; export type * from './types'; export { resolveProjectScope, type ProjectScopeLookup } from './scope'; +export { publishAfterWrite, type EventPublisher } from './publish'; const GLOBAL_KEY = Symbol.for('gitops.events.bus'); diff --git a/src/lib/server/events/publish.ts b/src/lib/server/events/publish.ts new file mode 100644 index 00000000..6ee48601 --- /dev/null +++ b/src/lib/server/events/publish.ts @@ -0,0 +1,25 @@ +import type { Logger } from 'pino'; +import type { EventBus } from './event-bus'; +import type { DomainEventMap, EventScope, EventType } from './types'; + +export type EventPublisher = Pick; + +/** + * Publishes an event describing a write that already succeeded. Resolving the scope or publishing + * never throws back into the caller: a failure is logged and the request carries on. + */ +export async function publishAfterWrite( + events: EventPublisher | undefined, + log: Pick, + type: K, + payload: DomainEventMap[K], + scope: EventScope | (() => Promise), +): Promise { + if (!events) return; + try { + const resolved = typeof scope === 'function' ? await scope() : scope; + events.publish(type, payload, { scope: resolved }); + } catch (error) { + log.error({ err: error, eventType: type }, `[events] failed to publish ${type}`); + } +} diff --git a/src/lib/server/events/scope.ts b/src/lib/server/events/scope.ts index 4fcda847..7c488f3a 100644 --- a/src/lib/server/events/scope.ts +++ b/src/lib/server/events/scope.ts @@ -2,7 +2,7 @@ import type { EventScope } from './types'; /** Project lookup used to add the organization to a project-scoped event. */ export type ProjectScopeLookup = { - getProject(id: string): Promise<{ organization?: { id: string } | null }>; + getProject(id: string): Promise<{ organization?: { id: string } | null } | null>; }; /** diff --git a/src/modules/auth/application/apikeys.service.test.ts b/src/modules/auth/application/apikeys.service.test.ts index 562504c7..fefd3128 100644 --- a/src/modules/auth/application/apikeys.service.test.ts +++ b/src/modules/auth/application/apikeys.service.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ApiKeysService } from './apikeys.service'; +import { RecordingEventBus } from '#lib/server/events/testing'; import type { ApiKeyView } from '../domain/entities'; function apiKey(overrides: Partial = {}): ApiKeyView { @@ -291,3 +292,90 @@ describe('ApiKeysService', () => { expect(repository.updateKeyMaterial).not.toHaveBeenCalled(); }); }); + +describe('ApiKeysService events', () => { + const projectLookup = { + getProject: async () => ({ id: 'project-1', organization: { id: 'org-1' } }), + }; + + it('publishes api_key.created for a project key with the prefix but never the key', async () => { + const repository = createRepositoryMock(); + const events = new RecordingEventBus(); + const service = new ApiKeysService( + repository, + createRoleRepositoryMock(), + projectLookup, + events, + ); + + const { token, key } = await service.createProjectApiKey({ + projectId: 'project-1', + roleId: 'role-1', + name: 'CI pipeline', + expiresAt: null, + createdByUserId: 'user-1', + }); + + expect(events.types()).toEqual(['api_key.created']); + const [event] = events.ofType('api_key.created'); + expect(event.payload).toEqual({ + apiKeyId: key.id, + name: 'CI pipeline', + keyPrefix: token.slice(0, 10), + projectId: 'project-1', + userId: null, + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + + const serialized = JSON.stringify(events.events); + expect(serialized).not.toContain(token); + expect(serialized).not.toContain(repository.create.mock.calls[0][0].keyHash); + }); + + it('publishes api_key.created for a personal key without a project scope', async () => { + const events = new RecordingEventBus(); + const service = new ApiKeysService(createRepositoryMock(), undefined, undefined, events); + + await service.createApiKey('user-1', 'Laptop', null); + + expect(events.ofType('api_key.created')[0]).toMatchObject({ + payload: { name: 'Laptop', projectId: null, userId: 'user-1' }, + scope: {}, + }); + }); + + it('publishes api_key.revoked for personal and project keys', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => apiKey()); + repository.findByIdAny.mockImplementation(async () => + apiKey({ id: 'key-2', name: 'CI', userId: null, projectId: 'project-1' }), + ); + const events = new RecordingEventBus(); + const service = new ApiKeysService(repository, undefined, projectLookup, events); + + await service.revokeApiKey('user-1', 'key-1'); + await service.revokeProjectApiKey('project-1', 'key-2'); + + expect(events.ofType('api_key.revoked').map((event) => event.payload.apiKeyId)).toEqual([ + 'key-1', + 'key-2', + ]); + expect(events.ofType('api_key.revoked')[1].scope.projectId).toBe('project-1'); + }); + + it('publishes nothing when creation or revocation is rejected', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => apiKey({ revokedAt: '2026-01-01' })); + repository.create.mockImplementation(async () => { + throw new Error('GitDB write failed'); + }); + const events = new RecordingEventBus(); + const service = new ApiKeysService(repository, undefined, undefined, events); + + await expect(service.createApiKey('user-1', ' ', null)).rejects.toThrow(); + await expect(service.createApiKey('user-1', 'Laptop', null)).rejects.toThrow(); + await expect(service.revokeApiKey('user-1', 'key-1')).rejects.toThrow(/already revoked/); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index 115d497f..fad92181 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -2,6 +2,11 @@ import crypto from 'crypto'; import type { ApiKeyView, AuthenticatedApiKey, SessionRole } from '../domain/entities'; import type { RoleDomain } from '../domain/role.domain'; import { ApiKeyRepository } from '../infrastructure/repositories/apikey.repository'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import { resolveProjectScope } from '#lib/server/events/scope'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('api-keys'); const TOKEN_PREFIX = 'gvs_'; const PREFIX_LENGTH = 10; @@ -28,6 +33,7 @@ export class ApiKeysService { private readonly apiKeyRepository: ApiKeyRepository, private readonly roleRepository?: RoleLookup, private readonly projectLookup?: ProjectLookup, + private readonly events?: EventPublisher, ) {} async listActiveApiKeys(userId: string): Promise { @@ -134,6 +140,7 @@ export class ApiKeysService { } await this.apiKeyRepository.revoke(userId, keyId); + await this.publishKeyEvent('api_key.revoked', existing); } async revokeProjectApiKey(projectId: string, keyId: string): Promise { @@ -144,6 +151,27 @@ export class ApiKeysService { } await this.apiKeyRepository.revokeAny(keyId); + await this.publishKeyEvent('api_key.revoked', existing); + } + + /** The key and its hash never leave this service: events only carry the public prefix. */ + private async publishKeyEvent( + type: 'api_key.created' | 'api_key.revoked', + key: Pick, + ): Promise { + await publishAfterWrite( + this.events, + log, + type, + { + apiKeyId: key.id, + name: key.name, + keyPrefix: key.keyPrefix, + projectId: key.projectId, + userId: key.userId, + }, + async () => (key.projectId ? resolveProjectScope(key.projectId, this.projectLookup) : {}), + ); } async regenerateApiKey( @@ -229,6 +257,14 @@ export class ApiKeysService { expiresAt: input.expiresAt, }); + await this.publishKeyEvent('api_key.created', { + id, + name, + keyPrefix, + projectId: input.projectId, + userId: input.userId, + }); + return { token, key: { diff --git a/src/modules/auth/application/invitation.service.test.ts b/src/modules/auth/application/invitation.service.test.ts index 00fafa41..32ae1748 100644 --- a/src/modules/auth/application/invitation.service.test.ts +++ b/src/modules/auth/application/invitation.service.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import crypto from 'crypto'; import { InvitationService } from './invitation.service'; import { UserDomain } from '../domain/user.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; function hash(token: string) { return crypto.createHash('sha256').update(token).digest('hex'); @@ -190,3 +191,79 @@ describe('InvitationService', () => { }); }); }); + +describe('InvitationService events', () => { + let userRepository: FakeUserRepository; + let userAccessRepository: FakeUserAccessRepository; + let events: RecordingEventBus; + let service: InvitationService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + userAccessRepository = new FakeUserAccessRepository(); + events = new RecordingEventBus(); + service = new InvitationService( + userRepository as any, + userAccessRepository as any, + { hashPassword: (password: string) => `hashed:${password}` }, + undefined, + { events, projects: { getProject: async () => ({ organization: { id: 'org-1' } }) } }, + ); + userRepository.rows.push(invitedUser()); + userAccessRepository.rows.push( + { + id: 'access-org', + userId: 'jose-id', + status: 'invited', + roleId: 'role-org', + scope: 'organization', + organizationId: 'org-1', + projectId: null, + } as any, + { + id: 'access-project', + userId: 'jose-id', + status: 'invited', + roleId: 'role-project', + scope: 'project', + organizationId: null, + projectId: 'project-1', + } as any, + { id: 'access-old', userId: 'jose-id', status: 'active', scope: 'organization' } as any, + ); + }); + + it('publishes one invitation.accepted per activated membership, without the token', async () => { + const { token } = await service.issueToken('jose-id'); + + await service.acceptInvitation(token, 'a-strong-password'); + + expect( + events.ofType('invitation.accepted').map((event) => [event.payload, event.scope]), + ).toEqual([ + [ + { userId: 'jose-id', accessId: 'access-org', roleId: 'role-org', scope: 'organization' }, + { organizationId: 'org-1', projectId: null }, + ], + [ + { + userId: 'jose-id', + accessId: 'access-project', + roleId: 'role-project', + scope: 'project', + }, + { organizationId: 'org-1', projectId: 'project-1' }, + ], + ]); + expect(JSON.stringify(events.events)).not.toContain(token); + }); + + it('publishes nothing when the invitation is rejected', async () => { + const { token } = await service.issueToken('jose-id'); + + await expect(service.acceptInvitation('wrong', 'a-strong-password')).rejects.toThrow(); + await expect(service.acceptInvitation(token, 'short')).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/invitation.service.ts b/src/modules/auth/application/invitation.service.ts index 1e0e58b1..1a7baf56 100644 --- a/src/modules/auth/application/invitation.service.ts +++ b/src/modules/auth/application/invitation.service.ts @@ -2,6 +2,12 @@ import crypto from 'crypto'; import type { UserAccessRepository } from '../infrastructure/repositories/user-access.repository'; import type { UserRepository } from '../infrastructure/repositories/user.repository'; import type { PasswordService } from './password.service'; +import { publishAfterWrite } from '#lib/server/events/publish'; +import { resolveProjectScope } from '#lib/server/events/scope'; +import { createLogger } from '#lib/server/logger'; +import type { AccessEventsOptions } from './user-access.service'; + +const log = createLogger('invitation'); export type InvitationView = { userId: string; @@ -21,6 +27,7 @@ export class InvitationService { private readonly userAccessRepository: Pick, private readonly passwordService: Pick, private readonly ttlDays: number = DEFAULT_TTL_DAYS, + private readonly eventOptions: AccessEventsOptions = {}, ) {} /** Issues a new token, stores only its hash, and returns the raw token for the invite link. */ @@ -50,12 +57,25 @@ export class InvitationService { ); const access = await this.userAccessRepository.findByUserId(user.id); + const accepted = access.filter((entry) => entry.status === 'invited'); await Promise.all( - access - .filter((entry) => entry.status === 'invited') - .map((entry) => this.userAccessRepository.update(entry.id, { status: 'active' })), + accepted.map((entry) => this.userAccessRepository.update(entry.id, { status: 'active' })), ); + // one event per activated membership, so each organization/project sees its own + for (const entry of accepted) { + await publishAfterWrite( + this.eventOptions.events, + log, + 'invitation.accepted', + { userId: user.id, accessId: entry.id, roleId: entry.roleId || null, scope: entry.scope }, + async () => + entry.scope === 'project' + ? resolveProjectScope(entry.projectId, this.eventOptions.projects) + : { organizationId: entry.organizationId ?? null, projectId: null }, + ); + } + return { userId: user.id, username: user.username, email: user.email }; } diff --git a/src/modules/auth/application/role.service.test.ts b/src/modules/auth/application/role.service.test.ts index 6eb096f2..ae7a9118 100644 --- a/src/modules/auth/application/role.service.test.ts +++ b/src/modules/auth/application/role.service.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, beforeEach } from 'vitest'; import { RoleService } from './role.service'; import { RoleDomain } from '../domain/role.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; class FakeRoleRepository { rows: RoleDomain[] = []; @@ -288,3 +289,70 @@ describe('RoleService', () => { }); }); }); + +describe('RoleService events', () => { + let roleRepository: FakeRoleRepository; + let events: RecordingEventBus; + let service: RoleService; + + beforeEach(async () => { + roleRepository = new FakeRoleRepository(); + events = new RecordingEventBus(); + service = new RoleService( + roleRepository as any, + new FakeUserRepository() as any, + new FakeUserAccessRepository() as any, + { + events, + projects: { getProject: async () => ({ organization: { id: 'org-1' } }) }, + }, + ); + await roleRepository.create({ + id: 'role-1', + slug: 'project-dev', + name: 'Project Developer', + scope: 'project', + projectId: 'project-1', + permissions: ['project:vault:secrets:read', 'project:vault:secrets:update'], + } as any); + }); + + it('publishes role.updated with the permission diff and the project scope', async () => { + await service.updateRole('role-1', { + permissions: ['project:vault:secrets:read', 'project:vault:secrets:delete'], + }); + + expect(events.types()).toEqual(['role.updated']); + const [event] = events.ofType('role.updated'); + expect(event.payload).toEqual({ + roleId: 'role-1', + name: 'Project Developer', + scope: 'project', + nameChanged: false, + addedPermissions: ['project:vault:secrets:delete'], + removedPermissions: ['project:vault:secrets:update'], + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + }); + + it('reports a rename', async () => { + await service.updateRole('role-1', { name: 'Developer' }); + + expect(events.ofType('role.updated')[0].payload).toMatchObject({ + name: 'Developer', + nameChanged: true, + addedPermissions: [], + removedPermissions: [], + }); + }); + + it('does not publish when creating default roles or on rejected updates', async () => { + await service.createDefaultProjectRoles('project-2'); + await service.createDefaultOrganizationRoles('org-2'); + await expect(service.updateRole('missing', { name: 'X' })).rejects.toThrow(); + await expect(service.updateRole('role-1', { name: ' ' })).rejects.toThrow(); + await expect(service.updateRole('role-1', { permissions: ['nope'] })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/role.service.ts b/src/modules/auth/application/role.service.ts index a298799d..703d3a61 100644 --- a/src/modules/auth/application/role.service.ts +++ b/src/modules/auth/application/role.service.ts @@ -11,6 +11,12 @@ import { PROJECT_DEVELOPER_PERMISSIONS, PROJECT_VIEWER_PERMISSIONS, } from '../domain/role-permissions.data'; +import { publishAfterWrite } from '#lib/server/events/publish'; +import { resolveProjectScope } from '#lib/server/events/scope'; +import { createLogger } from '#lib/server/logger'; +import type { AccessEventsOptions } from './user-access.service'; + +const log = createLogger('roles'); export class RoleService { constructor( @@ -20,6 +26,7 @@ export class RoleService { >, private readonly userRepository: Pick, private readonly userAccessRepository: Pick, + private readonly eventOptions: AccessEventsOptions = {}, ) {} async listRoles(scope: RoleScope = 'cluster', scopeId?: string): Promise { @@ -141,6 +148,7 @@ export class RoleService { throw new Error('Role not found'); } + const previous = { name: role.name, permissions: [...(role.permissions ?? [])] }; const patch: { name?: string; permissions?: string[] } = {}; if (changes.name !== undefined) { @@ -162,6 +170,31 @@ export class RoleService { throw new Error('Failed to update role'); } + const before = new Set(previous.permissions); + const after = new Set(updated.permissions ?? []); + await publishAfterWrite( + this.eventOptions.events, + log, + 'role.updated', + { + roleId: updated.id, + name: updated.name, + scope: updated.scope, + nameChanged: previous.name !== updated.name, + addedPermissions: [...after].filter((permission) => !before.has(permission)), + removedPermissions: [...before].filter((permission) => !after.has(permission)), + }, + async () => { + if (updated.scope === 'project') { + return resolveProjectScope(updated.projectId, this.eventOptions.projects); + } + if (updated.scope === 'organization') { + return { organizationId: updated.organizationId ?? null, projectId: null }; + } + return {}; + }, + ); + return updated.toJson(); } diff --git a/src/modules/auth/application/user-access.service.test.ts b/src/modules/auth/application/user-access.service.test.ts index 6e23b908..64e31e79 100644 --- a/src/modules/auth/application/user-access.service.test.ts +++ b/src/modules/auth/application/user-access.service.test.ts @@ -7,6 +7,7 @@ import { import { RoleDomain } from '../domain/role.domain'; import { UserAccessDomain } from '../domain/user-access.domain'; import { UserDomain } from '../domain/user.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; function role(input: { id: string; @@ -78,6 +79,19 @@ class FakeUserRepository { this.rows = this.rows.filter((entry) => entry.id !== id); } + roleRepository?: FakeRoleRepository; + + async updateRoleId(id: string, roleId: string) { + const row = this.rows.find((entry) => entry.id === id); + const nextRole = await this.roleRepository?.findById(roleId); + if (row && nextRole) row.role = nextRole; + } + + async updateStatus(id: string, status: 'active' | 'invited') { + const row = this.rows.find((entry) => entry.id === id); + if (row) row.status = status; + } + async createUser(input: { id: string; username: string; @@ -657,3 +671,216 @@ describe('UserAccessService', () => { ).rejects.toThrow(/does not belong/); }); }); + +describe('UserAccessService events', () => { + let userRepository: FakeUserRepository; + let roleRepository: FakeRoleRepository; + let userAccessRepository: FakeUserAccessRepository; + let events: RecordingEventBus; + let service: UserAccessService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + roleRepository = new FakeRoleRepository(); + userAccessRepository = new FakeUserAccessRepository(); + userAccessRepository.userRepository = userRepository; + userAccessRepository.roleRepository = roleRepository; + userRepository.roleRepository = roleRepository; + events = new RecordingEventBus(); + service = new UserAccessService( + userRepository as any, + roleRepository as any, + userAccessRepository as any, + { hashPassword: (password: string) => `hashed:${password}` }, + { sendInvitation: vi.fn(async () => {}) }, + { issueToken: vi.fn(async () => ({ token: 'raw-token', expiresAt: '2024-01-08' })) }, + { events, projects: { getProject: async () => ({ organization: { id: 'gitops' } }) } }, + ); + roleRepository.rows.push( + role({ id: 'cluster-user-id', slug: 'cluster-user' }), + role({ id: 'cluster-admin-id', slug: 'cluster-admin' }), + role({ + id: 'org-dev', + slug: 'org-developer', + scope: 'organization', + organizationId: 'gitops', + }), + role({ id: 'org-admin', slug: 'org-admin', scope: 'organization', organizationId: 'gitops' }), + role({ id: 'project-dev', slug: 'project-dev', scope: 'project', projectId: 'shop' }), + ); + userRepository.rows.push( + user({ id: 'ana', username: 'ana', email: 'ana@example.com', role: roleRepository.rows[0] }), + ); + }); + + it('publishes access.granted for organization and project assignments', async () => { + const orgAccess = await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + const projectAccess = await service.assignProjectUser({ + projectId: 'shop', + userId: 'ana', + roleId: 'project-dev', + }); + + expect(events.ofType('access.granted').map((event) => [event.payload, event.scope])).toEqual([ + [ + { + accessId: orgAccess.id, + userId: 'ana', + roleId: 'org-dev', + scope: 'organization', + status: 'active', + }, + { organizationId: 'gitops', projectId: null }, + ], + [ + { + accessId: projectAccess.id, + userId: 'ana', + roleId: 'project-dev', + scope: 'project', + status: 'active', + }, + { organizationId: 'gitops', projectId: 'shop' }, + ], + ]); + }); + + it('publishes access.granted and user.invited for an invitation, without token or URL', async () => { + await service.inviteOrganizationUser({ + organizationId: 'gitops', + organizationName: 'GitOps', + email: 'new@example.com', + inviteUrl: 'https://gitops.example.com/auth/invitation', + }); + + expect(events.types()).toEqual(['access.granted', 'user.invited']); + const invited = userRepository.rows.find((row) => row.email === 'new@example.com')!; + expect(events.ofType('user.invited')[0].payload).toEqual({ + userId: invited.id, + roleId: 'org-dev', + organizationId: 'gitops', + }); + const serialized = JSON.stringify(events.events); + expect(serialized).not.toContain('raw-token'); + expect(serialized).not.toContain('auth/invitation'); + expect(serialized).not.toContain('new@example.com'); + }); + + it('publishes access.updated with the previous role and status', async () => { + const access = await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + events.clear(); + + await service.updateAccess({ + accessId: access.id, + scope: 'organization', + scopeId: 'gitops', + roleId: 'org-admin', + status: 'active', + }); + + expect(events.ofType('access.updated')[0].payload).toEqual({ + accessId: access.id, + userId: 'ana', + roleId: 'org-admin', + scope: 'organization', + status: 'active', + previousRoleId: 'org-dev', + previousStatus: 'active', + }); + }); + + it('publishes access.updated for a cluster role change', async () => { + await service.updateAccess({ + accessId: 'ana', + scope: 'cluster', + roleId: 'cluster-admin-id', + status: 'active', + }); + + const [event] = events.ofType('access.updated'); + expect(event.payload).toMatchObject({ + accessId: 'ana', + userId: 'ana', + scope: 'cluster', + roleId: 'cluster-admin-id', + previousRoleId: 'cluster-user-id', + }); + expect(event.scope).toEqual({}); + }); + + it('publishes access.revoked for a project membership', async () => { + const access = await service.assignProjectUser({ + projectId: 'shop', + userId: 'ana', + roleId: 'project-dev', + }); + events.clear(); + + await service.removeAccess({ accessId: access.id, scope: 'project', scopeId: 'shop' }); + + expect(events.ofType('access.revoked').map((event) => event.payload.accessId)).toEqual([ + access.id, + ]); + }); + + it('revokes every membership and the account when removing an organization user', async () => { + const orgAccess = await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + const projectAccess = await service.assignProjectUser({ + projectId: 'shop', + userId: 'ana', + roleId: 'project-dev', + }); + events.clear(); + + await service.removeAccess({ + accessId: orgAccess.id, + scope: 'organization', + scopeId: 'gitops', + }); + + expect( + events.ofType('access.revoked').map((event) => [event.payload.accessId, event.payload.scope]), + ).toEqual([ + [orgAccess.id, 'organization'], + [projectAccess.id, 'project'], + ['ana', 'cluster'], + ]); + }); + + it('publishes nothing when the operation is rejected', async () => { + await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + events.clear(); + + await expect( + service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }), + ).rejects.toThrow(/already has access/); + await expect( + service.assignProjectUser({ projectId: 'shop', userId: 'ana', roleId: 'org-dev' }), + ).rejects.toThrow(); + await expect( + service.removeAccess({ accessId: 'missing', scope: 'project', scopeId: 'shop' }), + ).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/user-access.service.ts b/src/modules/auth/application/user-access.service.ts index 516d2248..1f4ef70e 100644 --- a/src/modules/auth/application/user-access.service.ts +++ b/src/modules/auth/application/user-access.service.ts @@ -7,6 +7,13 @@ import type { RoleRepository } from '../infrastructure/repositories/role.reposit import type { UserAccessRepository } from '../infrastructure/repositories/user-access.repository'; import type { UserRepository } from '../infrastructure/repositories/user.repository'; import type { PasswordService } from './password.service'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import { resolveProjectScope, type ProjectScopeLookup } from '#lib/server/events/scope'; +import type { EventScope } from '#lib/server/events'; +import type { AccessPayload } from '#lib/events/domain-events'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('user-access'); type UserAccessRow = { id: string; @@ -22,6 +29,11 @@ type UserAccessRow = { createdAt: string; }; +type AccessEntry = Pick< + UserAccessDomain, + 'id' | 'userId' | 'roleId' | 'scope' | 'organizationId' | 'projectId' | 'status' +> & { user?: UserAccessDomain['user'] }; + export type InvitationNotifierPort = { sendInvitation(input: { email: string; @@ -38,7 +50,15 @@ export type InvitationTokenIssuerPort = { issueToken(userId: string): Promise<{ token: string; expiresAt: string }>; }; +export type AccessEventsOptions = { + events?: EventPublisher; + projects?: ProjectScopeLookup; +}; + export class UserAccessService { + private readonly events?: EventPublisher; + private readonly projects?: ProjectScopeLookup; + constructor( private readonly userRepository: Pick< UserRepository, @@ -59,7 +79,11 @@ export class UserAccessService { private readonly passwordService: Pick, private readonly invitationNotifier: InvitationNotifierPort, private readonly invitationTokens: InvitationTokenIssuerPort, - ) {} + options: AccessEventsOptions = {}, + ) { + this.events = options.events; + this.projects = options.projects; + } async listUsers(scope: RoleScope, scopeId?: string): Promise { this.validateScope(scope, scopeId); @@ -155,6 +179,14 @@ export class UserAccessService { expiresAt: invitation.expiresAt, invitedBy: input.invitedBy ?? null, }); + + await publishAfterWrite( + this.events, + log, + 'user.invited', + { userId: user.id, roleId: role.id, organizationId }, + { organizationId, projectId: null }, + ); } return this.toRow(access); @@ -273,6 +305,7 @@ export class UserAccessService { status: string; }): Promise { const access = await this.findAccessInScope(input.accessId, input.scope, input.scopeId); + const before = this.snapshot(access); if (input.scope === 'cluster') { const role = await this.findRoleForScope(input.roleId, 'cluster', ''); const status = this.sanitizeStatus(input.status); @@ -282,6 +315,7 @@ export class UserAccessService { ]); const updated = await this.userRepository.findById(access.id); if (!updated) throw new Error('Failed to update user access'); + await this.publishAccessUpdated(before, role.id, status); return this.toClusterRow(updated); } @@ -292,6 +326,7 @@ export class UserAccessService { const updated = await this.userAccessRepository.findById(access.id); if (!updated) throw new Error('Failed to update user access'); + await this.publishAccessUpdated(before, role.id, status); return this.toRow(updated); } @@ -306,10 +341,79 @@ export class UserAccessService { const userAccess = await this.userAccessRepository.findByUserId(access.userId); await Promise.all(userAccess.map((entry) => this.userAccessRepository.deleteById(entry.id))); await this.userRepository.deleteById(userId); + + // removing the account revokes every membership it had, plus the account itself + for (const entry of userAccess) await this.publishAccess('access.revoked', entry); + await this.publishAccess( + 'access.revoked', + input.scope === 'cluster' + ? access + : { + id: userId, + userId, + roleId: access.user?.role?.id ?? '', + scope: 'cluster', + organizationId: null, + projectId: null, + status: access.user?.status ?? 'active', + }, + ); return; } await this.userAccessRepository.deleteById(access.id); + await this.publishAccess('access.revoked', access); + } + + private async publishAccess( + type: 'access.granted' | 'access.revoked', + entry: AccessEntry, + ): Promise { + await publishAfterWrite(this.events, log, type, this.accessPayload(entry), () => + this.accessScope(entry), + ); + } + + private async publishAccessUpdated( + before: AccessEntry, + roleId: string, + status: UserAccessStatus, + ): Promise { + await publishAfterWrite( + this.events, + log, + 'access.updated', + { + ...this.accessPayload({ ...before, roleId, status }), + previousRoleId: before.roleId || null, + previousStatus: before.status === 'invited' ? 'invited' : 'active', + }, + () => this.accessScope(before), + ); + } + + // copy: the repository may mutate the stored entry in place on update + private snapshot(entry: AccessEntry): AccessEntry { + const { id, userId, roleId, scope, organizationId, projectId, status } = entry; + return { id, userId, roleId, scope, organizationId, projectId, status }; + } + + private accessPayload(entry: AccessEntry): AccessPayload { + return { + accessId: entry.id, + userId: entry.userId, + roleId: entry.roleId || null, + scope: entry.scope, + status: entry.status === 'invited' ? 'invited' : 'active', + }; + } + + private async accessScope(entry: AccessEntry): Promise { + if (entry.scope === 'project') return resolveProjectScope(entry.projectId, this.projects); + if (entry.scope === 'organization') { + return { organizationId: entry.organizationId ?? null, projectId: null }; + } + return {}; } async resendInvitation(input: { @@ -377,6 +481,7 @@ export class UserAccessService { const created = await this.userAccessRepository.findOne(lookup); if (!created) throw new Error('Failed to create user access'); + await this.publishAccess('access.granted', created); return created; } diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index 4fa028d8..c978ab1c 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -19,6 +19,9 @@ import { GoogleOidcClient } from './infrastructure/oidc/google-oidc.client'; import { InvitationNotifier } from './infrastructure/notifications/invitation.notifier'; import { PasswordResetNotifier } from './infrastructure/notifications/password-reset.notifier'; import { projectService } from '../projects'; +import { eventBus } from '#lib/server/events'; + +const accessEvents = { events: eventBus, projects: projectService }; const userRepository = new UserRepository(); const roleRepository = new RoleRepository(); @@ -29,7 +32,12 @@ const passwordResetNotifier = new PasswordResetNotifier(); export const passwordService = new PasswordService(); const sessionService = new SessionService(passwordService); -export const apiKeysService = new ApiKeysService(apiKeyRepository, roleRepository, projectService); +export const apiKeysService = new ApiKeysService( + apiKeyRepository, + roleRepository, + projectService, + eventBus, +); export const authService = new AuthService( userRepository, @@ -39,11 +47,18 @@ export const authService = new AuthService( ); export const userService = new UserService(userRepository, roleRepository, passwordService); export const profileService = new ProfileService(userRepository, passwordService); -export const roleService = new RoleService(roleRepository, userRepository, userAccessRepository); +export const roleService = new RoleService( + roleRepository, + userRepository, + userAccessRepository, + accessEvents, +); export const invitationService = new InvitationService( userRepository, userAccessRepository, passwordService, + undefined, + accessEvents, ); export const passwordResetService = new PasswordResetService( userRepository, @@ -57,6 +72,7 @@ export const userAccessService = new UserAccessService( passwordService, invitationNotifier, invitationService, + accessEvents, ); export const ssoService = new SsoService( readGoogleSsoConfig,