diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 02dcc9c7..b13b5402 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -1,5 +1,6 @@ import type { Handle } from '@sveltejs/kit'; -import { authService, canAccessAdminArea, ensureAuthReady } from './modules/auth'; +import { authService, cancanService, ensureAuthReady } from './modules/auth'; +import { ensureOrganizationReady, organizationService } from './modules/organization'; import { getGitDb } from '$lib/server/gitdb'; getGitDb(); @@ -10,6 +11,8 @@ export const handle: Handle = async ({ event, resolve }) => { } await ensureAuthReady(); + await ensureOrganizationReady(); + const sessionCookie = event.cookies.get('pos_session'); const currentUser = await authService.resolveAuthenticatedUser(sessionCookie); @@ -22,8 +25,18 @@ export const handle: Handle = async ({ event, resolve }) => { return new Response(null, { status: 302, headers: { location: '/login' } }); } - if (event.url.pathname.startsWith('/settings') || event.url.pathname.startsWith('/api/system')) { - if (!canAccessAdminArea(currentUser)) { + 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))) { + return new Response(null, { status: 302, headers: { location: '/' } }); + } + } else if ( + event.url.pathname.startsWith('/cluster-settings') || + event.url.pathname.startsWith('/api/system') || + event.url.pathname.startsWith('/api/organizations') + ) { + if (!cancanService.canAccessAdminArea(currentUser)) { return new Response(null, { status: 302, headers: { location: '/' } }); } } diff --git a/src/lib/components/AppNavbar.svelte b/src/lib/components/AppNavbar.svelte index ba31a4ba..1659b32a 100644 --- a/src/lib/components/AppNavbar.svelte +++ b/src/lib/components/AppNavbar.svelte @@ -1,12 +1,12 @@ + + + {title} + + +
+ {#if detailError} +
+ {detailError} +
+ {/if} + {#if detailSuccess} +
+ {detailSuccess} +
+ {/if} + +
+ + +
+
+

Permissions

+
+ {#if !isCreate} + + {/if} + + + + Cancel + +
+
+
+ + + + + + + + + {#each visiblePermissionRows as permissionRow (permissionRow.key)} + + + + + + {#if expanded[permissionRow.key] && permissionRow.permissions.length} + + + + {/if} + {/each} + +
ResourcePermission
+
+ {#if hasExpandableContent(permissionRow)} + + {:else} + + {/if} + + {rowLabel(permissionRow)} + +
+
+ {#if permissionRow.permissions.length} + {#key `${permissionRow.key}:${accessLevel(permissionRow)}`} + + {/key} + {:else} + Section group + {/if} +
+
+ {#each visibleRowPermissions(permissionRow) as permission} + {@const action = actionFrom(permission)} + {#key `${permission}:${selectedPermissionsKey}`} + + {/key} + {/each} +
+
+
+
+
+
diff --git a/src/lib/components/RolePermissions.svelte b/src/lib/components/RolePermissions.svelte new file mode 100644 index 00000000..4a98ff4f --- /dev/null +++ b/src/lib/components/RolePermissions.svelte @@ -0,0 +1,82 @@ + + + + {title} + + +
+
+
+

{title}

+

{description}

+
+ + + Add Role + +
+ + {#if roles.length === 0} +
+ No roles found. +
+ {:else} +
+ + + + + + + + + {#each roles as role (role.id)} + + + + + {/each} + +
NameSlug
+ + + {role.name} + + + {role.slug} +
+
+ {/if} +
diff --git a/src/lib/components/Users.svelte b/src/lib/components/Users.svelte new file mode 100644 index 00000000..1b25345d --- /dev/null +++ b/src/lib/components/Users.svelte @@ -0,0 +1,578 @@ + + + + {title} + + +
+
+
+

{title}

+

{description}

+
+ +
+ +
+
+ + +
+
+ + {#if error} +
+ {error} +
+ {/if} + + {#if success} +
+ {success} +
+ {/if} + + {#if filteredUsers.length === 0} +
+ +

+ {users.length === 0 ? 'No users found.' : 'No users match your search.'} +

+
+ {:else} +
+
+ + + + + + {#if scope === 'cluster'} + + {/if} + + + + + + + + {#each filteredUsers as user (user.id)} + + + + {#if scope === 'cluster'} + + {/if} + + + + + + {/each} + +
UserEmailOrganizationsRoleStatusAddedActions
{user.username}{user.email || '-'} + {#if user.organizations?.length} +
+ {#each user.organizations as organization (organization.id)} + + {organization.name} + {#if organization.role} + · + {organization.role} + {/if} + + {/each} +
+ {:else} + - + {/if} +
+
+ + {#if openRoleMenuId === user.id} +
+ {#each roles as role (role.id)} + + {/each} +
+ {/if} +
+
+ + + {user.status === 'invited' ? 'Invited' : 'Active'} + + {formatDate(user.createdAt)} +
+ {#if user.status === 'invited'} + + {/if} + +
+
+
+
+ {/if} +
+ +{#if addModalOpen} + +
+ +
+{/if} + +{#if removeModalUser} + +
+ +
+{/if} diff --git a/src/lib/config/permissions.ts b/src/lib/config/permissions.ts new file mode 100644 index 00000000..961e1a10 --- /dev/null +++ b/src/lib/config/permissions.ts @@ -0,0 +1,133 @@ +export const defaultActions = ['read', 'create', 'update', 'delete', 'all']; + +export function grantsFor(section: string, resource: string, extraActions: string[] = []) { + return [...defaultActions, ...extraActions].map((action) => `${section}:${resource}:${action}`); +} + +const permissions = { + version: 1, + sections: { + cluster: { + resource: 'cluster', + sections: { + organization: { + resource: 'organization', + permissions: grantsFor('cluster', 'organization'), + }, + users: { + resource: 'users', + permissions: grantsFor('cluster', 'users', ['invite']), + }, + settings: { + resource: 'settings', + permissions: grantsFor('cluster', 'settings'), + }, + }, + }, + organization: { + resource: 'organization', + sections: { + projects: { + resource: 'projects', + permissions: grantsFor('organization', 'projects'), + }, + users: { + resource: 'users', + permissions: grantsFor('organization', 'users', ['invite']), + }, + roles: { + resource: 'roles', + permissions: grantsFor('organization', 'roles'), + }, + backups: { + resource: 'backups', + permissions: grantsFor('organization', 'backups'), + }, + 'server-keys': { + resource: 'server-keys', + permissions: grantsFor('organization', 'server-keys'), + }, + audit: { + resource: 'audit', + permissions: grantsFor('organization', 'audit'), + }, + }, + }, + project: { + resource: 'project', + permissions: grantsFor('project', 'project'), + sections: { + users: { + resource: 'users', + permissions: grantsFor('project', 'users', ['invite']), + }, + roles: { + resource: 'roles', + permissions: grantsFor('project', 'roles'), + }, + 'server-keys': { + resource: 'server-keys', + permissions: grantsFor('project', 'server-keys'), + }, + audit: { + resource: 'audit', + permissions: grantsFor('project', 'audit'), + }, + modules: { + resource: 'modules', + sections: { + vault: { + resource: 'vault', + sections: { + secrets: { + resource: 'secrets', + permissions: grantsFor('project:vault', 'secrets', ['import', 'export']), + }, + environments: { + resource: 'environments', + permissions: grantsFor('project:vault', 'environments'), + }, + }, + }, + codereport: { + resource: 'codereport', + sections: { + reports: { + resource: 'reports', + permissions: grantsFor('project:codereport', 'reports'), + }, + dependencies: { + resource: 'dependencies', + permissions: grantsFor('project:codereport', 'dependencies'), + }, + vulnerabilities: { + resource: 'vulnerabilities', + permissions: grantsFor('project:codereport', 'vulnerabilities'), + }, + }, + }, + stateiac: { + resource: 'stateiac', + sections: { + stacks: { + resource: 'stacks', + permissions: grantsFor('project:stateiac', 'stacks'), + }, + states: { + resource: 'states', + permissions: grantsFor('project:stateiac', 'states'), + }, + history: { + resource: 'history', + permissions: grantsFor('project:stateiac', 'history'), + }, + }, + }, + }, + }, + }, + }, + }, +}; + +export default permissions; diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index dd5c6206..16f199bc 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -24,6 +24,9 @@ export const RoleEntity = entity('roles', { id: uuid().primaryKey(), slug: text().notNull(), name: text().notNull(), + scope: text().notNull().default('cluster'), + organizationId: uuid(), + projectId: uuid(), permissions: json() .notNull() .$defaultFn(() => []), @@ -49,26 +52,39 @@ export const ApiKeyEntity = entity('api_keys', { .$defaultFn(() => new Date().toISOString()), }); +export const UserAccessEntity = entity('user_access', { + id: uuid().primaryKey(), + userId: uuid().notNull(), + roleId: uuid().notNull(), + scope: text().notNull(), + organizationId: uuid(), + projectId: uuid(), + status: text().notNull().default('active'), + createdAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), +}); + export const relations = defineRelations(); relations.for(UserEntity, ({ one, many }) => ({ role: one(RoleEntity, { fields: ['roleId'], references: ['id'] }), apiKeys: many(ApiKeyEntity, { fields: ['id'], references: ['userId'] }), + access: many(UserAccessEntity, { fields: ['id'], references: ['userId'] }), })); relations.for(ApiKeyEntity, ({ one }) => ({ user: one(UserEntity, { fields: ['userId'], references: ['id'] }), })); -export const ProjectEntity = entity('projects', { +export const OrganizationEntity = entity('organizations', { id: uuid().primaryKey(), slug: text().notNull(), name: text().notNull(), description: text(), - status: text().notNull().default('active'), - modules: json() - .notNull() - .$defaultFn(() => ({ vault: true, openreport: true, stateiac: true })), createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), @@ -77,14 +93,16 @@ export const ProjectEntity = entity('projects', { .$defaultFn(() => new Date().toISOString()), }); -export const ProjectRoleEntity = entity('project_roles', { +export const ProjectEntity = entity('projects', { id: uuid().primaryKey(), - projectId: uuid().notNull(), + organizationId: uuid().notNull(), slug: text().notNull(), name: text().notNull(), - permissions: json() + description: text(), + status: text().notNull().default('active'), + modules: json() .notNull() - .$defaultFn(() => []), + .$defaultFn(() => ({ vault: true, openreport: true, stateiac: true })), createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), @@ -93,10 +111,27 @@ export const ProjectRoleEntity = entity('project_roles', { .$defaultFn(() => new Date().toISOString()), }); -relations.for(ProjectEntity, ({ many }) => ({ - roles: many(ProjectRoleEntity, { fields: ['id'], references: ['projectId'] }), +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'] }), })); -relations.for(ProjectRoleEntity, ({ one }) => ({ +relations.for(RoleEntity, ({ one, many }) => ({ + organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), project: one(ProjectEntity, { fields: ['projectId'], references: ['id'] }), + access: many(UserAccessEntity, { fields: ['id'], references: ['roleId'] }), +})); + +relations.for(UserAccessEntity, ({ one }) => ({ + user: one(UserEntity, { fields: ['userId'], references: ['id'] }), + role: one(RoleEntity, { fields: ['roleId'], references: ['id'] }), + organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), + project: one(ProjectEntity, { fields: ['projectId'], references: ['id'] }), +})); + +relations.for(OrganizationEntity, ({ many }) => ({ + projects: many(ProjectEntity, { fields: ['id'], references: ['organizationId'] }), + roles: many(RoleEntity, { fields: ['id'], references: ['organizationId'] }), + access: many(UserAccessEntity, { fields: ['id'], references: ['organizationId'] }), })); diff --git a/src/lib/permissions/index.test.ts b/src/lib/permissions/index.test.ts index 387e40e8..2c52c87b 100644 --- a/src/lib/permissions/index.test.ts +++ b/src/lib/permissions/index.test.ts @@ -1,97 +1,23 @@ import { describe, expect, it } from 'vitest'; import { - can, - hasPermission, isValidPermissionGrant, + isPermissionActionSelected, togglePermissionAction, toggleSectionAll, isSectionFullyGranted, + toStoredPermissionGrant, } from './index'; -// Fixture roles/users mirroring the RBAC spec: an admin with full access, a developer -// with read/create/update (no delete), and a role scoped to a single section only. -const adminUser = { - role: { permissions: ['vault:all', 'openreport:all', 'stateiac:all'] }, -}; - -const developerUser = { - role: { - permissions: [ - 'vault:read', - 'vault:create', - 'vault:update', - 'openreport:read', - 'openreport:create', - 'openreport:update', - 'stateiac:read', - 'stateiac:create', - 'stateiac:update', - ], - }, -}; - -const vaultOnlyUser = { - role: { permissions: ['vault:all'] }, -}; - -const noRoleUser = { role: null }; - -describe('hasPermission', () => { - it('denies by default when there are no grants', () => { - expect(hasPermission([], 'vault:read')).toBe(false); - expect(hasPermission(null, 'vault:read')).toBe(false); - expect(hasPermission(undefined, 'vault:read')).toBe(false); - }); - +describe('isPermissionActionSelected', () => { it('matches an exact grant', () => { - expect(hasPermission(['vault:read'], 'vault:read')).toBe(true); - expect(hasPermission(['vault:read'], 'vault:delete')).toBe(false); + expect(isPermissionActionSelected(['vault:read'], 'vault', 'read')).toBe(true); + expect(isPermissionActionSelected(['vault:read'], 'vault', 'delete')).toBe(false); }); - it('honors the section:all shortcut', () => { - expect(hasPermission(['vault:all'], 'vault:read')).toBe(true); - expect(hasPermission(['vault:all'], 'vault:delete')).toBe(true); - expect(hasPermission(['vault:all'], 'openreport:read')).toBe(false); - }); -}); - -describe('can', () => { - it('grants admin every action in every section', () => { - for (const permission of [ - 'vault:read', - 'vault:create', - 'vault:update', - 'vault:delete', - 'openreport:delete', - 'stateiac:delete', - ] as const) { - expect(can(adminUser, permission)).toBe(true); - } - }); - - it('grants developer read/create/update but never delete, across all sections', () => { - for (const section of ['vault', 'openreport', 'stateiac'] as const) { - expect(can(developerUser, `${section}:read`)).toBe(true); - expect(can(developerUser, `${section}:create`)).toBe(true); - expect(can(developerUser, `${section}:update`)).toBe(true); - expect(can(developerUser, `${section}:delete`)).toBe(false); - } - }); - - it('scopes a single-section role to only that section', () => { - expect(can(vaultOnlyUser, 'vault:read')).toBe(true); - expect(can(vaultOnlyUser, 'vault:delete')).toBe(true); - expect(can(vaultOnlyUser, 'openreport:read')).toBe(false); - expect(can(vaultOnlyUser, 'stateiac:read')).toBe(false); - }); - - it('denies a user with no role', () => { - expect(can(noRoleUser, 'vault:read')).toBe(false); - }); - - it('denies a null/undefined user', () => { - expect(can(null, 'vault:read')).toBe(false); - expect(can(undefined, 'vault:read')).toBe(false); + it('honors the section:all shortcut for UI checkboxes', () => { + expect(isPermissionActionSelected(['vault:all'], 'vault', 'read')).toBe(true); + expect(isPermissionActionSelected(['vault:all'], 'vault', 'delete')).toBe(true); + expect(isPermissionActionSelected(['vault:all'], 'openreport', 'read')).toBe(false); }); }); @@ -100,6 +26,11 @@ describe('isValidPermissionGrant', () => { expect(isValidPermissionGrant('vault:read')).toBe(true); expect(isValidPermissionGrant('stateiac:delete')).toBe(true); expect(isValidPermissionGrant('openreport:all')).toBe(true); + expect(isValidPermissionGrant('project:vault:secrets:import')).toBe(true); + expect(isValidPermissionGrant('organization:users:invite')).toBe(true); + expect(isValidPermissionGrant('project:all')).toBe(true); + expect(isValidPermissionGrant('users:invite')).toBe(true); + expect(isValidPermissionGrant('vault:secrets:import')).toBe(true); }); it('rejects unknown sections, actions, or malformed strings', () => { @@ -110,6 +41,18 @@ describe('isValidPermissionGrant', () => { }); }); +describe('toStoredPermissionGrant', () => { + it('maps UI permissions to canonical stored grants for the role scope', () => { + expect(toStoredPermissionGrant('project:project:all', 'project')).toBe('project:all'); + expect(toStoredPermissionGrant('project:vault:secrets:read', 'project')).toBe( + 'vault:secrets:read', + ); + expect(toStoredPermissionGrant('organization:users:invite', 'organization')).toBe( + 'users:invite', + ); + }); +}); + describe('togglePermissionAction', () => { it('adds and removes an individual grant', () => { let permissions: string[] = []; @@ -141,8 +84,11 @@ describe('toggleSectionAll', () => { describe('isSectionFullyGranted', () => { it('reports true only when the all shortcut is present', () => { expect(isSectionFullyGranted(['vault:all'], 'vault')).toBe(true); - expect(isSectionFullyGranted(['vault:read', 'vault:create', 'vault:update', 'vault:delete'], 'vault')).toBe( - false, - ); + expect( + isSectionFullyGranted( + ['vault:read', 'vault:create', 'vault:update', 'vault:delete'], + 'vault', + ), + ).toBe(false); }); }); diff --git a/src/lib/permissions/index.ts b/src/lib/permissions/index.ts index 57e4ee2b..4c04b5fc 100644 --- a/src/lib/permissions/index.ts +++ b/src/lib/permissions/index.ts @@ -1,6 +1,4 @@ -type PermissionAwareUser = { - role?: { slug?: string | null; permissions?: readonly string[] | null } | null; -} | null | undefined; +import permissionsCatalog from '$lib/config/permissions'; export const PERMISSION_SECTIONS = ['vault', 'openreport', 'stateiac'] as const; export type PermissionSection = (typeof PERMISSION_SECTIONS)[number]; @@ -22,13 +20,58 @@ export const PERMISSION_ACTION_LABELS: Record = { }; export type Permission = `${PermissionSection}:${PermissionAction}`; -export type PermissionGrant = Permission | `${PermissionSection}:all`; +export type PermissionGrant = string; +export type PermissionScope = 'cluster' | 'organization' | 'project'; + +type PermissionConfigSection = { + permissions?: string[]; + sections?: Record | PermissionConfigSection[]; +}; + +function permissionChildren(section: PermissionConfigSection): PermissionConfigSection[] { + if (!section.sections) return []; + return Array.isArray(section.sections) ? section.sections : Object.values(section.sections); +} + +function collectPermissionGrants(section: PermissionConfigSection): string[] { + return [ + ...(section.permissions ?? []), + ...permissionChildren(section).flatMap((child) => collectPermissionGrants(child)), + ]; +} + +function storedPermissionFor(permission: string): string { + const parts = permission.split(':'); + if (parts.length < 3) return permission; + return parts.slice(1).join(':'); +} + +export function toStoredPermissionGrant( + permission: string, + scope: PermissionScope, +): PermissionGrant { + if (permission.startsWith(`${scope}:${scope}:`)) { + return permission.replace(`${scope}:${scope}:`, `${scope}:`); + } + + if (permission.startsWith(`${scope}:`)) { + return permission.slice(scope.length + 1); + } + + return permission; +} + +const CATALOG_PERMISSION_GRANTS = Object.values(permissionsCatalog.sections).flatMap((section) => + collectPermissionGrants(section), +); export const ALL_PERMISSION_GRANTS: PermissionGrant[] = [ + ...CATALOG_PERMISSION_GRANTS, + ...CATALOG_PERMISSION_GRANTS.map((permission) => storedPermissionFor(permission)), ...PERMISSION_SECTIONS.flatMap((section) => PERMISSION_ACTIONS.map((action) => `${section}:${action}` as Permission), ), - ...PERMISSION_SECTIONS.map((section) => `${section}:all` as PermissionGrant), + ...PERMISSION_SECTIONS.map((section) => `${section}:all`), ]; const ALL_PERMISSION_GRANTS_SET = new Set(ALL_PERMISSION_GRANTS); @@ -37,25 +80,18 @@ export function isValidPermissionGrant(value: string): value is PermissionGrant return ALL_PERMISSION_GRANTS_SET.has(value); } -export function hasPermission( - grants: readonly string[] | null | undefined, - permission: Permission, +export function isPermissionActionSelected( + grants: readonly string[], + section: PermissionSection, + action: PermissionAction, ): boolean { if (!grants || grants.length === 0) return false; - const [section] = permission.split(':') as [PermissionSection, PermissionAction]; + const permission: Permission = `${section}:${action}`; return grants.includes(permission) || grants.includes(`${section}:all`); } -export function can(user: PermissionAwareUser, permission: Permission): boolean { - return hasPermission(user?.role?.permissions, permission); -} - -export function isAdmin(user: PermissionAwareUser): boolean { - return user?.role?.slug === 'admin'; -} - export function isSectionFullyGranted( permissions: readonly string[], section: PermissionSection, @@ -83,7 +119,10 @@ export function togglePermissionAction( } /** Toggles the `section:all` shortcut, replacing any explicit grants for that section. */ -export function toggleSectionAll(permissions: readonly string[], section: PermissionSection): string[] { +export function toggleSectionAll( + permissions: readonly string[], + section: PermissionSection, +): string[] { const withoutSection = permissions.filter((p) => !p.startsWith(`${section}:`)); return isSectionFullyGranted(permissions, section) ? withoutSection diff --git a/src/modules/auth/application/auth.service.test.ts b/src/modules/auth/application/auth.service.test.ts new file mode 100644 index 00000000..38d540f5 --- /dev/null +++ b/src/modules/auth/application/auth.service.test.ts @@ -0,0 +1,136 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { AuthService } from './auth.service'; +import { RoleDomain } from '../domain/role.domain'; +import { UserDomain } from '../domain/user.domain'; + +function role(input: { id: string; slug: string; permissions?: string[] }) { + return new RoleDomain({ + id: input.id, + slug: input.slug, + name: input.slug, + scope: 'cluster', + permissions: input.permissions ?? [], + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +function user(input: { id: string; username: string; role: RoleDomain | null }) { + return new UserDomain({ + id: input.id, + username: input.username, + email: null, + password: 'hashed', + role: input.role, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +class FakeUserRepository { + rows = new Map(); + updatedRoleIds: Array<{ userId: string; roleId: string }> = []; + + async findByUsername(username: string) { + return [...this.rows.values()].find((entry) => entry.username === username) ?? null; + } + + async findById(id: string) { + return this.rows.get(id) ?? null; + } + + async updateRoleId(userId: string, roleId: string) { + this.updatedRoleIds.push({ userId, roleId }); + const existing = this.rows.get(userId); + if (existing) existing.role = role({ id: roleId, slug: 'cluster-admin' }); + } +} + +class FakeRoleRepository { + rows: RoleDomain[] = []; + updates: Array<{ id: string; permissions?: string[] }> = []; + + async findBySlug(slug: string) { + return this.rows.find((entry) => entry.slug === slug) ?? null; + } + + async findById(id: string) { + return this.rows.find((entry) => entry.id === id) ?? null; + } + + async create(input: { id: string; slug: string; name: string; permissions: string[] }) { + this.rows.push(role({ id: input.id, slug: input.slug, permissions: input.permissions })); + } + + async update(id: string, changes: { name?: string; permissions?: string[] }) { + this.updates.push({ id, permissions: changes.permissions }); + const existing = this.rows.find((entry) => entry.id === id); + if (existing && changes.permissions) existing.permissions = changes.permissions; + } +} + +describe('AuthService bootstrapDefaults', () => { + let userRepository: FakeUserRepository; + let roleRepository: FakeRoleRepository; + let passwordService: { + ensureEncryptionKey: ReturnType; + verifyPassword: ReturnType; + }; + let sessionService: { + createToken: ReturnType; + parseAndVerifyToken: ReturnType; + }; + let service: AuthService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + roleRepository = new FakeRoleRepository(); + passwordService = { + ensureEncryptionKey: vi.fn(), + verifyPassword: vi.fn(), + }; + sessionService = { + createToken: vi.fn(), + parseAndVerifyToken: vi.fn(), + }; + service = new AuthService( + userRepository as any, + roleRepository as any, + passwordService as any, + sessionService as any, + ); + }); + + it('creates cluster-admin and assigns it to the admin user', async () => { + userRepository.rows.set( + 'admin-user', + user({ id: 'admin-user', username: 'admin', role: null }), + ); + + await service.bootstrapDefaults(); + + const clusterAdmin = roleRepository.rows.find((entry) => entry.slug === 'cluster-admin'); + const clusterUser = roleRepository.rows.find((entry) => entry.slug === 'cluster-user'); + expect(clusterAdmin?.permissions).toEqual(['vault:all', 'openreport:all', 'stateiac:all']); + expect(clusterUser?.permissions).toEqual([]); + expect(userRepository.updatedRoleIds).toEqual([ + { userId: 'admin-user', roleId: clusterAdmin?.id }, + ]); + }); + + it('keeps cluster-admin permissions current when the role already exists', async () => { + const clusterAdmin = role({ id: 'cluster-admin-id', slug: 'cluster-admin', permissions: [] }); + roleRepository.rows.push(clusterAdmin); + userRepository.rows.set( + 'admin-user', + user({ id: 'admin-user', username: 'admin', role: clusterAdmin }), + ); + + await service.bootstrapDefaults(); + + expect(roleRepository.updates).toEqual([ + { id: 'cluster-admin-id', permissions: ['vault:all', 'openreport:all', 'stateiac:all'] }, + ]); + expect(userRepository.updatedRoleIds).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/auth.service.ts b/src/modules/auth/application/auth.service.ts index c4c91d7f..415856ef 100644 --- a/src/modules/auth/application/auth.service.ts +++ b/src/modules/auth/application/auth.service.ts @@ -1,10 +1,16 @@ +import crypto from 'crypto'; import { PasswordService } from './password.service'; import { SessionService } from './session.service'; import { UserRepository } from '../infrastructure/repositories/user.repository'; +import { RoleRepository } from '../infrastructure/repositories/role.repository'; + +const CLUSTER_ADMIN_PERMISSIONS = ['vault:all', 'openreport:all', 'stateiac:all']; +const CLUSTER_USER_PERMISSIONS: string[] = []; export class AuthService { constructor( private readonly userRepository: UserRepository, + private readonly roleRepository: RoleRepository, private readonly passwordService: PasswordService, private readonly sessionService: SessionService, ) {} @@ -12,6 +18,9 @@ export class AuthService { async bootstrapDefaults(): Promise { this.passwordService.ensureEncryptionKey(); + const clusterAdminRole = await this.ensureClusterAdminRole(); + await this.ensureClusterUserRole(); + const adminExists = await this.userRepository.findByUsername('admin'); if (!adminExists) { // const roleAdmin = await this.roleRepository @@ -24,7 +33,64 @@ export class AuthService { // role: '00000000-0000-0000-0000-000000000001', // }); // console.log('Default admin user created (admin:admin)'); + return; + } + + if (adminExists.role?.id !== clusterAdminRole.id) { + await this.userRepository.updateRoleId(adminExists.id, clusterAdminRole.id); + } + } + + private async ensureClusterAdminRole(): Promise { + const existing = await this.roleRepository.findBySlug('cluster-admin', 'cluster'); + + if (existing) { + await this.roleRepository.update(existing.id, { + name: 'Cluster Admin', + permissions: CLUSTER_ADMIN_PERMISSIONS, + }); + const updated = await this.roleRepository.findById(existing.id); + if (!updated) throw new Error('Failed to load cluster-admin role'); + return updated; } + + await this.roleRepository.create({ + id: crypto.randomUUID(), + slug: 'cluster-admin', + name: 'Cluster Admin', + scope: 'cluster', + permissions: CLUSTER_ADMIN_PERMISSIONS, + }); + + const created = await this.roleRepository.findBySlug('cluster-admin', 'cluster'); + if (!created) throw new Error('Failed to create cluster-admin role'); + return created; + } + + private async ensureClusterUserRole(): Promise { + const existing = await this.roleRepository.findBySlug('cluster-user', 'cluster'); + + if (existing) { + await this.roleRepository.update(existing.id, { + name: 'Cluster User', + permissions: CLUSTER_USER_PERMISSIONS, + }); + const updated = await this.roleRepository.findById(existing.id); + if (!updated) throw new Error('Failed to load cluster-user role'); + return updated; + } + + await this.roleRepository.create({ + id: crypto.randomUUID(), + slug: 'cluster-user', + name: 'Cluster User', + scope: 'cluster', + permissions: CLUSTER_USER_PERMISSIONS, + }); + + const created = await this.roleRepository.findBySlug('cluster-user', 'cluster'); + if (!created) throw new Error('Failed to create cluster-user role'); + return created; } async authenticate(username: string, password: string): Promise { @@ -64,12 +130,17 @@ export class AuthService { id: user.id, username: user.username, email: user.email, - role: user.role ? { - id: user.role.id, - name: user.role.name, - slug: user.role.slug, - permissions: Array.isArray(user.role.permissions) ? user.role.permissions : [], - } : null, + role: user.role + ? { + id: user.role.id, + name: user.role.name, + slug: user.role.slug, + scope: user.role.scope, + organizationId: user.role.organizationId, + projectId: user.role.projectId, + permissions: Array.isArray(user.role.permissions) ? user.role.permissions : [], + } + : null, }; } } diff --git a/src/modules/auth/application/cancan.service.test.ts b/src/modules/auth/application/cancan.service.test.ts new file mode 100644 index 00000000..06d34087 --- /dev/null +++ b/src/modules/auth/application/cancan.service.test.ts @@ -0,0 +1,195 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { CanCanService } from './cancan.service'; +import { RoleDomain } from '../domain/role.domain'; +import { UserDomain } from '../domain/user.domain'; +import { UserAccessDomain } from '../domain/user-access.domain'; + +function role(input: { id: string; slug: string; permissions?: string[]; scope?: string }) { + return new RoleDomain({ + id: input.id, + slug: input.slug, + name: input.slug, + scope: input.scope ?? 'cluster', + permissions: input.permissions ?? [], + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +function user(input: { id: string; role: RoleDomain | null }) { + return new UserDomain({ + id: input.id, + username: input.id, + email: null, + password: 'hashed', + role: input.role, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +function access(input: { + id: string; + userId: string; + role: RoleDomain; + scope: 'organization' | 'project'; + organizationId?: string; + projectId?: string; +}) { + return new UserAccessDomain({ + id: input.id, + userId: input.userId, + roleId: input.role.id, + role: input.role, + scope: input.scope, + organizationId: input.organizationId, + projectId: input.projectId, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +class FakeUserRepository { + rows = new Map(); + + async findById(id: string) { + return this.rows.get(id) ?? null; + } +} + +class FakeUserAccessRepository { + rows: UserAccessDomain[] = []; + + async findByUserId(userId: string) { + return this.rows.filter((entry) => entry.userId === userId); + } +} + +class FakeProjectLookup { + organizationsByProjectId = new Map(); + + async getProject(id: string) { + const organizationId = this.organizationsByProjectId.get(id); + return organizationId ? { id, organization: { id: organizationId } } : null; + } +} + +describe('CanCanService', () => { + let userRepository: FakeUserRepository; + let userAccessRepository: FakeUserAccessRepository; + let projectLookup: FakeProjectLookup; + let service: CanCanService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + userAccessRepository = new FakeUserAccessRepository(); + projectLookup = new FakeProjectLookup(); + service = new CanCanService(userRepository, userAccessRepository, projectLookup); + }); + + it('matches explicit grants and section:all shortcuts', () => { + expect(CanCanService.hasPermission([], 'vault:read')).toBe(false); + expect(CanCanService.hasPermission(null, 'vault:read')).toBe(false); + expect(CanCanService.hasPermission(undefined, 'vault:read')).toBe(false); + expect(CanCanService.hasPermission(['vault:read'], 'vault:read')).toBe(true); + expect(CanCanService.hasPermission(['vault:read'], 'vault:delete')).toBe(false); + expect(CanCanService.hasPermission(['vault:all'], 'vault:delete')).toBe(true); + expect(CanCanService.hasPermission(['vault:all'], 'openreport:read')).toBe(false); + expect(CanCanService.hasPermission(['project:vault:read'], 'vault:read')).toBe(true); + expect(CanCanService.hasPermission(['project:vault:all'], 'vault:delete')).toBe(true); + }); + + it('allows a cluster admin without organization or project access rows', async () => { + userRepository.rows.set( + 'jose', + user({ id: 'jose', role: role({ id: 'admin', slug: 'admin' }) }), + ); + + await expect( + service.can('jose', 'stateiac:delete', { scope: 'project', projectId: 'kettu' }), + ).resolves.toBe(true); + }); + + it('allows an organization role inside that organization', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + userAccessRepository.rows.push( + access({ + id: 'access-1', + userId: 'jose', + scope: 'organization', + organizationId: 'gitops', + role: role({ + id: 'developer', + slug: 'developer', + scope: 'organization', + permissions: ['stateiac:read'], + }), + }), + ); + + await expect( + service.can('jose', 'stateiac:read', { scope: 'organization', organizationId: 'gitops' }), + ).resolves.toBe(true); + await expect( + service.can('jose', 'stateiac:read', { scope: 'organization', organizationId: 'other' }), + ).resolves.toBe(false); + }); + + it('inherits organization access for projects in that organization', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + projectLookup.organizationsByProjectId.set('kettu', 'gitops'); + userAccessRepository.rows.push( + access({ + id: 'access-1', + userId: 'jose', + scope: 'organization', + organizationId: 'gitops', + role: role({ + id: 'developer', + slug: 'developer', + scope: 'organization', + permissions: ['stateiac:read'], + }), + }), + ); + + await expect( + service.can('jose', 'stateiac:read', { scope: 'project', projectId: 'kettu' }), + ).resolves.toBe(true); + }); + + it('allows a project-specific admin role only for that project', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + userAccessRepository.rows.push( + access({ + id: 'access-1', + userId: 'jose', + scope: 'project', + projectId: 'kettu', + role: role({ id: 'project-admin', slug: 'project-admin', scope: 'project' }), + }), + ); + + await expect( + service.can('jose', 'stateiac:delete', { scope: 'project', projectId: 'kettu' }), + ).resolves.toBe(true); + await expect( + service.can('jose', 'stateiac:delete', { scope: 'project', projectId: 'other' }), + ).resolves.toBe(false); + }); + + it('denies scoped access when the user has no matching access row', async () => { + userRepository.rows.set( + 'jose', + user({ + id: 'jose', + role: role({ id: 'cluster-user', slug: 'cluster-user', permissions: ['stateiac:read'] }), + }), + ); + + await expect( + service.can('jose', 'stateiac:read', { scope: 'organization', organizationId: 'gitops' }), + ).resolves.toBe(false); + await expect(service.can('jose', 'stateiac:read', { scope: 'cluster' })).resolves.toBe(true); + }); +}); diff --git a/src/modules/auth/application/cancan.service.ts b/src/modules/auth/application/cancan.service.ts new file mode 100644 index 00000000..2342439b --- /dev/null +++ b/src/modules/auth/application/cancan.service.ts @@ -0,0 +1,162 @@ +import type { Permission } from '$lib/permissions'; +import type { ProjectDomain } from '../../projects/domain/project.domain'; +import type { RoleDomain } from '../domain/role.domain'; +import type { UserDomain } from '../domain/user.domain'; +import type { UserAccessDomain } from '../domain/user-access.domain'; + +type PermissionRole = { + slug?: string | null; + scope?: 'cluster' | 'organization' | 'project' | null; + organizationId?: string | null; + permissions?: readonly string[] | null; +} | null; + +type PermissionAwareUser = + | { + id?: string; + role?: PermissionRole; + } + | null + | undefined; + +export type CanCanContext = + | { scope: 'cluster' } + | { scope: 'organization'; organizationId: string } + | { scope: 'project'; projectId: string; organizationId?: string }; + +type UserLookup = { + findById(id: string): Promise; +}; + +type UserAccessLookup = { + findByUserId(userId: string): Promise; +}; + +type ProjectLookup = { + getProject(id: string): Promise; +}; + +export class CanCanService { + constructor( + private readonly userRepository: UserLookup, + private readonly userAccessRepository: UserAccessLookup, + private readonly projectLookup?: ProjectLookup, + ) {} + + async can(userId: string, permission: Permission, context: CanCanContext): Promise { + const user = await this.userRepository.findById(userId); + if (!user) return false; + + return this.canForUser(user, permission, context); + } + + async canSessionUser( + user: PermissionAwareUser, + permission: Permission, + context: CanCanContext, + ): Promise { + if (!user?.id) return false; + const role = user.role ?? null; + if (this.isClusterAdmin(role)) return true; + + if (context.scope === 'cluster') { + return this.roleCan(role, permission); + } + + return this.can(user.id, permission, context); + } + + async canManageOrganization(user: PermissionAwareUser, organizationId: string): Promise { + return this.canSessionUser(user, 'stateiac:read', { scope: 'organization', organizationId }); + } + + canAccessAdminArea(user: PermissionAwareUser): boolean { + return this.isAdmin(user); + } + + isAdmin(user: PermissionAwareUser): boolean { + return this.isAdminRole(user?.role ?? null); + } + + async canForUser( + user: UserDomain, + permission: Permission, + context: CanCanContext, + ): Promise { + if (this.isClusterAdmin(user.role)) return true; + + if (context.scope === 'cluster') { + return this.roleCan(user.role, permission); + } + + const access = await this.userAccessRepository.findByUserId(user.id); + const candidateRoles = await this.rolesForContext(access, context); + return candidateRoles.some((role) => this.roleCan(role, permission)); + } + + private async rolesForContext( + access: UserAccessDomain[], + context: CanCanContext, + ): Promise { + if (context.scope === 'organization') { + return access + .filter( + (entry) => + entry.scope === 'organization' && entry.organizationId === context.organizationId, + ) + .map((entry) => entry.role) + .filter((role): role is RoleDomain => Boolean(role)); + } + + if (context.scope !== 'project') return []; + + const organizationId = + context.organizationId ?? (await this.findProjectOrganizationId(context.projectId)); + + return access + .filter((entry) => { + if (entry.scope === 'project') return entry.projectId === context.projectId; + if (entry.scope === 'organization') return entry.organizationId === organizationId; + return false; + }) + .map((entry) => entry.role) + .filter((role): role is RoleDomain => Boolean(role)); + } + + private roleCan(role: PermissionRole, permission: Permission): boolean { + if (!role) return false; + if (this.isAdminRole(role)) return true; + return CanCanService.hasPermission(role.permissions, permission); + } + + private isClusterAdmin(role: PermissionRole): boolean { + return role?.scope === 'cluster' && this.isAdminRole(role); + } + + private isAdminRole(role: PermissionRole): boolean { + if (!role?.slug) return false; + return role.slug === 'admin' || role.slug.endsWith('-admin'); + } + + static hasPermission( + grants: readonly string[] | null | undefined, + permission: Permission, + ): boolean { + if (!grants || grants.length === 0) return false; + + const [section] = permission.split(':') as [string, string]; + return grants.some( + (grant) => + grant === permission || + grant === `${section}:all` || + grant.endsWith(`:${permission}`) || + grant.endsWith(`:${section}:all`), + ); + } + + private async findProjectOrganizationId(projectId: string): Promise { + if (!this.projectLookup) return null; + const project = await this.projectLookup.getProject(projectId); + return project?.organization?.id ?? null; + } +} diff --git a/src/modules/auth/application/role.service.test.ts b/src/modules/auth/application/role.service.test.ts index 16c115d4..58d1ace6 100644 --- a/src/modules/auth/application/role.service.test.ts +++ b/src/modules/auth/application/role.service.test.ts @@ -23,6 +23,9 @@ class FakeRoleRepository { id: input.id, slug: input.slug, name: input.name, + scope: (input as any).scope, + organizationId: (input as any).organizationId, + projectId: (input as any).projectId, permissions: input.permissions, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-01T00:00:00.000Z', @@ -75,6 +78,53 @@ describe('RoleService', () => { expect(roles[0].slug).toBe('admin'); }); + it('lists only roles owned by the requested organization', async () => { + await service.createRole({ + name: 'Organization role', + slug: 'organization-role', + permissions: [], + scope: 'organization', + organizationId: 'org-1', + }); + await service.createRole({ + name: 'Other organization role', + slug: 'other-organization-role', + permissions: [], + scope: 'organization', + organizationId: 'org-2', + }); + await service.createRole({ + name: 'Project role', + slug: 'project-role', + permissions: [], + scope: 'project', + projectId: 'project-1', + }); + + const roles = await service.listRoles('organization', 'org-1'); + + expect(roles.map((role) => role.slug)).toEqual(['organization-role']); + }); + + it('requires an owner ID for organization and project roles', async () => { + await expect( + service.createRole({ + name: 'Organization role', + slug: 'org-role', + permissions: [], + scope: 'organization', + }), + ).rejects.toThrow(/organization role requires its ID/); + await expect( + service.createRole({ + name: 'Project role', + slug: 'project-role', + permissions: [], + scope: 'project', + }), + ).rejects.toThrow(/project role requires its ID/); + }); + it('creates a role accepting the section:all shortcut', async () => { const role = await service.createRole({ name: 'Auditor', @@ -109,7 +159,11 @@ describe('RoleService', () => { }); it('updates only the fields provided', async () => { - const created = await service.createRole({ name: 'Auditor', slug: 'auditor', permissions: ['vault:read'] }); + const created = await service.createRole({ + name: 'Auditor', + slug: 'auditor', + permissions: ['vault:read'], + }); const updated = await service.updateRole(created.id, { permissions: ['vault:all'] }); expect(updated.name).toBe('Auditor'); diff --git a/src/modules/auth/application/role.service.ts b/src/modules/auth/application/role.service.ts index 57a0bbaa..a0fc5c04 100644 --- a/src/modules/auth/application/role.service.ts +++ b/src/modules/auth/application/role.service.ts @@ -2,6 +2,7 @@ import crypto from 'crypto'; import { isValidPermissionGrant } from '$lib/permissions'; import type { RoleRepository } from '../infrastructure/repositories/role.repository'; import type { UserRepository } from '../infrastructure/repositories/user.repository'; +import type { RoleScope } from '../domain/role.domain'; export class RoleService { constructor( @@ -12,12 +13,29 @@ export class RoleService { private readonly userRepository: Pick, ) {} - async listRoles(): Promise { - const roles = await this.roleRepository.findAll(); - return roles.map((role) => role.toJson()); + async listRoles(scope: RoleScope = 'cluster', scopeId?: string): Promise { + this.validateScope(scope, scopeId); + const roles = await this.roleRepository.findAll(scope, scopeId); + return roles + .filter((role) => { + if (role.scope !== scope) return false; + if (scope === 'organization') return role.organizationId === scopeId; + if (scope === 'project') return role.projectId === scopeId; + return true; + }) + .map((role) => role.toJson()); } - async createRole(input: { name: string; slug: string; permissions: string[] }): Promise { + async createRole(input: { + name: string; + slug: string; + permissions: string[]; + scope?: RoleScope; + organizationId?: string; + projectId?: string; + }): Promise { + const scope = input.scope ?? 'cluster'; + this.validateScope(scope, scope === 'organization' ? input.organizationId : input.projectId); const name = input.name.trim(); const slug = input.slug.trim().toLowerCase(); @@ -29,16 +47,32 @@ export class RoleService { throw new Error('Role slug is required'); } - const existing = await this.roleRepository.findBySlug(slug); + const scopeId = + scope === 'organization' + ? input.organizationId + : scope === 'project' + ? input.projectId + : undefined; + const existing = await this.roleRepository.findBySlug(slug, scope, scopeId); if (existing) { throw new Error('A role with this slug already exists'); } const permissions = this.sanitizePermissions(input.permissions); - - await this.roleRepository.create({ id: crypto.randomUUID(), slug, name, permissions }); - - const created = await this.roleRepository.findBySlug(slug); + const organizationId = scope === 'organization' ? input.organizationId : null; + const projectId = scope === 'project' ? input.projectId : null; + + await this.roleRepository.create({ + id: crypto.randomUUID(), + slug, + name, + scope, + organizationId, + projectId, + permissions, + }); + + const created = await this.roleRepository.findBySlug(slug, scope, scopeId); if (!created) { throw new Error('Failed to create role'); } @@ -104,4 +138,14 @@ export class RoleService { return unique; } + + private validateScope(scope?: RoleScope, scopeId?: string): void { + if (!scope || !['cluster', 'organization', 'project'].includes(scope)) { + throw new Error('Role scope must be cluster, organization, or project'); + } + + if (scope !== 'cluster' && !scopeId?.trim()) { + throw new Error(`A ${scope} role requires its ID`); + } + } } diff --git a/src/modules/auth/application/user-access.service.test.ts b/src/modules/auth/application/user-access.service.test.ts new file mode 100644 index 00000000..a7215a1d --- /dev/null +++ b/src/modules/auth/application/user-access.service.test.ts @@ -0,0 +1,329 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { UserAccessService } from './user-access.service'; +import { RoleDomain } from '../domain/role.domain'; +import { UserAccessDomain } from '../domain/user-access.domain'; +import { UserDomain } from '../domain/user.domain'; + +function role(input: { + id: string; + slug: string; + scope?: 'cluster' | 'organization' | 'project'; + organizationId?: string | null; + projectId?: string | null; +}) { + return new RoleDomain({ + id: input.id, + slug: input.slug, + name: input.slug, + scope: input.scope ?? 'cluster', + organizationId: input.organizationId ?? null, + projectId: input.projectId ?? null, + permissions: [], + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +function user(input: { id: string; username: string; role: RoleDomain | null }) { + return new UserDomain({ + id: input.id, + username: input.username, + email: null, + password: 'hashed', + role: input.role, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }); +} + +function organization(input: { id: string; name: string; slug: string }) { + return { + ...input, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }; +} + +class FakeUserRepository { + rows: UserDomain[] = []; + + async findById(id: string) { + return this.rows.find((entry) => entry.id === id) ?? null; + } + + async findByUsername(username: string) { + return this.rows.find((entry) => entry.username === username) ?? null; + } + + async listUsers() { + return [...this.rows]; + } + + async createUser(input: { id: string; username: string; role: any }) { + this.rows.push( + user({ id: input.id, username: input.username, role: new RoleDomain(input.role) }), + ); + } +} + +class FakeRoleRepository { + rows: RoleDomain[] = []; + + async findById(id: string) { + return this.rows.find((entry) => entry.id === id) ?? null; + } + + async findBySlug(slug: string) { + return this.rows.find((entry) => entry.slug === slug) ?? null; + } +} + +class FakeUserAccessRepository { + rows: UserAccessDomain[] = []; + userRepository!: FakeUserRepository; + roleRepository!: FakeRoleRepository; + + async findByScope(scope: 'cluster' | 'organization' | 'project', scopeId?: string) { + return this.rows.filter((entry) => { + if (entry.scope !== scope) return false; + if (!scopeId) return true; + if (scope === 'organization') return entry.organizationId === scopeId; + if (scope === 'project') return entry.projectId === scopeId; + return true; + }); + } + + async findOne(input: { + userId: string; + scope: 'cluster' | 'organization' | 'project'; + organizationId?: string; + projectId?: string; + }) { + return ( + this.rows.find((entry) => { + if (entry.userId !== input.userId || entry.scope !== input.scope) return false; + if (input.scope === 'organization') return entry.organizationId === input.organizationId; + if (input.scope === 'project') return entry.projectId === input.projectId; + return true; + }) ?? null + ); + } + + async findById(id: string) { + return this.rows.find((entry) => entry.id === id) ?? null; + } + + async create(input: { + id: string; + userId: string; + roleId: string; + scope: 'cluster' | 'organization' | 'project'; + organizationId?: string; + projectId?: string; + status?: 'active' | 'invited'; + }) { + const userRow = await this.userRepository.findById(input.userId); + const roleRow = await this.roleRepository.findById(input.roleId); + this.rows.push( + new UserAccessDomain({ + ...input, + user: userRow?.toJson(), + role: roleRow?.toJson(), + status: input.status, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }), + ); + } + + async update(id: string, changes: { roleId?: string; status?: 'active' | 'invited' }) { + const existing = this.rows.find((entry) => entry.id === id); + if (!existing) return; + if (changes.roleId) { + const roleRow = await this.roleRepository.findById(changes.roleId); + existing.roleId = changes.roleId; + existing.role = roleRow; + } + if (changes.status) existing.status = changes.status; + } + + async deleteById(id: string) { + this.rows = this.rows.filter((entry) => entry.id !== id); + } +} + +describe('UserAccessService', () => { + let userRepository: FakeUserRepository; + let roleRepository: FakeRoleRepository; + let userAccessRepository: FakeUserAccessRepository; + let service: UserAccessService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + roleRepository = new FakeRoleRepository(); + userAccessRepository = new FakeUserAccessRepository(); + userAccessRepository.userRepository = userRepository; + userAccessRepository.roleRepository = roleRepository; + service = new UserAccessService( + userRepository as any, + roleRepository as any, + userAccessRepository as any, + { hashPassword: (password: string) => `hashed:${password}` }, + ); + + roleRepository.rows.push(role({ id: 'cluster-user-id', slug: 'cluster-user' })); + }); + + it('creates an organization user and grants organization access', async () => { + roleRepository.rows.push( + role({ + id: 'org-developer-id', + slug: 'developer', + scope: 'organization', + organizationId: 'gitops', + }), + ); + + const created = await service.createOrganizationUser({ + organizationId: 'gitops', + username: 'jose', + password: 'secret', + roleId: 'org-developer-id', + }); + + expect(created.username).toBe('jose'); + expect(created.role?.id).toBe('org-developer-id'); + expect(userRepository.rows[0].role?.slug).toBe('cluster-user'); + }); + + it('assigns an existing user to a project role', async () => { + userRepository.rows.push(user({ id: 'jose-id', username: 'jose', role: null })); + roleRepository.rows.push( + role({ id: 'project-admin-id', slug: 'project-admin', scope: 'project', projectId: 'kettu' }), + ); + + const assigned = await service.assignProjectUser({ + projectId: 'kettu', + userId: 'jose-id', + roleId: 'project-admin-id', + }); + + expect(assigned.username).toBe('jose'); + expect(assigned.role?.slug).toBe('project-admin'); + expect(assigned.status).toBe('active'); + }); + + it('updates the role and status for an access row', async () => { + userRepository.rows.push(user({ id: 'jose-id', username: 'jose', role: null })); + roleRepository.rows.push( + role({ id: 'project-developer-id', slug: 'developer', scope: 'project', projectId: 'kettu' }), + role({ id: 'project-admin-id', slug: 'project-admin', scope: 'project', projectId: 'kettu' }), + ); + await userAccessRepository.create({ + id: 'access-id', + userId: 'jose-id', + roleId: 'project-developer-id', + scope: 'project', + projectId: 'kettu', + }); + + const updated = await service.updateAccess({ + accessId: 'access-id', + scope: 'project', + scopeId: 'kettu', + roleId: 'project-admin-id', + status: 'invited', + }); + + expect(updated.role?.slug).toBe('project-admin'); + expect(updated.status).toBe('invited'); + }); + + it('removes an access row', async () => { + userRepository.rows.push(user({ id: 'jose-id', username: 'jose', role: null })); + roleRepository.rows.push( + role({ id: 'project-admin-id', slug: 'project-admin', scope: 'project', projectId: 'kettu' }), + ); + await userAccessRepository.create({ + id: 'access-id', + userId: 'jose-id', + roleId: 'project-admin-id', + scope: 'project', + projectId: 'kettu', + }); + + await service.removeAccess({ accessId: 'access-id', scope: 'project', scopeId: 'kettu' }); + + expect(userAccessRepository.rows).toEqual([]); + }); + + it('resends invitations only for invited access rows', async () => { + userRepository.rows.push(user({ id: 'jose-id', username: 'jose', role: null })); + roleRepository.rows.push( + role({ id: 'project-admin-id', slug: 'project-admin', scope: 'project', projectId: 'kettu' }), + ); + await userAccessRepository.create({ + id: 'access-id', + userId: 'jose-id', + roleId: 'project-admin-id', + scope: 'project', + projectId: 'kettu', + status: 'invited', + }); + + const resent = await service.resendInvitation({ + accessId: 'access-id', + scope: 'project', + scopeId: 'kettu', + }); + + expect(resent.status).toBe('invited'); + }); + + it('includes organization labels when listing cluster users', async () => { + userRepository.rows.push(user({ id: 'jose-id', username: 'jose', role: null })); + roleRepository.rows.push( + role({ + id: 'org-developer-id', + slug: 'developer', + scope: 'organization', + organizationId: 'gitops', + }), + ); + userAccessRepository.rows.push( + new UserAccessDomain({ + id: 'access-id', + userId: 'jose-id', + roleId: 'org-developer-id', + scope: 'organization', + organizationId: 'gitops', + user: userRepository.rows[0].toJson(), + role: roleRepository.rows[1].toJson(), + organization: organization({ id: 'gitops', name: 'GitOps', slug: 'gitops' }), + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }), + ); + + const users = await service.listUsers('cluster'); + + expect(users[0].organizations).toEqual([ + { id: 'gitops', name: 'GitOps', slug: 'gitops', role: 'developer' }, + ]); + }); + + it('rejects a project role from a different project', async () => { + userRepository.rows.push(user({ id: 'jose-id', username: 'jose', role: null })); + roleRepository.rows.push( + role({ id: 'project-admin-id', slug: 'project-admin', scope: 'project', projectId: 'other' }), + ); + + await expect( + service.assignProjectUser({ + projectId: 'kettu', + userId: 'jose-id', + roleId: 'project-admin-id', + }), + ).rejects.toThrow(/does not belong/); + }); +}); diff --git a/src/modules/auth/application/user-access.service.ts b/src/modules/auth/application/user-access.service.ts new file mode 100644 index 00000000..e78b0c51 --- /dev/null +++ b/src/modules/auth/application/user-access.service.ts @@ -0,0 +1,379 @@ +import crypto from 'crypto'; +import type { RoleScope } from '../domain/role.domain'; +import type { RoleView } from '../domain/entities'; +import type { UserAccessDomain, UserAccessStatus } from '../domain/user-access.domain'; +import type { UserDomain } from '../domain/user.domain'; +import type { RoleRepository } from '../infrastructure/repositories/role.repository'; +import type { UserAccessRepository } from '../infrastructure/repositories/user-access.repository'; +import type { UserRepository } from '../infrastructure/repositories/user.repository'; +import type { PasswordService } from './password.service'; + +type UserAccessRow = { + id: string; + userId: string; + username: string; + email: string | null; + role: ReturnType['toJson']> | null; + organizations: Array<{ id: string; name: string; slug: string; role: string | null }>; + scope: RoleScope; + organizationId: string | null; + projectId: string | null; + status: UserAccessStatus; + createdAt: string; +}; + +export class UserAccessService { + constructor( + private readonly userRepository: Pick< + UserRepository, + 'findById' | 'findByUsername' | 'listUsers' | 'createUser' | 'updateRoleId' | 'updateStatus' + >, + private readonly roleRepository: Pick, + private readonly userAccessRepository: Pick< + UserAccessRepository, + 'findByScope' | 'findOne' | 'findById' | 'create' | 'update' | 'deleteById' + >, + private readonly passwordService: Pick, + ) {} + + async listUsers(scope: RoleScope, scopeId?: string): Promise { + this.validateScope(scope, scopeId); + if (scope === 'cluster') return this.listClusterUsers(); + const access = await this.userAccessRepository.findByScope(scope, scopeId); + return access.map((entry) => this.toRow(entry)); + } + + async listAssignableUsers(): Promise { + const users = await this.userRepository.listUsers(); + return users.map((user) => user.toJson()); + } + + async createOrganizationUser(input: { + organizationId: string; + username: string; + password: string; + roleId: string; + email?: string | null; + }): Promise { + const organizationId = input.organizationId.trim(); + const username = input.username.trim(); + const password = input.password.trim(); + if (!organizationId) throw new Error('Organization is required'); + if (!username) throw new Error('Username is required'); + if (!password) throw new Error('Password is required'); + + const role = await this.findRoleForScope(input.roleId, 'organization', organizationId); + const clusterUserRole = await this.ensureClusterUserRole(); + + await this.userRepository.createUser({ + id: crypto.randomUUID(), + username, + email: input.email?.trim() || null, + passwordHash: this.passwordService.hashPassword(password), + role: this.toRoleView(clusterUserRole), + }); + + const user = await this.userRepository.findByUsername(username); + if (!user) throw new Error('Failed to create user'); + + const access = await this.createAccess({ + userId: user.id, + roleId: role.id, + scope: 'organization', + organizationId, + }); + return this.toRow(access); + } + + async createClusterUser(input: { + username: string; + password: string; + roleId: string; + email?: string | null; + }): Promise { + const username = input.username.trim(); + const password = input.password.trim(); + if (!username) throw new Error('Username is required'); + if (!password) throw new Error('Password is required'); + + const role = await this.findRoleForScope(input.roleId, 'cluster', ''); + + await this.userRepository.createUser({ + id: crypto.randomUUID(), + username, + email: input.email?.trim() || null, + passwordHash: this.passwordService.hashPassword(password), + role: this.toRoleView(role), + }); + + const user = await this.userRepository.findByUsername(username); + if (!user) throw new Error('Failed to create user'); + return this.toClusterRow(user); + } + + async assignProjectUser(input: { + projectId: string; + userId: string; + roleId: string; + }): Promise { + const projectId = input.projectId.trim(); + const userId = input.userId.trim(); + if (!projectId) throw new Error('Project is required'); + if (!userId) throw new Error('User is required'); + + const user = await this.userRepository.findById(userId); + if (!user) throw new Error('User not found'); + const role = await this.findRoleForScope(input.roleId, 'project', projectId); + + const access = await this.createAccess({ + userId, + roleId: role.id, + scope: 'project', + projectId, + }); + return this.toRow(access); + } + + async updateAccess(input: { + accessId: string; + scope: RoleScope; + scopeId?: string; + roleId: string; + status: string; + }): Promise { + const access = await this.findAccessInScope(input.accessId, input.scope, input.scopeId); + if (input.scope === 'cluster') { + const role = await this.findRoleForScope(input.roleId, 'cluster', ''); + const status = this.sanitizeStatus(input.status); + await Promise.all([ + this.userRepository.updateRoleId(access.id, role.id), + this.userRepository.updateStatus(access.id, status), + ]); + const updated = await this.userRepository.findById(access.id); + if (!updated) throw new Error('Failed to update user access'); + return this.toClusterRow(updated); + } + + const role = await this.findRoleForScope(input.roleId, access.scope, this.scopeIdFor(access)); + const status = this.sanitizeStatus(input.status); + + await this.userAccessRepository.update(access.id, { roleId: role.id, status }); + + const updated = await this.userAccessRepository.findById(access.id); + if (!updated) throw new Error('Failed to update user access'); + return this.toRow(updated); + } + + async removeAccess(input: { + accessId: string; + scope: RoleScope; + scopeId?: string; + }): Promise { + const access = await this.findAccessInScope(input.accessId, input.scope, input.scopeId); + if (input.scope === 'cluster') { + const clusterUserRole = await this.ensureClusterUserRole(); + await this.userRepository.updateRoleId(access.id, clusterUserRole.id); + return; + } + + await this.userAccessRepository.deleteById(access.id); + } + + async resendInvitation(input: { + accessId: string; + scope: RoleScope; + scopeId?: string; + }): Promise { + const access = await this.findAccessInScope(input.accessId, input.scope, input.scopeId); + if (input.scope === 'cluster') { + const user = await this.userRepository.findById(access.id); + if (!user) throw new Error('User not found'); + if (user.status !== 'invited') throw new Error('Only invited users can receive invitations'); + await this.userRepository.updateStatus(user.id, 'invited'); + const updated = await this.userRepository.findById(user.id); + if (!updated) throw new Error('Failed to resend invitation'); + return this.toClusterRow(updated); + } + + if (access.status !== 'invited') throw new Error('Only invited users can receive invitations'); + + await this.userAccessRepository.update(access.id, { status: 'invited' }); + const updated = await this.userAccessRepository.findById(access.id); + if (!updated) throw new Error('Failed to resend invitation'); + return this.toRow(updated); + } + + private async createAccess(input: { + userId: string; + roleId: string; + scope: RoleScope; + organizationId?: string; + projectId?: string; + }): Promise { + const existing = await this.userAccessRepository.findOne(input); + if (existing) throw new Error('User already has access in this scope'); + + await this.userAccessRepository.create({ + id: crypto.randomUUID(), + userId: input.userId, + roleId: input.roleId, + scope: input.scope, + organizationId: input.organizationId, + projectId: input.projectId, + status: 'active', + }); + + const created = await this.userAccessRepository.findOne(input); + if (!created) throw new Error('Failed to create user access'); + return created; + } + + private async findRoleForScope(roleId: string, scope: RoleScope, scopeId: string) { + const role = await this.roleRepository.findById(roleId.trim()); + if (!role) throw new Error('Role not found'); + if (role.scope !== scope) throw new Error(`Role must be a ${scope} role`); + if (scope === 'organization' && role.organizationId !== scopeId) { + throw new Error('Role does not belong to this organization'); + } + if (scope === 'project' && role.projectId !== scopeId) { + throw new Error('Role does not belong to this project'); + } + return role; + } + + private async findAccessInScope( + accessId: string, + scope: RoleScope, + scopeId?: string, + ): Promise { + const access = await this.userAccessRepository.findById(accessId.trim()); + if (scope === 'cluster') { + const user = await this.userRepository.findById(accessId.trim()); + if (!user) throw new Error('User not found'); + return this.clusterAccessAdapter(user); + } + + if (!access) throw new Error('User access not found'); + if (access.scope !== scope) throw new Error('User access does not belong to this scope'); + if (scope === 'organization' && access.organizationId !== scopeId) { + throw new Error('User access does not belong to this organization'); + } + if (scope === 'project' && access.projectId !== scopeId) { + throw new Error('User access does not belong to this project'); + } + return access; + } + + private scopeIdFor(access: UserAccessDomain): string { + if (access.scope === 'organization') return access.organizationId ?? ''; + if (access.scope === 'project') return access.projectId ?? ''; + return ''; + } + + private sanitizeStatus(status: string): UserAccessStatus { + return status === 'invited' ? 'invited' : 'active'; + } + + private async ensureClusterUserRole() { + const existing = await this.roleRepository.findBySlug('cluster-user', 'cluster'); + if (existing) return existing; + + throw new Error('Cluster user role is required before creating organization users'); + } + + private validateScope(scope: RoleScope, scopeId?: string): void { + if (scope !== 'cluster' && !scopeId?.trim()) { + throw new Error(`${scope} ID is required`); + } + } + + private toRow(entry: UserAccessDomain): UserAccessRow { + return { + id: entry.id, + userId: entry.userId, + username: entry.user?.username ?? 'Unknown user', + email: entry.user?.email ?? null, + role: entry.role ? entry.role.toJson() : null, + organizations: [], + scope: entry.scope, + organizationId: entry.organizationId, + projectId: entry.projectId, + status: entry.status, + createdAt: entry.createdAt.toISOString(), + }; + } + + private toRoleView(role: NonNullable): RoleView { + const value = role.toJson(); + return { + ...value, + createdAt: role.createdAt.toISOString(), + updatedAt: role.updatedAt.toISOString(), + }; + } + + private async listClusterUsers(): Promise { + const [users, organizationAccess] = await Promise.all([ + this.userRepository.listUsers(), + this.userAccessRepository.findByScope('organization'), + ]); + return users.map((user) => this.toClusterRow(user, organizationAccess)); + } + + private toClusterRow(user: UserDomain, access: UserAccessDomain[] = []): UserAccessRow { + return { + id: user.id, + userId: user.id, + username: user.username, + email: user.email, + role: user.role ? user.role.toJson() : null, + organizations: access + .filter((entry) => entry.userId === user.id && entry.organization) + .map((entry) => ({ + id: entry.organization?.id ?? '', + name: entry.organization?.name ?? 'Unknown organization', + slug: entry.organization?.slug ?? '', + role: entry.role?.name ?? null, + })), + scope: 'cluster', + organizationId: null, + projectId: null, + status: user.status, + createdAt: user.createdAt.toISOString(), + }; + } + + private clusterAccessAdapter(user: UserDomain): UserAccessDomain { + return { + id: user.id, + userId: user.id, + roleId: user.role?.id ?? '', + scope: 'cluster', + organizationId: null, + projectId: null, + status: user.status, + user, + role: user.role, + organization: null, + project: null, + createdAt: user.createdAt, + updatedAt: user.updatedAt, + toJson: () => ({ + id: user.id, + userId: user.id, + roleId: user.role?.id ?? '', + scope: 'cluster', + organizationId: null, + projectId: null, + status: user.status, + user: user.toJson(), + role: user.role ? user.role.toJson() : null, + organizations: [], + organization: null, + project: null, + createdAt: user.createdAt, + updatedAt: user.updatedAt, + }), + } as UserAccessDomain; + } +} diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index a972ceef..3a36053f 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -21,16 +21,22 @@ export type RoleView = { id: string; name: string; slug: string; + scope: 'cluster' | 'organization' | 'project'; + organizationId: string | null; + projectId: string | null; description?: string; permissions: string[]; createdAt: string; updatedAt: string; -} +}; export type SessionRole = { id: string; name: string; slug: string; + scope: 'cluster' | 'organization' | 'project'; + organizationId: string | null; + projectId: string | null; permissions: string[]; }; diff --git a/src/modules/auth/domain/rbac.ts b/src/modules/auth/domain/rbac.ts deleted file mode 100644 index 91f38c6f..00000000 --- a/src/modules/auth/domain/rbac.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { AuthenticatedUser } from './entities'; -import { isAdmin } from '$lib/permissions'; - -export { can, hasPermission, isAdmin } from '$lib/permissions'; -export type { Permission, PermissionGrant, PermissionSection, PermissionAction } from '$lib/permissions'; - -export function canAccessAdminArea(user: AuthenticatedUser | null | undefined): boolean { - return isAdmin(user); -} diff --git a/src/modules/auth/domain/role.domain.ts b/src/modules/auth/domain/role.domain.ts index af155bfc..edfa63b3 100644 --- a/src/modules/auth/domain/role.domain.ts +++ b/src/modules/auth/domain/role.domain.ts @@ -1,25 +1,44 @@ import { Domain } from './domain'; +import { OrganizationDomain } from '../../organization/domain/organization.domain'; +import { ProjectDomain } from '../../projects/domain/project.domain'; + +export type RoleScope = 'cluster' | 'organization' | 'project'; export class RoleDomain extends Domain { - public name: string = '' - public slug: string = '' - public permissions: string[] = [] + public name: string = ''; + public slug: string = ''; + public scope: RoleScope = 'cluster'; + public organizationId: string | null = null; + public projectId: string | null = null; + public organization: OrganizationDomain | null = null; + public project: ProjectDomain | null = null; + public permissions: string[] = []; - constructor(data: any) { - super(data); - this.name = data.name - this.slug = data.slug - this.permissions = Array.isArray(data.permissions) ? data.permissions : [] - } + constructor(data: any) { + super(data); + this.name = data.name; + this.slug = data.slug; + this.scope = data.scope === 'organization' || data.scope === 'project' ? data.scope : 'cluster'; + this.organizationId = data.organizationId ?? null; + this.projectId = data.projectId ?? null; + this.organization = data.organization ? new OrganizationDomain(data.organization) : null; + this.project = data.project ? new ProjectDomain(data.project) : null; + this.permissions = Array.isArray(data.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, + scope: this.scope, + organizationId: this.organizationId, + projectId: this.projectId, + organization: this.organization ? this.organization.toJson() : null, + project: this.project ? this.project.toJson() : null, + permissions: this.permissions, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} diff --git a/src/modules/auth/domain/user-access.domain.ts b/src/modules/auth/domain/user-access.domain.ts new file mode 100644 index 00000000..64bf3fc7 --- /dev/null +++ b/src/modules/auth/domain/user-access.domain.ts @@ -0,0 +1,53 @@ +import { Domain } from './domain'; +import { OrganizationDomain } from '../../organization/domain/organization.domain'; +import { ProjectDomain } from '../../projects/domain/project.domain'; +import { RoleDomain, type RoleScope } from './role.domain'; +import { UserDomain } from './user.domain'; + +export type UserAccessScope = RoleScope; +export type UserAccessStatus = 'active' | 'invited'; + +export class UserAccessDomain extends Domain { + public userId: string = ''; + public roleId: string = ''; + public scope: UserAccessScope = 'cluster'; + public organizationId: string | null = null; + public projectId: string | null = null; + public status: UserAccessStatus = 'active'; + public user: UserDomain | null = null; + public role: RoleDomain | null = null; + public organization: OrganizationDomain | null = null; + public project: ProjectDomain | null = null; + + constructor(data: any) { + super(data); + this.userId = data.userId; + this.roleId = data.roleId; + this.scope = data.scope === 'organization' || data.scope === 'project' ? data.scope : 'cluster'; + this.organizationId = data.organizationId ?? null; + this.projectId = data.projectId ?? null; + this.status = data.status === 'invited' ? 'invited' : 'active'; + this.user = data.user ? new UserDomain(data.user) : null; + this.role = data.role ? new RoleDomain(data.role) : null; + this.organization = data.organization ? new OrganizationDomain(data.organization) : null; + this.project = data.project ? new ProjectDomain(data.project) : null; + } + + toJson() { + return { + id: this.id, + userId: this.userId, + roleId: this.roleId, + scope: this.scope, + organizationId: this.organizationId, + projectId: this.projectId, + status: this.status, + user: this.user ? this.user.toJson() : null, + role: this.role ? this.role.toJson() : null, + organization: this.organization ? this.organization.toJson() : null, + project: this.project ? this.project.toJson() : null, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} diff --git a/src/modules/auth/domain/user.domain.ts b/src/modules/auth/domain/user.domain.ts index d0ee9649..a983ea64 100644 --- a/src/modules/auth/domain/user.domain.ts +++ b/src/modules/auth/domain/user.domain.ts @@ -1,28 +1,29 @@ - - import { Domain } from './domain'; import { RoleDomain } from './role.domain'; export class UserDomain extends Domain { - public username: string = '' - public email: string | null = null - public password: string = '' - public role: RoleDomain | null = null - constructor(data: any) { - super(data); - this.username = data.username - this.email = data.email - this.password = data.password - this.role = data.role ? new RoleDomain(data.role) : null - } + public username: string = ''; + public email: string | null = null; + public password: string = ''; + public role: RoleDomain | null = null; + public status: 'active' | 'invited' = 'active'; + constructor(data: any) { + super(data); + this.username = data.username; + this.email = data.email; + this.password = data.password; + this.status = data.status === 'invited' ? 'invited' : 'active'; + this.role = data.role ? new RoleDomain(data.role) : null; + } - toJson() { - return { - id: this.id, - username: this.username, - email: this.email, - role: this.role ? this.role.toJson() : null, - createdAt: this.createdAt - } - } -} \ No newline at end of file + toJson() { + return { + id: this.id, + username: this.username, + email: this.email, + role: this.role ? this.role.toJson() : null, + status: this.status, + createdAt: this.createdAt, + }; + } +} diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index 5cbb6053..81c44f8e 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -1,33 +1,51 @@ -import { canAccessAdminArea, isAdmin, can, hasPermission } from './domain/rbac'; import { AuthService } from './application/auth.service'; import { ApiKeysService } from './application/apikeys.service'; import { PasswordService } from './application/password.service'; import { ProfileService } from './application/profile.service'; import { SessionService } from './application/session.service'; import { UserService } from './application/user.service'; +import { UserAccessService } from './application/user-access.service'; +import { CanCanService } from './application/cancan.service'; import { RoleService } from './application/role.service'; import { UserRepository } from './infrastructure/repositories/user.repository'; import { RoleRepository } from './infrastructure/repositories/role.repository'; import { ApiKeyRepository } from './infrastructure/repositories/apikey.repository'; +import { UserAccessRepository } from './infrastructure/repositories/user-access.repository'; +import { projectService } from '../projects'; const userRepository = new UserRepository(); const roleRepository = new RoleRepository(); const apiKeyRepository = new ApiKeyRepository(); +const userAccessRepository = new UserAccessRepository(); export const passwordService = new PasswordService(); const sessionService = new SessionService(passwordService); export const apiKeysService = new ApiKeysService(apiKeyRepository); -export const authService = new AuthService(userRepository, passwordService, sessionService); +export const authService = new AuthService( + userRepository, + roleRepository, + passwordService, + sessionService, +); export const userService = new UserService(userRepository, roleRepository, passwordService); export const profileService = new ProfileService(userRepository, passwordService); export const roleService = new RoleService(roleRepository, userRepository); - -export { canAccessAdminArea, isAdmin, can, hasPermission }; +export const userAccessService = new UserAccessService( + userRepository, + roleRepository, + userAccessRepository, + passwordService, +); +export const cancanService = new CanCanService( + userRepository, + userAccessRepository, + projectService, +); // Bootstrap auth primitives once at startup. const authBootstrap = authService.bootstrapDefaults(); export async function ensureAuthReady(): Promise { - await authBootstrap; + await authBootstrap; } diff --git a/src/modules/auth/infrastructure/repositories/role.repository.ts b/src/modules/auth/infrastructure/repositories/role.repository.ts index 2bf394d6..a47cb58d 100644 --- a/src/modules/auth/infrastructure/repositories/role.repository.ts +++ b/src/modules/auth/infrastructure/repositories/role.repository.ts @@ -1,37 +1,76 @@ -import { RoleEntity } from '$lib/database/schemas'; +import { RoleEntity } from '$lib/database/schemas'; import type { RoleView } from '../../domain/entities'; -import { RoleDomain } from '../../domain/role.domain'; +import { RoleDomain, type RoleScope } from '../../domain/role.domain'; import { Repository } from './repository'; export class RoleRepository extends Repository { - async findByName(name: string): Promise { const role = await this.db.select().from(RoleEntity).where({ name }).limit(1); - return role.rows[0] as RoleView | undefined || null; + return (role.rows[0] as RoleView | undefined) || null; } - async findAll(): Promise { - const result = await this.db.select().from(RoleEntity).orderBy('createdAt', 'asc'); - return result.rows.map((row: any) => new RoleDomain(row)); + async findAll(scope?: RoleScope, scopeId?: string): Promise { + const result = await this.db + .with({ organization: true, project: true }) + .select() + .from(RoleEntity) + .orderBy('createdAt', 'asc'); + return result.rows + .map((row: any) => new RoleDomain(row)) + .filter((role) => { + if (!scope) return true; + if (role.scope !== scope) return false; + if (scope === 'organization') return role.organizationId === scopeId; + if (scope === 'project') return role.projectId === scopeId; + return true; + }); } async findById(id: string): Promise { - const result = await this.db.select().from(RoleEntity).where({ id }).limit(1); + const result = await this.db + .with({ organization: true, project: true }) + .select() + .from(RoleEntity) + .where({ id }) + .limit(1); const row = result.rows[0]; return row ? new RoleDomain(row) : null; } - async findBySlug(slug: string): Promise { - const result = await this.db.select().from(RoleEntity).where({ slug }).limit(1); - const row = result.rows[0]; - return row ? new RoleDomain(row) : null; + async findBySlug(slug: string, scope?: RoleScope, scopeId?: string): Promise { + const result = await this.db + .with({ organization: true, project: true }) + .select() + .from(RoleEntity) + .where({ slug }); + const roles = result.rows.map((row: any) => new RoleDomain(row)); + return ( + roles.find((role) => { + if (!scope) return true; + if (role.scope !== scope) return false; + if (scope === 'organization') return role.organizationId === scopeId; + if (scope === 'project') return role.projectId === scopeId; + return true; + }) ?? null + ); } - async create(input: { id: string; slug: string; name: string; permissions: string[] }): Promise { + async create(input: { + id: string; + slug: string; + name: string; + scope: RoleScope; + organizationId?: string | null; + projectId?: string | null; + permissions: string[]; + }): Promise { await this.db.insert(RoleEntity).values({ id: input.id, slug: input.slug, name: input.name, + scope: input.scope, + organizationId: input.organizationId ?? null, + projectId: input.projectId ?? null, permissions: input.permissions, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), @@ -48,4 +87,4 @@ export class RoleRepository extends Repository { async deleteById(id: string): Promise { await this.db.delete(RoleEntity).where({ id }); } -} \ No newline at end of file +} diff --git a/src/modules/auth/infrastructure/repositories/user-access.repository.ts b/src/modules/auth/infrastructure/repositories/user-access.repository.ts new file mode 100644 index 00000000..4cdfea4a --- /dev/null +++ b/src/modules/auth/infrastructure/repositories/user-access.repository.ts @@ -0,0 +1,121 @@ +import { UserAccessEntity } from '$lib/database/schemas'; +import { + UserAccessDomain, + type UserAccessScope, + type UserAccessStatus, +} from '../../domain/user-access.domain'; +import { Repository } from './repository'; + +export class UserAccessRepository extends Repository { + async findAll(): Promise { + const result = await this.db + .with({ user: true, role: true, organization: true, project: true }) + .select() + .from(UserAccessEntity) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new UserAccessDomain(row)); + } + + async findByUserId(userId: string): Promise { + const result = await this.db + .with({ user: true, role: true, organization: true, project: true }) + .select() + .from(UserAccessEntity) + .where({ userId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new UserAccessDomain(row)); + } + + async findById(id: string): Promise { + const result = await this.db + .with({ user: true, role: true, organization: true, project: true }) + .select() + .from(UserAccessEntity) + .where({ id }) + .limit(1); + const row = result.rows[0]; + return row ? new UserAccessDomain(row) : null; + } + + async findByUserIdAndScope( + userId: string, + scope: UserAccessScope, + scopeId?: string, + ): Promise { + const access = await this.findByUserId(userId); + return access.filter((entry) => { + if (entry.scope !== scope) return false; + if (!scopeId) return true; + if (scope === 'organization') return entry.organizationId === scopeId; + if (scope === 'project') return entry.projectId === scopeId; + return true; + }); + } + + async findByScope(scope: UserAccessScope, scopeId?: string): Promise { + const access = await this.findAll(); + return access.filter((entry) => { + if (entry.scope !== scope) return false; + if (!scopeId) return true; + if (scope === 'organization') return entry.organizationId === scopeId; + if (scope === 'project') return entry.projectId === scopeId; + return true; + }); + } + + async findOne(input: { + userId: string; + scope: UserAccessScope; + organizationId?: string | null; + projectId?: string | null; + }): Promise { + const access = await this.findByUserId(input.userId); + return ( + access.find((entry) => { + if (entry.scope !== input.scope) return false; + if (input.scope === 'organization') return entry.organizationId === input.organizationId; + if (input.scope === 'project') return entry.projectId === input.projectId; + return true; + }) ?? null + ); + } + + async create(input: { + id: string; + userId: string; + roleId: string; + scope: UserAccessScope; + organizationId?: string | null; + projectId?: string | null; + status?: UserAccessStatus; + }): Promise { + await this.db.insert(UserAccessEntity).values({ + id: input.id, + userId: input.userId, + roleId: input.roleId, + scope: input.scope, + organizationId: input.organizationId ?? null, + projectId: input.projectId ?? null, + status: input.status ?? 'active', + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + } + + async update( + id: string, + changes: { + roleId?: string; + status?: UserAccessStatus; + }, + ): Promise { + await this.db + .update(UserAccessEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async deleteById(id: string): Promise { + await this.db.delete(UserAccessEntity).where({ id }); + } +} diff --git a/src/modules/auth/infrastructure/repositories/user.repository.ts b/src/modules/auth/infrastructure/repositories/user.repository.ts index 6ca954e7..864a5510 100644 --- a/src/modules/auth/infrastructure/repositories/user.repository.ts +++ b/src/modules/auth/infrastructure/repositories/user.repository.ts @@ -4,26 +4,36 @@ import type { CreateUserInput } from '../../domain/entities'; import { UserDomain } from '../../domain/user.domain'; - - export class UserRepository extends Repository { - - async findById(id: string): Promise { - const result = await this.db.with({ role: true }).select().from(UserEntity).where({ id }).limit(1); + const result = await this.db + .with({ role: true }) + .select() + .from(UserEntity) + .where({ id }) + .limit(1); const row = result.rows[0]; return row ? this.toDomain(row) : null; } async findByUsername(username: string): Promise { - const result = await this.db.with({ role: true }).select().from(UserEntity).where({ username }).limit(1); + const result = await this.db + .with({ role: true }) + .select() + .from(UserEntity) + .where({ username }) + .limit(1); const row = result.rows[0]; return row ? this.toDomain(row) : null; } async listUsers(): Promise { - const result = await this.db.with({ role: true }).select().from(UserEntity).orderBy('createdAt', 'desc'); - return (result.rows).map((row) => this.toDomain(row)); + const result = await this.db + .with({ role: true }) + .select() + .from(UserEntity) + .orderBy('createdAt', 'desc'); + return result.rows.map((row) => this.toDomain(row)); } async createUser(input: CreateUserInput): Promise { @@ -61,6 +71,19 @@ export class UserRepository extends Repository { .where({ id: userId }); } + async updateRoleId(userId: string, roleId: string): Promise { + await this.db + .update(UserEntity) + .set({ roleId, updatedAt: new Date().toISOString() }) + .where({ id: userId }); + } + + async updateStatus(userId: string, status: 'active' | 'invited'): Promise { + await this.db + .update(UserEntity) + .set({ status, updatedAt: new Date().toISOString() }) + .where({ id: userId }); + } async deleteById(userId: string): Promise { await this.db.delete(ApiKeyEntity).where({ userId }); @@ -83,6 +106,7 @@ export class UserRepository extends Repository { username: user.username, email: user.email ?? null, password: user.passwordHash, + status: user.status, role: user.role, createdAt: user.createdAt, updatedAt: user.updatedAt, @@ -99,6 +123,4 @@ export class UserRepository extends Repository { createdAt: user.createdAt, }; } - - } diff --git a/src/modules/organization/application/organization.service.test.ts b/src/modules/organization/application/organization.service.test.ts new file mode 100644 index 00000000..ab7e0b72 --- /dev/null +++ b/src/modules/organization/application/organization.service.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, it, beforeEach } from 'vitest'; +import { OrganizationService } from './organization.service'; +import { OrganizationDomain } from '../domain/organization.domain'; + +class FakeOrganizationRepository { + rows: OrganizationDomain[] = []; + + async findAll() { + return [...this.rows]; + } + + async findById(id: string) { + return this.rows.find((o) => o.id === id) ?? null; + } + + async findBySlug(slug: string) { + return this.rows.find((o) => o.slug === slug) ?? null; + } + + async create(input: { id: string; slug: string; name: string; description?: string }) { + this.rows.push( + new OrganizationDomain({ + id: input.id, + slug: input.slug, + name: input.name, + description: input.description, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-01T00:00:00.000Z', + }), + ); + } + + async update(id: string, changes: { name?: string; slug?: string; description?: string }) { + const organization = this.rows.find((o) => o.id === id); + if (!organization) return; + if (changes.name !== undefined) organization.name = changes.name; + if (changes.slug !== undefined) organization.slug = changes.slug; + if (changes.description !== undefined) organization.description = changes.description; + } + + async deleteById(id: string) { + this.rows = this.rows.filter((o) => o.id !== id); + } +} + +describe('OrganizationService', () => { + let repository: FakeOrganizationRepository; + let service: OrganizationService; + + beforeEach(() => { + repository = new FakeOrganizationRepository(); + service = new OrganizationService(repository as any); + }); + + describe('listOrganizations', () => { + it('returns an empty list when there are no organizations', async () => { + expect(await service.listOrganizations()).toEqual([]); + }); + + it('lists created organizations', async () => { + await service.createOrganization({ name: 'GitOps' }); + const organizations = await service.listOrganizations(); + expect(organizations).toHaveLength(1); + expect(organizations[0].slug).toBe('gitops'); + }); + }); + + describe('getOrganization / findBySlug', () => { + it('throws when the organization does not exist', async () => { + await expect(service.getOrganization('missing-id')).rejects.toThrow(/not found/); + await expect(service.findBySlug('missing-slug')).rejects.toThrow(/not found/); + }); + + it('returns the organization by id and by slug', async () => { + const created = await service.createOrganization({ name: 'Kettu' }); + + const byId = await service.getOrganization(created.id); + expect(byId.slug).toBe('kettu'); + + const bySlug = await service.findBySlug('kettu'); + expect(bySlug.id).toBe(created.id); + }); + }); + + describe('createOrganization', () => { + it('requires a non-empty name', async () => { + await expect(service.createOrganization({ name: ' ' })).rejects.toThrow( + /name is required/, + ); + }); + + it('auto-generates a normalized slug from the name when none is provided', async () => { + const organization = await service.createOrganization({ name: 'Kettu Studio!!' }); + expect(organization.slug).toBe('kettu-studio'); + }); + + it('uses the provided slug, normalized', async () => { + const organization = await service.createOrganization({ + name: 'Kettu Studio', + slug: 'Custom Slug', + }); + expect(organization.slug).toBe('custom-slug'); + }); + + it('rejects creating an organization with a duplicate slug', async () => { + await service.createOrganization({ name: 'Kettu Studio' }); + await expect(service.createOrganization({ name: 'Kettu Studio' })).rejects.toThrow( + /already exists/, + ); + }); + + it('trims the optional description', async () => { + const organization = await service.createOrganization({ + name: 'Kettu Studio', + description: ' A studio ', + }); + expect(organization.description).toBe('A studio'); + }); + }); + + describe('updateOrganization', () => { + it('throws when the organization does not exist', async () => { + await expect(service.updateOrganization('missing-id', { name: 'X' })).rejects.toThrow( + /not found/, + ); + }); + + it('updates only the fields provided', async () => { + const created = await service.createOrganization({ name: 'Original Name' }); + + const updated = await service.updateOrganization(created.id, { + description: 'New description', + }); + expect(updated.name).toBe('Original Name'); + expect(updated.description).toBe('New description'); + }); + + it('rejects clearing the name', async () => { + const created = await service.createOrganization({ name: 'Original Name' }); + await expect(service.updateOrganization(created.id, { name: ' ' })).rejects.toThrow( + /name is required/, + ); + }); + + it('normalizes the slug when updating it', async () => { + const created = await service.createOrganization({ name: 'Original Name' }); + const updated = await service.updateOrganization(created.id, { slug: 'New Slug!!' }); + expect(updated.slug).toBe('new-slug'); + }); + + it('rejects updating to a slug already used by another organization', async () => { + await service.createOrganization({ name: 'Organization A', slug: 'taken' }); + const created = await service.createOrganization({ name: 'Organization B' }); + + await expect(service.updateOrganization(created.id, { slug: 'taken' })).rejects.toThrow( + /already exists/, + ); + }); + + it('allows keeping the same slug on the same organization', async () => { + const created = await service.createOrganization({ + name: 'Organization A', + slug: 'same-slug', + }); + const updated = await service.updateOrganization(created.id, { slug: 'same-slug' }); + expect(updated.slug).toBe('same-slug'); + }); + }); + + describe('deleteOrganization', () => { + it('throws when the organization does not exist', async () => { + await expect(service.deleteOrganization('missing-id')).rejects.toThrow(/not found/); + }); + + it('removes the organization', async () => { + const created = await service.createOrganization({ name: 'Organization A' }); + await service.deleteOrganization(created.id); + await expect(service.getOrganization(created.id)).rejects.toThrow(/not found/); + }); + }); + + describe('bootstrapDefaults', () => { + it('seeds the default gitops organization when none exists', async () => { + await service.bootstrapDefaults(); + const organizations = await service.listOrganizations(); + expect(organizations).toHaveLength(1); + expect(organizations[0].slug).toBe('gitops'); + }); + + it('does not create a duplicate when the default organization already exists', async () => { + await service.bootstrapDefaults(); + await service.bootstrapDefaults(); + const organizations = await service.listOrganizations(); + expect(organizations).toHaveLength(1); + }); + }); +}); diff --git a/src/modules/organization/application/organization.service.ts b/src/modules/organization/application/organization.service.ts index 71d885bf..513ef0bf 100644 --- a/src/modules/organization/application/organization.service.ts +++ b/src/modules/organization/application/organization.service.ts @@ -1,8 +1,159 @@ -export type Organization = { id: string; name: string; slug: string }; +import crypto from 'crypto'; +import { OrganizationRepository } from '../infrastructure/repositories/organization.repository'; + +export type Organization = { + id: string; + name: string; + slug: string; + description?: string | null; + createdAt: Date; + updatedAt: Date; +}; + +const DEFAULT_ORGANIZATION = { name: 'GitOps', slug: 'gitops' }; export class OrganizationService { - // stub: no persistence yet, always resolves to the single default organization - async findBySlug(_slug: string): Promise { - return { id: 'gitops', name: 'GitOps', slug: 'gitops' }; + constructor(private readonly repository: OrganizationRepository) {} + + async listOrganizations() { + const organizations = await this.repository.findAll(); + return organizations.map((organization) => organization.toJson()); + } + + async getOrganization(id: string) { + const organization = await this.repository.findById(id); + if (!organization) { + throw new Error('Organization not found'); + } + return organization.toJson(); + } + + async findBySlug(slug: string) { + const organization = await this.repository.findBySlug(slug); + if (!organization) { + throw new Error('Organization not found'); + } + return organization.toJson(); + } + + // non-throwing variant, for callers that should degrade gracefully (e.g. the root layout) + async tryFindBySlug(slug: string) { + const organization = await this.repository.findBySlug(slug); + return organization ? organization.toJson() : null; + } + + // resolves the org to use when no slug is present in the route (e.g. bare '/') + // returns null when no organization exists yet, instead of throwing + async getDefaultOrganization() { + const organizations = await this.repository.findAll(); + return organizations.length > 0 ? organizations[0].toJson() : null; + } + + async createOrganization(input: { name: string; slug?: string; description?: string }) { + const name = input.name.trim(); + if (!name) { + throw new Error('Organization name is required'); + } + + const slug = this.normalizeSlug(input.slug || name); + if (!slug) { + throw new Error('Organization slug is required'); + } + + const existing = await this.repository.findBySlug(slug); + if (existing) { + throw new Error('An organization with this slug already exists'); + } + + await this.repository.create({ + id: crypto.randomUUID(), + slug, + name, + description: input.description?.trim() || undefined, + }); + + const created = await this.repository.findBySlug(slug); + if (!created) { + throw new Error('Failed to create organization'); + } + + return created.toJson(); + } + + async updateOrganization( + id: string, + changes: { name?: string; slug?: string; description?: string }, + ) { + const organization = await this.repository.findById(id); + if (!organization) { + throw new Error('Organization not found'); + } + + const patch: { name?: string; slug?: string; description?: string } = {}; + + if (changes.name !== undefined) { + const name = changes.name.trim(); + if (!name) { + throw new Error('Organization name is required'); + } + patch.name = name; + } + + if (changes.slug !== undefined) { + const slug = this.normalizeSlug(changes.slug); + if (!slug) { + throw new Error('Organization slug is required'); + } + + const existing = await this.repository.findBySlug(slug); + if (existing && existing.id !== id) { + throw new Error('An organization with this slug already exists'); + } + patch.slug = slug; + } + + if (changes.description !== undefined) { + patch.description = changes.description.trim(); + } + + await this.repository.update(id, patch); + + const updated = await this.repository.findById(id); + if (!updated) { + throw new Error('Failed to update organization'); + } + + return updated.toJson(); + } + + async deleteOrganization(id: string) { + const organization = await this.repository.findById(id); + if (!organization) { + throw new Error('Organization not found'); + } + + await this.repository.deleteById(id); + } + + // seeds the single default org so existing routes keep resolving 'gitops' out of the box + async bootstrapDefaults(): Promise { + const existing = await this.repository.findBySlug(DEFAULT_ORGANIZATION.slug); + if (existing) { + return; + } + + await this.repository.create({ + id: crypto.randomUUID(), + slug: DEFAULT_ORGANIZATION.slug, + name: DEFAULT_ORGANIZATION.name, + }); + } + + private normalizeSlug(value: string): string { + return value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); } } diff --git a/src/modules/organization/domain/organization.domain.ts b/src/modules/organization/domain/organization.domain.ts new file mode 100644 index 00000000..5daf65ac --- /dev/null +++ b/src/modules/organization/domain/organization.domain.ts @@ -0,0 +1,25 @@ +import { Domain } from '$lib/server/domain/domain'; + +export class OrganizationDomain extends Domain { + public name: string = ''; + public slug: string = ''; + public description?: string | null = null; + + constructor(data: any) { + super(data); + this.name = data.name; + this.slug = data.slug; + this.description = data.description; + } + + toJson() { + return { + id: this.id, + name: this.name, + slug: this.slug, + description: this.description, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} diff --git a/src/modules/organization/index.ts b/src/modules/organization/index.ts index 635db93d..ad14d919 100644 --- a/src/modules/organization/index.ts +++ b/src/modules/organization/index.ts @@ -1,4 +1,15 @@ import { OrganizationService } from './application/organization.service'; +import { OrganizationRepository } from './infrastructure/repositories/organization.repository'; -export const organizationService = new OrganizationService(); +const organizationRepository = new OrganizationRepository(); + +export const organizationService = new OrganizationService(organizationRepository); export type { Organization } from './application/organization.service'; +export { OrganizationDomain } from './domain/organization.domain'; + +// Bootstrap the default org once at startup. +const organizationBootstrap = organizationService.bootstrapDefaults(); + +export async function ensureOrganizationReady(): Promise { + await organizationBootstrap; +} diff --git a/src/modules/organization/infrastructure/repositories/organization.repository.ts b/src/modules/organization/infrastructure/repositories/organization.repository.ts new file mode 100644 index 00000000..8193bc6b --- /dev/null +++ b/src/modules/organization/infrastructure/repositories/organization.repository.ts @@ -0,0 +1,52 @@ +import { Repository } from '$lib/server/infra/repository'; +import { OrganizationDomain } from '../../domain/organization.domain'; +import { OrganizationEntity } from '$lib/database/schemas'; + +export class OrganizationRepository extends Repository { + async findAll(): Promise { + const result = await this.db.select().from(OrganizationEntity).orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new OrganizationDomain(row)); + } + + async findById(id: string): Promise { + const result = await this.db.select().from(OrganizationEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new OrganizationDomain(row) : null; + } + + async findBySlug(slug: string): Promise { + const result = await this.db.select().from(OrganizationEntity).where({ slug }).limit(1); + const row = result.rows[0]; + return row ? new OrganizationDomain(row) : null; + } + + async create(input: { + id: string; + slug: string; + name: string; + description?: string; + }): Promise { + await this.db.insert(OrganizationEntity).values({ + id: input.id, + slug: input.slug, + name: input.name, + description: input.description, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + } + + async update( + id: string, + changes: { name?: string; slug?: string; description?: string }, + ): Promise { + await this.db + .update(OrganizationEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async deleteById(id: string): Promise { + await this.db.delete(OrganizationEntity).where({ id }); + } +} diff --git a/src/modules/projects/application/project.service.test.ts b/src/modules/projects/application/project.service.test.ts index 6616a256..4bd1bc41 100644 --- a/src/modules/projects/application/project.service.test.ts +++ b/src/modules/projects/application/project.service.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it, beforeEach } from 'vitest'; import { ProjectService } from './project.service'; import { ProjectDomain } from '../domain/project.domain'; +const DEFAULT_ORGANIZATION_ID = 'org-1'; + class FakeProjectRepository { rows: ProjectDomain[] = []; @@ -19,6 +21,7 @@ class FakeProjectRepository { async create(input: { id: string; + organizationId: string; slug: string; name: string; description?: string; @@ -28,6 +31,7 @@ class FakeProjectRepository { this.rows.push( new ProjectDomain({ id: input.id, + organization: { id: input.organizationId, name: 'Org', slug: 'org' }, slug: input.slug, name: input.name, description: input.description, @@ -47,6 +51,7 @@ class FakeProjectRepository { description?: string; status?: string; modules?: { vault: boolean; openreport: boolean; stateiac: boolean }; + organizationId?: string; }, ) { const project = this.rows.find((p) => p.id === id); @@ -56,6 +61,9 @@ class FakeProjectRepository { if (changes.description !== undefined) project.description = changes.description; if (changes.status !== undefined) project.status = changes.status as 'active' | 'inactive'; if (changes.modules !== undefined) project.modules = changes.modules; + if (changes.organizationId !== undefined) { + project.organization = { id: changes.organizationId, name: 'Org', slug: 'org' } as any; + } } async deleteById(id: string) { @@ -63,22 +71,36 @@ class FakeProjectRepository { } } +class FakeOrganizationLookup { + async getOrganization(id: string) { + return { id, name: 'Org', slug: 'org' }; + } +} + describe('ProjectService', () => { let repository: FakeProjectRepository; let service: ProjectService; beforeEach(() => { repository = new FakeProjectRepository(); - service = new ProjectService(repository as any); + service = new ProjectService(repository as any, new FakeOrganizationLookup()); }); + function withOrg(input: Record = {}) { + return { organizationId: DEFAULT_ORGANIZATION_ID, ...input }; + } + + function createProject(input: Record) { + return service.createProject(withOrg(input) as any); + } + describe('listProjects', () => { it('returns an empty list when there are no projects', async () => { expect(await service.listProjects()).toEqual([]); }); it('lists created projects', async () => { - await service.createProject({ name: 'Platform Core' }); + await createProject({ name: 'Platform Core' }); const projects = await service.listProjects(); expect(projects).toHaveLength(1); expect(projects[0].slug).toBe('platform-core'); @@ -92,7 +114,7 @@ describe('ProjectService', () => { }); it('returns the project by id and by slug', async () => { - const created = await service.createProject({ name: 'Kettu Studio' }); + const created = await createProject({ name: 'Kettu Studio' }); const byId = await service.getProject(created.id); expect(byId.slug).toBe('kettu-studio'); @@ -104,43 +126,41 @@ describe('ProjectService', () => { describe('createProject', () => { it('requires a non-empty name', async () => { - await expect(service.createProject({ name: ' ' })).rejects.toThrow(/name is required/); + await expect(createProject({ name: ' ' })).rejects.toThrow(/name is required/); }); it('auto-generates a normalized slug from the name when none is provided', async () => { - const project = await service.createProject({ name: 'Kettu Studio!!' }); + const project = await createProject({ name: 'Kettu Studio!!' }); expect(project.slug).toBe('kettu-studio'); }); it('uses the provided slug, normalized', async () => { - const project = await service.createProject({ name: 'Kettu Studio', slug: 'Custom Slug' }); + const project = await createProject({ name: 'Kettu Studio', slug: 'Custom Slug' }); expect(project.slug).toBe('custom-slug'); }); it('rejects creating a project with a duplicate slug', async () => { - await service.createProject({ name: 'Kettu Studio' }); - await expect(service.createProject({ name: 'Kettu Studio' })).rejects.toThrow( - /already exists/, - ); + await createProject({ name: 'Kettu Studio' }); + await expect(createProject({ name: 'Kettu Studio' })).rejects.toThrow(/already exists/); }); it('defaults status to active for missing or invalid values', async () => { - const project = await service.createProject({ name: 'Project A' }); + const project = await createProject({ name: 'Project A' }); expect(project.status).toBe('active'); }); it('accepts an explicit inactive status', async () => { - const project = await service.createProject({ name: 'Project B', status: 'inactive' }); + const project = await createProject({ name: 'Project B', status: 'inactive' }); expect(project.status).toBe('inactive'); }); it('defaults all modules to enabled when none are provided', async () => { - const project = await service.createProject({ name: 'Project C' }); + const project = await createProject({ name: 'Project C' }); expect(project.modules).toEqual({ vault: true, openreport: true, stateiac: true }); }); it('accepts a partial modules override, defaulting the rest to enabled', async () => { - const project = await service.createProject({ + const project = await createProject({ name: 'Project D', modules: { vault: false }, }); @@ -154,7 +174,7 @@ describe('ProjectService', () => { }); it('updates only the fields provided', async () => { - const created = await service.createProject({ name: 'Original Name' }); + const created = await createProject({ name: 'Original Name' }); const updated = await service.updateProject(created.id, { description: 'New description' }); expect(updated.name).toBe('Original Name'); @@ -162,21 +182,21 @@ describe('ProjectService', () => { }); it('rejects clearing the name', async () => { - const created = await service.createProject({ name: 'Original Name' }); + const created = await createProject({ name: 'Original Name' }); await expect(service.updateProject(created.id, { name: ' ' })).rejects.toThrow( /name is required/, ); }); it('normalizes the slug when updating it', async () => { - const created = await service.createProject({ name: 'Original Name' }); + const created = await createProject({ name: 'Original Name' }); const updated = await service.updateProject(created.id, { slug: 'New Slug!!' }); expect(updated.slug).toBe('new-slug'); }); it('rejects updating to a slug already used by another project', async () => { - await service.createProject({ name: 'Project A', slug: 'taken' }); - const created = await service.createProject({ name: 'Project B' }); + await createProject({ name: 'Project A', slug: 'taken' }); + const created = await createProject({ name: 'Project B' }); await expect(service.updateProject(created.id, { slug: 'taken' })).rejects.toThrow( /already exists/, @@ -184,13 +204,13 @@ describe('ProjectService', () => { }); it('allows keeping the same slug on the same project', async () => { - const created = await service.createProject({ name: 'Project A', slug: 'same-slug' }); + const created = await createProject({ name: 'Project A', slug: 'same-slug' }); const updated = await service.updateProject(created.id, { slug: 'same-slug' }); expect(updated.slug).toBe('same-slug'); }); it('merges partial module updates with the existing modules', async () => { - const created = await service.createProject({ name: 'Project A' }); + 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 }); @@ -202,7 +222,7 @@ describe('ProjectService', () => { }); it('updates the status', async () => { - const created = await service.createProject({ name: 'Project A' }); + const created = await createProject({ name: 'Project A' }); const updated = await service.updateProject(created.id, { status: 'inactive' }); expect(updated.status).toBe('inactive'); }); @@ -214,7 +234,7 @@ describe('ProjectService', () => { }); it('deletes an existing project', async () => { - const created = await service.createProject({ name: 'Project A' }); + const created = await createProject({ name: 'Project A' }); await service.deleteProject(created.id); diff --git a/src/modules/projects/application/project.service.ts b/src/modules/projects/application/project.service.ts index 89a92d76..87f346a1 100644 --- a/src/modules/projects/application/project.service.ts +++ b/src/modules/projects/application/project.service.ts @@ -4,14 +4,26 @@ import { DEFAULT_PROJECT_MODULES, type ProjectModules } from '../domain/project. export type ProjectStatusValue = 'active' | 'inactive'; +export interface OrganizationLookup { + getOrganization(id: string): Promise; +} + export class ProjectService { - constructor(private readonly repository: ProjectRepository) {} + constructor( + private readonly repository: ProjectRepository, + private readonly organizationLookup: OrganizationLookup, + ) {} async listProjects() { const projects = await this.repository.findAll(); return projects.map((project) => project.toJson()); } + async listProjectsByOrganization(organizationId: string) { + const projects = await this.repository.findByOrganizationId(organizationId); + return projects.map((project) => project.toJson()); + } + async getProject(id: string) { const project = await this.repository.findById(id); if (!project) { @@ -29,12 +41,19 @@ export class ProjectService { } async createProject(input: { + organizationId: string; name: string; slug?: string; description?: string; status?: string; modules?: Partial; }) { + const organizationId = input.organizationId?.trim(); + if (!organizationId) { + throw new Error('Organization is required'); + } + await this.organizationLookup.getOrganization(organizationId); + const name = input.name.trim(); if (!name) { throw new Error('Project name is required'); @@ -52,6 +71,7 @@ export class ProjectService { await this.repository.create({ id: crypto.randomUUID(), + organizationId, slug, name, description: input.description?.trim() || undefined, @@ -75,6 +95,7 @@ export class ProjectService { description?: string; status?: string; modules?: Partial; + organizationId?: string; }, ) { const project = await this.repository.findById(id); @@ -88,8 +109,18 @@ export class ProjectService { description?: string; status?: string; modules?: ProjectModules; + organizationId?: string; } = {}; + if (changes.organizationId !== undefined) { + const organizationId = changes.organizationId.trim(); + if (!organizationId) { + throw new Error('Organization is required'); + } + await this.organizationLookup.getOrganization(organizationId); + patch.organizationId = organizationId; + } + if (changes.name !== undefined) { const name = changes.name.trim(); if (!name) { diff --git a/src/modules/projects/domain/project.domain.ts b/src/modules/projects/domain/project.domain.ts index f4d927de..8dfef0a6 100644 --- a/src/modules/projects/domain/project.domain.ts +++ b/src/modules/projects/domain/project.domain.ts @@ -1,4 +1,5 @@ import { Domain } from '$lib/server/domain/domain'; +import { OrganizationDomain } from '../../organization/domain/organization.domain'; export interface ProjectStatus { ACTIVE: 'active'; @@ -23,6 +24,7 @@ export class ProjectDomain extends Domain { public description?: string | null = null; public status: ProjectStatus[keyof ProjectStatus] = 'active'; public modules: ProjectModules = { ...DEFAULT_PROJECT_MODULES }; + public organization: OrganizationDomain | null = null; constructor(data: any) { super(data); this.name = data.name; @@ -30,6 +32,7 @@ export class ProjectDomain extends Domain { this.description = data.description; this.status = data.status; this.modules = { ...DEFAULT_PROJECT_MODULES, ...(data.modules ?? {}) }; + this.organization = data.organization ? new OrganizationDomain(data.organization) : null; } toJson() { @@ -42,6 +45,7 @@ export class ProjectDomain extends Domain { status: this.status, modules: this.modules, updatedAt: this.updatedAt, + organization: this.organization ? this.organization.toJson() : null, }; } } diff --git a/src/modules/projects/index.ts b/src/modules/projects/index.ts index aab224f1..cc2ef734 100644 --- a/src/modules/projects/index.ts +++ b/src/modules/projects/index.ts @@ -1,6 +1,7 @@ import { ProjectService } from './application/project.service'; import { ProjectRepository } from './infrastructure/repositories/project.repostitory'; +import { organizationService } from '../organization'; const projectRepository = new ProjectRepository(); -export const projectService = new ProjectService(projectRepository); +export const projectService = new ProjectService(projectRepository, organizationService); diff --git a/src/modules/projects/infrastructure/repositories/project.repostitory.ts b/src/modules/projects/infrastructure/repositories/project.repostitory.ts index c80539ec..f237cd4f 100644 --- a/src/modules/projects/infrastructure/repositories/project.repostitory.ts +++ b/src/modules/projects/infrastructure/repositories/project.repostitory.ts @@ -4,29 +4,59 @@ import { ProjectEntity } from '$lib/database/schemas'; export class ProjectRepository extends Repository { async findByName(name: string): Promise { - const role = await this.db.select().from(ProjectEntity).where({ name }).limit(1); + const role = await this.db + .with({ organization: true }) + .select() + .from(ProjectEntity) + .where({ name }) + .limit(1); return role.rows[0] ? new ProjectDomain(role.rows[0]) : null; } async findAll(): Promise { - const result = await this.db.select().from(ProjectEntity).orderBy('createdAt', 'asc'); + const result = await this.db + .with({ organization: true }) + .select() + .from(ProjectEntity) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new ProjectDomain(row)); + } + + async findByOrganizationId(organizationId: string): Promise { + const result = await this.db + .with({ organization: true }) + .select() + .from(ProjectEntity) + .where({ organizationId }) + .orderBy('createdAt', 'asc'); return result.rows.map((row: any) => new ProjectDomain(row)); } async findById(id: string): Promise { - const result = await this.db.select().from(ProjectEntity).where({ id }).limit(1); + const result = await this.db + .with({ organization: true }) + .select() + .from(ProjectEntity) + .where({ id }) + .limit(1); const row = result.rows[0]; return row ? new ProjectDomain(row) : null; } async findBySlug(slug: string): Promise { - const result = await this.db.select().from(ProjectEntity).where({ slug }).limit(1); + const result = await this.db + .with({ organization: true }) + .select() + .from(ProjectEntity) + .where({ slug }) + .limit(1); const row = result.rows[0]; return row ? new ProjectDomain(row) : null; } async create(input: { id: string; + organizationId: string; slug: string; name: string; description?: string; @@ -35,6 +65,7 @@ export class ProjectRepository extends Repository { }): Promise { await this.db.insert(ProjectEntity).values({ id: input.id, + organizationId: input.organizationId, slug: input.slug, name: input.name, description: input.description, @@ -53,6 +84,7 @@ export class ProjectRepository extends Repository { description?: string; status?: string; modules?: ProjectModules; + organizationId?: string; }, ): Promise { await this.db diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 5de5c53d..1764ceac 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,9 +1,9 @@ import { projectService } from '../modules/projects'; import { organizationService } from '../modules/organization'; -import { can } from '../modules/auth'; +import { cancanService } from '../modules/auth'; // import { configService, storageBackendService } from '../modules/config'; -export async function load({ locals }) { +export async function load({ locals, url }) { // const config = configService.getConfig(); // const backends = storageBackendService.list(); @@ -15,12 +15,29 @@ export async function load({ locals }) { // activeBackendId = activeBackend.id; // } - const organization = await organizationService.findBySlug('gitops'); + const orgSlugFromUrl = url.pathname.match(/^\/org\/([^/]+)/)?.[1]; + const organization = orgSlugFromUrl + ? await organizationService.tryFindBySlug(orgSlugFromUrl) + : await organizationService.getDefaultOrganization(); - const projects = - locals.user && can(locals.user, 'stateiac:read') - ? (await projectService.listProjects()).filter((project) => project.status === 'active') - : []; + const projects = locals.user + ? ( + await Promise.all( + (await projectService.listProjects()) + .filter((project) => project.status === 'active') + .map(async (project) => ({ + project, + allowed: await cancanService.canSessionUser(locals.user, 'stateiac:read', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }), + })), + ) + ) + .filter(({ allowed }) => allowed) + .map(({ project }) => project) + : []; return { // isConfigured: !!config && backends.length > 0, diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index ede3a411..9cd36f5a 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -29,7 +29,7 @@ @@ -42,7 +42,8 @@ diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts index e23bdf3d..d9ab3b03 100644 --- a/src/routes/+page.server.ts +++ b/src/routes/+page.server.ts @@ -2,6 +2,9 @@ import { redirect } from '@sveltejs/kit'; import { organizationService } from '../modules/organization'; export async function load() { - const organization = await organizationService.findBySlug('gitops'); + const organization = await organizationService.getDefaultOrganization(); + if (!organization) { + throw redirect(302, '/cluster-settings/orgs'); + } throw redirect(302, `/org/${organization.slug}/overview`); } diff --git a/src/routes/api/backends/+server.ts b/src/routes/api/backends/+server.ts index 70e14283..7d3de8bf 100644 --- a/src/routes/api/backends/+server.ts +++ b/src/routes/api/backends/+server.ts @@ -1,9 +1,9 @@ import { json } from '@sveltejs/kit'; import { storageBackendService } from '../../../modules/config'; -import { can } from '../../../modules/auth'; +import { cancanService } from '../../../modules/auth'; export async function GET({ locals }) { - if (!can(locals.user, 'stateiac:read')) { + if (!(await cancanService.canSessionUser(locals.user, 'stateiac:read', { scope: 'cluster' }))) { return json({ error: 'Forbidden' }, { status: 403 }); } @@ -14,7 +14,13 @@ export async function POST({ request, locals }) { try { const data = await request.json(); - if (!can(locals.user, data.id ? 'stateiac:update' : 'stateiac:create')) { + if ( + !(await cancanService.canSessionUser( + locals.user, + data.id ? 'stateiac:update' : 'stateiac:create', + { scope: 'cluster' }, + )) + ) { return json({ error: 'Forbidden' }, { status: 403 }); } diff --git a/src/routes/api/backends/[id]/+server.ts b/src/routes/api/backends/[id]/+server.ts index a423461c..9bfff352 100644 --- a/src/routes/api/backends/[id]/+server.ts +++ b/src/routes/api/backends/[id]/+server.ts @@ -1,9 +1,9 @@ import { json } from '@sveltejs/kit'; import { storageBackendService } from '../../../../modules/config'; -import { can } from '../../../../modules/auth'; +import { cancanService } from '../../../../modules/auth'; export async function DELETE({ params, locals }) { - if (!can(locals.user, 'stateiac:delete')) { + if (!(await cancanService.canSessionUser(locals.user, 'stateiac:delete', { scope: 'cluster' }))) { return json({ error: 'Forbidden' }, { status: 403 }); } diff --git a/src/routes/api/organizations/+server.ts b/src/routes/api/organizations/+server.ts new file mode 100644 index 00000000..bd9ca2f0 --- /dev/null +++ b/src/routes/api/organizations/+server.ts @@ -0,0 +1,42 @@ +import { json } from '@sveltejs/kit'; +import { organizationService } from '../../../modules/organization'; +import { cancanService } from '../../../modules/auth'; + +export async function GET({ locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + + try { + const organizations = await organizationService.listOrganizations(); + return json({ organizations }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : 'Unknown error'; + return json({ error: message }, { status: 500 }); + } +} + +export async function POST({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + + try { + const data = (await request.json()) as { + name?: string; + slug?: string; + description?: string; + }; + + const organization = await organizationService.createOrganization({ + name: String(data.name || ''), + slug: data.slug ? String(data.slug) : undefined, + description: data.description ? String(data.description) : undefined, + }); + + return json({ success: true, organization }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : 'Unknown error'; + return json({ error: message }, { status: 400 }); + } +} diff --git a/src/routes/api/organizations/[id]/+server.ts b/src/routes/api/organizations/[id]/+server.ts new file mode 100644 index 00000000..fc43873d --- /dev/null +++ b/src/routes/api/organizations/[id]/+server.ts @@ -0,0 +1,56 @@ +import { json } from '@sveltejs/kit'; +import { organizationService } from '../../../../modules/organization'; +import { cancanService } from '../../../../modules/auth'; + +export async function GET({ params, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + + try { + const organization = await organizationService.getOrganization(params.id); + return json({ organization }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : 'Unknown error'; + return json({ error: message }, { status: 404 }); + } +} + +export async function PATCH({ request, params, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + + try { + const data = (await request.json()) as { + name?: string; + slug?: string; + description?: string; + }; + + const organization = await organizationService.updateOrganization(params.id, { + name: data.name, + slug: data.slug, + description: data.description, + }); + + return json({ success: true, organization }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : 'Unknown error'; + return json({ error: message }, { status: 400 }); + } +} + +export async function DELETE({ params, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + + try { + await organizationService.deleteOrganization(params.id); + return json({ success: true }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : 'Unknown error'; + return json({ error: message }, { status: 400 }); + } +} diff --git a/src/routes/api/projects/+server.ts b/src/routes/api/projects/+server.ts index 7ca2ebb5..f94f721f 100644 --- a/src/routes/api/projects/+server.ts +++ b/src/routes/api/projects/+server.ts @@ -1,14 +1,17 @@ import { json } from '@sveltejs/kit'; import { projectService } from '../../../modules/projects'; -import { can } from '../../../modules/auth'; +import { cancanService } from '../../../modules/auth'; -export async function GET({ locals }) { - if (!can(locals.user, 'stateiac:read')) { +export async function GET({ url, locals }) { + if (!(await cancanService.canSessionUser(locals.user, 'stateiac:read', { scope: 'cluster' }))) { return json({ error: 'Forbidden' }, { status: 403 }); } try { - const projects = await projectService.listProjects(); + const organizationId = url.searchParams.get('organizationId'); + const projects = organizationId + ? await projectService.listProjectsByOrganization(organizationId) + : await projectService.listProjects(); return json({ projects }); } catch (error: unknown) { const message = error instanceof Error ? error.message : 'Unknown error'; @@ -17,12 +20,9 @@ export async function GET({ locals }) { } export async function POST({ request, locals }) { - if (!can(locals.user, 'stateiac:create')) { - return json({ error: 'Forbidden' }, { status: 403 }); - } - try { const data = (await request.json()) as { + organizationId?: string; name?: string; slug?: string; description?: string; @@ -30,7 +30,19 @@ export async function POST({ request, locals }) { modules?: { vault?: boolean; openreport?: boolean; stateiac?: boolean }; }; + const canCreate = data.organizationId + ? await cancanService.canSessionUser(locals.user, 'stateiac:create', { + scope: 'organization', + organizationId: data.organizationId, + }) + : await cancanService.canSessionUser(locals.user, 'stateiac:create', { scope: 'cluster' }); + + if (!canCreate) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + const project = await projectService.createProject({ + organizationId: String(data.organizationId || ''), name: String(data.name || ''), slug: data.slug ? String(data.slug) : undefined, description: data.description ? String(data.description) : undefined, diff --git a/src/routes/api/projects/[id]/+server.ts b/src/routes/api/projects/[id]/+server.ts index f76ca960..211c9755 100644 --- a/src/routes/api/projects/[id]/+server.ts +++ b/src/routes/api/projects/[id]/+server.ts @@ -1,14 +1,20 @@ import { json } from '@sveltejs/kit'; import { projectService } from '../../../../modules/projects'; -import { can } from '../../../../modules/auth'; +import { cancanService } from '../../../../modules/auth'; export async function GET({ params, locals }) { - if (!can(locals.user, 'stateiac:read')) { - return json({ error: 'Forbidden' }, { status: 403 }); - } - try { const project = await projectService.getProject(params.id); + if ( + !(await cancanService.canSessionUser(locals.user, 'stateiac:read', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + })) + ) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + return json({ project }); } catch (error: unknown) { const message = error instanceof Error ? error.message : 'Unknown error'; @@ -17,12 +23,20 @@ export async function GET({ params, locals }) { } export async function PATCH({ request, params, locals }) { - if (!can(locals.user, 'stateiac:update')) { - return json({ error: 'Forbidden' }, { status: 403 }); - } - try { + const currentProject = await projectService.getProject(params.id); + if ( + !(await cancanService.canSessionUser(locals.user, 'stateiac:update', { + scope: 'project', + projectId: currentProject.id, + organizationId: currentProject.organization?.id, + })) + ) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + const data = (await request.json()) as { + organizationId?: string; name?: string; slug?: string; description?: string; @@ -31,6 +45,7 @@ export async function PATCH({ request, params, locals }) { }; const project = await projectService.updateProject(params.id, { + organizationId: data.organizationId, name: data.name, slug: data.slug, description: data.description, @@ -46,11 +61,18 @@ export async function PATCH({ request, params, locals }) { } export async function DELETE({ params, locals }) { - if (!can(locals.user, 'stateiac:delete')) { - return json({ error: 'Forbidden' }, { status: 403 }); - } - try { + const project = await projectService.getProject(params.id); + if ( + !(await cancanService.canSessionUser(locals.user, 'stateiac:delete', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + })) + ) { + return json({ error: 'Forbidden' }, { status: 403 }); + } + await projectService.deleteProject(params.id); return json({ success: true }); } catch (error: unknown) { diff --git a/src/routes/api/projects/sync/+server.ts b/src/routes/api/projects/sync/+server.ts index 34b8b1d5..0567557e 100644 --- a/src/routes/api/projects/sync/+server.ts +++ b/src/routes/api/projects/sync/+server.ts @@ -2,10 +2,10 @@ import { json } from '@sveltejs/kit'; import { storageBackendService } from '../../../../modules/config'; import { projectService } from '../../../../modules/projects'; import { storageService } from '../../../../modules/storage'; -import { can } from '../../../../modules/auth'; +import { cancanService } from '../../../../modules/auth'; export async function POST({ cookies, locals }) { - if (!can(locals.user, 'stateiac:update')) { + if (!(await cancanService.canSessionUser(locals.user, 'stateiac:update', { scope: 'cluster' }))) { return json({ error: 'Forbidden' }, { status: 403 }); } diff --git a/src/routes/api/roles/+server.ts b/src/routes/api/roles/+server.ts index 1e43b006..57f216a6 100644 --- a/src/routes/api/roles/+server.ts +++ b/src/routes/api/roles/+server.ts @@ -1,13 +1,17 @@ import { json } from '@sveltejs/kit'; -import { roleService, isAdmin } from '../../../modules/auth'; +import { roleService, cancanService } from '../../../modules/auth'; -export async function GET({ locals }) { +export async function GET({ locals, url }) { if (!locals.user) { return json({ error: 'Forbidden' }, { status: 403 }); } try { - const roles = await roleService.listRoles(); + const scope = (url.searchParams.get('scope') ?? 'cluster') as + 'cluster' | 'organization' | 'project'; + const scopeId = + url.searchParams.get('organizationId') ?? url.searchParams.get('projectId') ?? undefined; + const roles = await roleService.listRoles(scope, scopeId); return json({ roles }); } catch (error: unknown) { const message = error instanceof Error ? error.message : 'Failed to list roles'; @@ -16,17 +20,27 @@ export async function GET({ locals }) { } export async function POST({ request, locals }) { - if (!locals.user || !isAdmin(locals.user)) { + if (!cancanService.canAccessAdminArea(locals.user)) { return json({ error: 'Forbidden' }, { status: 403 }); } try { - const data = (await request.json()) as { name?: string; slug?: string; permissions?: string[] }; + const data = (await request.json()) as { + name?: string; + slug?: string; + permissions?: string[]; + scope?: 'cluster' | 'organization' | 'project'; + organizationId?: string; + projectId?: string; + }; const role = await roleService.createRole({ name: data.name ?? '', slug: data.slug ?? '', permissions: Array.isArray(data.permissions) ? data.permissions : [], + scope: data.scope, + organizationId: data.organizationId, + projectId: data.projectId, }); return json({ success: true, role }); diff --git a/src/routes/api/roles/[id]/+server.ts b/src/routes/api/roles/[id]/+server.ts index f378f2f8..c01eca54 100644 --- a/src/routes/api/roles/[id]/+server.ts +++ b/src/routes/api/roles/[id]/+server.ts @@ -1,8 +1,8 @@ import { json } from '@sveltejs/kit'; -import { roleService, isAdmin } from '../../../../modules/auth'; +import { roleService, cancanService } from '../../../../modules/auth'; export async function PATCH({ request, params, locals }) { - if (!locals.user || !isAdmin(locals.user)) { + if (!cancanService.canAccessAdminArea(locals.user)) { return json({ error: 'Forbidden' }, { status: 403 }); } @@ -22,7 +22,7 @@ export async function PATCH({ request, params, locals }) { } export async function DELETE({ params, locals }) { - if (!locals.user || !isAdmin(locals.user)) { + if (!cancanService.canAccessAdminArea(locals.user)) { return json({ error: 'Forbidden' }, { status: 403 }); } diff --git a/src/routes/cluster-settings/+layout.svelte b/src/routes/cluster-settings/+layout.svelte new file mode 100644 index 00000000..98bd2cec --- /dev/null +++ b/src/routes/cluster-settings/+layout.svelte @@ -0,0 +1,14 @@ + + Cluster Settings - GitVault Suite + + +
+
+
+

Cluster Settings

+
+
+ +
+
+
diff --git a/src/routes/settings/+page.server.ts b/src/routes/cluster-settings/+page.server.ts similarity index 57% rename from src/routes/settings/+page.server.ts rename to src/routes/cluster-settings/+page.server.ts index 2471ee43..6802e6ca 100644 --- a/src/routes/settings/+page.server.ts +++ b/src/routes/cluster-settings/+page.server.ts @@ -1,5 +1,5 @@ import { redirect } from '@sveltejs/kit'; export function load() { - throw redirect(302, '/settings/authentication'); + throw redirect(302, '/cluster-settings/orgs'); } diff --git a/src/routes/cluster-settings/orgs/+page.svelte b/src/routes/cluster-settings/orgs/+page.svelte new file mode 100644 index 00000000..a481aacf --- /dev/null +++ b/src/routes/cluster-settings/orgs/+page.svelte @@ -0,0 +1,410 @@ + + + + Organizations - Cluster Settings + + +
+
+
+

Organizations

+

Create, view and manage cluster organizations.

+
+ + +
+ +
+
+ + +
+
+ + {#if error} +
+ {error} +
+ {/if} + + {#if success} +
+ {success} +
+ {/if} + + {#if loading} +
+ Loading organizations... +
+ {:else if filteredOrganizations.length === 0} +
+ {organizations.length === 0 + ? 'No organizations found.' + : 'No organizations match your search.'} +
+ {:else} +
+
+ + + + + + + + + + + {#each filteredOrganizations as organization (organization.id)} + + + + + + + {/each} + +
NameSlugCreatedActions
+
+ +
+

{organization.name}

+ {#if organization.description} +

{organization.description}

+ {/if} +
+
+
{organization.slug}{formatDate(organization.createdAt)} +
+ + + View + + +
+
+
+
+ {/if} +
+ +{#if createModalOpen} + +
+ +
+{/if} + +{#if deleteModalOrganization} + +
+ +
+{/if} diff --git a/src/routes/cluster-settings/orgs/[org]/+page.server.ts b/src/routes/cluster-settings/orgs/[org]/+page.server.ts new file mode 100644 index 00000000..a3fdcccd --- /dev/null +++ b/src/routes/cluster-settings/orgs/[org]/+page.server.ts @@ -0,0 +1,11 @@ +import { error } from '@sveltejs/kit'; +import { organizationService } from '../../../../modules/organization'; + +export async function load({ params }) { + try { + const organization = await organizationService.findBySlug(params.org); + return { organization }; + } catch { + throw error(404, 'Organization not found'); + } +} diff --git a/src/routes/cluster-settings/orgs/[org]/+page.svelte b/src/routes/cluster-settings/orgs/[org]/+page.svelte new file mode 100644 index 00000000..c0e0ee17 --- /dev/null +++ b/src/routes/cluster-settings/orgs/[org]/+page.svelte @@ -0,0 +1,272 @@ + + + + {organization.name} - Cluster Settings + + +
+ {#if error} +
+ {error} +
+ {/if} + + {#if success} +
+ {success} +
+ {/if} + +
+
+

Información

+ +
+ +
+
+
+ + +
+ +
+ + +
+
+ +
+ + +
+
+ +
+ +
+
+ +
+
+

Danger Zone

+
+
+
+

Delete organization

+

+ Permanently deletes this organization. This action cannot be undone. +

+
+ +
+
+
+ +{#if deleteModalOpen} + +
+ +
+{/if} diff --git a/src/routes/cluster-settings/roles-permissions/+page.server.ts b/src/routes/cluster-settings/roles-permissions/+page.server.ts new file mode 100644 index 00000000..485aea74 --- /dev/null +++ b/src/routes/cluster-settings/roles-permissions/+page.server.ts @@ -0,0 +1,64 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../modules/auth'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'Role action failed.' }); +} + +export async function load() { + const roles = await roleService.listRoles('cluster'); + return { roles }; +} + +export const actions = { + async createRole({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.createRole({ + name: String(form.get('name') ?? ''), + slug: String(form.get('slug') ?? ''), + permissions: parsePermissions(form.get('permissions')), + scope: 'cluster', + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async updateRole({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.updateRole(String(form.get('id') ?? ''), { + name: String(form.get('name') ?? ''), + permissions: parsePermissions(form.get('permissions')), + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async deleteRole({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + await roleService.deleteRole(String(form.get('id') ?? '')); + return { success: true }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/cluster-settings/roles-permissions/+page.svelte b/src/routes/cluster-settings/roles-permissions/+page.svelte new file mode 100644 index 00000000..d9a3228a --- /dev/null +++ b/src/routes/cluster-settings/roles-permissions/+page.svelte @@ -0,0 +1,12 @@ + + + diff --git a/src/routes/cluster-settings/roles-permissions/[id]/+page.server.ts b/src/routes/cluster-settings/roles-permissions/[id]/+page.server.ts new file mode 100644 index 00000000..c9e1335b --- /dev/null +++ b/src/routes/cluster-settings/roles-permissions/[id]/+page.server.ts @@ -0,0 +1,51 @@ +import { error, fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../modules/auth'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(errorValue: unknown) { + return fail(400, { + error: errorValue instanceof Error ? errorValue.message : 'Role action failed.', + }); +} + +export async function load({ params }) { + const roles = await roleService.listRoles('cluster'); + const role = roles.find((row) => row.id === params.id); + if (!role) throw error(404, 'Role not found'); + return { role }; +} + +export const actions = { + async updateRole({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.updateRole(String(form.get('id') ?? ''), { + name: String(form.get('name') ?? ''), + permissions: parsePermissions(form.get('permissions')), + }); + return { success: true, role }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, + + async deleteRole({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + await roleService.deleteRole(String(form.get('id') ?? '')); + return { success: true }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, +}; diff --git a/src/routes/cluster-settings/roles-permissions/[id]/+page.svelte b/src/routes/cluster-settings/roles-permissions/[id]/+page.svelte new file mode 100644 index 00000000..7544fcad --- /dev/null +++ b/src/routes/cluster-settings/roles-permissions/[id]/+page.svelte @@ -0,0 +1,12 @@ + + + diff --git a/src/routes/cluster-settings/roles-permissions/new/+page.server.ts b/src/routes/cluster-settings/roles-permissions/new/+page.server.ts new file mode 100644 index 00000000..8a996b5d --- /dev/null +++ b/src/routes/cluster-settings/roles-permissions/new/+page.server.ts @@ -0,0 +1,32 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../modules/auth'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'Role action failed.' }); +} + +export const actions = { + async createRole({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.createRole({ + name: String(form.get('name') ?? ''), + slug: String(form.get('slug') ?? ''), + permissions: parsePermissions(form.get('permissions')), + scope: 'cluster', + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/cluster-settings/roles-permissions/new/+page.svelte b/src/routes/cluster-settings/roles-permissions/new/+page.svelte new file mode 100644 index 00000000..d6a80373 --- /dev/null +++ b/src/routes/cluster-settings/roles-permissions/new/+page.svelte @@ -0,0 +1,9 @@ + + + diff --git a/src/routes/cluster-settings/users/+page.server.ts b/src/routes/cluster-settings/users/+page.server.ts new file mode 100644 index 00000000..4ca0a30a --- /dev/null +++ b/src/routes/cluster-settings/users/+page.server.ts @@ -0,0 +1,80 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService, userAccessService } from '../../../modules/auth'; + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'User action failed.' }); +} + +export async function load() { + const [users, roles] = await Promise.all([ + userAccessService.listUsers('cluster'), + roleService.listRoles('cluster'), + ]); + return { users, roles }; +} + +export const actions = { + async addUser({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const user = await userAccessService.createClusterUser({ + username: String(form.get('username') ?? ''), + email: String(form.get('email') ?? '') || null, + password: String(form.get('password') ?? ''), + roleId: String(form.get('roleId') ?? ''), + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async updateUserAccess({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const user = await userAccessService.updateAccess({ + accessId: String(form.get('accessId') ?? ''), + scope: 'cluster', + roleId: String(form.get('roleId') ?? ''), + status: String(form.get('status') ?? ''), + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async removeUserAccess({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + await userAccessService.removeAccess({ + accessId: String(form.get('accessId') ?? ''), + scope: 'cluster', + }); + return { success: true }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async resendInvitation({ request, locals }) { + if (!cancanService.canAccessAdminArea(locals.user)) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const user = await userAccessService.resendInvitation({ + accessId: String(form.get('accessId') ?? ''), + scope: 'cluster', + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/cluster-settings/users/+page.svelte b/src/routes/cluster-settings/users/+page.svelte new file mode 100644 index 00000000..bade11d7 --- /dev/null +++ b/src/routes/cluster-settings/users/+page.svelte @@ -0,0 +1,13 @@ + + + diff --git a/src/routes/org/+page.server.ts b/src/routes/org/+page.server.ts new file mode 100644 index 00000000..217317ac --- /dev/null +++ b/src/routes/org/+page.server.ts @@ -0,0 +1,6 @@ +import { organizationService } from '../../modules/organization'; + +export async function load() { + const organizations = await organizationService.listOrganizations(); + return { organizations }; +} diff --git a/src/routes/org/+page.svelte b/src/routes/org/+page.svelte new file mode 100644 index 00000000..70f913ce --- /dev/null +++ b/src/routes/org/+page.svelte @@ -0,0 +1,70 @@ + + + + Organizations - GitVault Suite + + +
+
+

Select an organization

+

Choose an organization to continue.

+
+ + {#if errorMessage} +
+ {errorMessage} +
+ {/if} + + {#if data.organizations.length === 0} +
+ No organizations found. +
+ {:else} + + {/if} +
diff --git a/src/routes/org/[org]/+layout.server.ts b/src/routes/org/[org]/+layout.server.ts index 577d60b1..bc3cb65c 100644 --- a/src/routes/org/[org]/+layout.server.ts +++ b/src/routes/org/[org]/+layout.server.ts @@ -1,6 +1,10 @@ +import { redirect } from '@sveltejs/kit'; import { organizationService } from '../../../modules/organization'; export async function load({ params }) { - const organization = await organizationService.findBySlug(params.org); + const organization = await organizationService.tryFindBySlug(params.org); + if (!organization) { + throw redirect(302, '/org?error=organization-not-found'); + } return { organization }; } diff --git a/src/routes/org/[org]/+page.server.ts b/src/routes/org/[org]/+page.server.ts new file mode 100644 index 00000000..a6fdeafc --- /dev/null +++ b/src/routes/org/[org]/+page.server.ts @@ -0,0 +1,10 @@ +import { redirect } from '@sveltejs/kit'; +import { organizationService } from '../../../modules/organization'; + +export async function load({ params }) { + const organization = await organizationService.tryFindBySlug(params.org); + if (!organization) { + throw redirect(302, '/org?error=organization-not-found'); + } + throw redirect(302, `/org/${organization.slug}/overview`); +} diff --git a/src/routes/org/[org]/overview/+page.server.ts b/src/routes/org/[org]/overview/+page.server.ts index 20194ff3..5d25f991 100644 --- a/src/routes/org/[org]/overview/+page.server.ts +++ b/src/routes/org/[org]/overview/+page.server.ts @@ -1,9 +1,16 @@ import { error } from '@sveltejs/kit'; import { projectService } from '../../../../modules/projects'; -import { can } from '../../../../modules/auth'; +import { cancanService } from '../../../../modules/auth'; -export async function load({ locals }) { - if (!can(locals.user, 'stateiac:read')) { +export async function load({ locals, parent }) { + const { organization } = await parent(); + + if ( + !(await cancanService.canSessionUser(locals.user, 'stateiac:read', { + scope: 'organization', + organizationId: organization.id, + })) + ) { throw error(403, 'Forbidden'); } diff --git a/src/routes/org/[org]/projects/[slug]/+layout.server.ts b/src/routes/org/[org]/projects/[slug]/+layout.server.ts index 3a5de88e..9baa3857 100644 --- a/src/routes/org/[org]/projects/[slug]/+layout.server.ts +++ b/src/routes/org/[org]/projects/[slug]/+layout.server.ts @@ -1,16 +1,42 @@ import { error } from '@sveltejs/kit'; import { projectService } from '../../../../../modules/projects'; -import { can } from '../../../../../modules/auth'; +import { cancanService } from '../../../../../modules/auth'; export async function load({ params, locals }) { - if (!can(locals.user, 'stateiac:read')) { - throw error(403, 'Forbidden'); - } - try { const project = await projectService.getProjectBySlug(params.slug); - return { project }; - } catch { + const organizationId = project.organization?.id; + const canRead = await cancanService.canSessionUser(locals.user, 'stateiac:read', { + scope: 'project', + projectId: project.id, + organizationId, + }); + + if (!canRead) { + throw error(403, 'Forbidden'); + } + + const [canCreateVault, canCreateOpenReport, canCreateStateIac] = await Promise.all([ + cancanService.canSessionUser(locals.user, 'vault:create', { + scope: 'project', + projectId: project.id, + organizationId, + }), + cancanService.canSessionUser(locals.user, 'openreport:create', { + scope: 'project', + projectId: project.id, + organizationId, + }), + cancanService.canSessionUser(locals.user, 'stateiac:create', { + scope: 'project', + projectId: project.id, + organizationId, + }), + ]); + + return { project, canCreateVault, canCreateOpenReport, canCreateStateIac }; + } catch (err) { + if (err && typeof err === 'object' && 'status' in err && err.status === 403) throw err; throw error(404, 'Project not found'); } } diff --git a/src/routes/org/[org]/projects/[slug]/report/+page.svelte b/src/routes/org/[org]/projects/[slug]/report/+page.svelte index ea40e278..ef839adf 100644 --- a/src/routes/org/[org]/projects/[slug]/report/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/report/+page.svelte @@ -1,9 +1,8 @@ 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 b5d3bad2..62ab8d9a 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte @@ -208,7 +208,7 @@ const payload = await res.json(); if (payload.error) throw new Error(payload.error); - await goto('/settings/projects'); + await goto(`/org/${orgSlug}/settings/projects`); } catch (err: unknown) { error = err instanceof Error ? err.message : 'Failed to delete project.'; deleteLoading = false; diff --git a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.server.ts new file mode 100644 index 00000000..ac5e448e --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.server.ts @@ -0,0 +1,88 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../../../../modules/auth'; +import { projectService } from '../../../../../../../modules/projects'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'Role action failed.' }); +} + +async function canManageProjectRole( + user: Parameters[0], + projectSlug: string, + permission: 'stateiac:create' | 'stateiac:update' | 'stateiac:delete', +) { + const project = await projectService.getProjectBySlug(projectSlug); + const allowed = await cancanService.canSessionUser(user, permission, { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + return { project, allowed }; +} + +export async function load({ parent }) { + const { project } = await parent(); + const roles = await roleService.listRoles('project', project.id); + return { roles }; +} + +export const actions = { + async createRole({ request, locals, params }) { + const { project, allowed } = await canManageProjectRole( + locals.user, + params.slug, + 'stateiac:create', + ); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.createRole({ + name: String(form.get('name') ?? ''), + slug: String(form.get('slug') ?? ''), + permissions: parsePermissions(form.get('permissions')), + scope: 'project', + projectId: project.id, + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async updateRole({ request, locals, params }) { + const { allowed } = await canManageProjectRole(locals.user, params.slug, 'stateiac:update'); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.updateRole(String(form.get('id') ?? ''), { + name: String(form.get('name') ?? ''), + permissions: parsePermissions(form.get('permissions')), + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async deleteRole({ request, locals, params }) { + const { allowed } = await canManageProjectRole(locals.user, params.slug, 'stateiac:delete'); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + await roleService.deleteRole(String(form.get('id') ?? '')); + return { success: true }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.svelte index 75678ba0..8ce5c957 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/+page.svelte @@ -1,24 +1,17 @@ + import RolePermissions from '$lib/components/RolePermissions.svelte'; - - Roles y Permisos - Projects - + export let data: { + project: { slug: string; organization: { slug: string } | null }; + roles: any[]; + }; -
-
-

Roles y Permisos

-

Define roles y permisos específicos por proyecto.

-
+ $: baseHref = `/org/${data.project.organization?.slug ?? ''}/projects/${data.project.slug}/settings/roles-permissions`; + -
- -

Próximamente

-

- Los roles y permisos por proyecto todavía no están disponibles. -

-
-
+ diff --git a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/[id]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/[id]/+page.server.ts new file mode 100644 index 00000000..8070a25a --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/[id]/+page.server.ts @@ -0,0 +1,69 @@ +import { error, fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../../../../../modules/auth'; +import { projectService } from '../../../../../../../../modules/projects'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(errorValue: unknown) { + return fail(400, { + error: errorValue instanceof Error ? errorValue.message : 'Role action failed.', + }); +} + +async function canManageProjectRole( + user: Parameters[0], + projectSlug: string, + permission: 'stateiac:create' | 'stateiac:update' | 'stateiac:delete', +) { + const project = await projectService.getProjectBySlug(projectSlug); + const allowed = await cancanService.canSessionUser(user, permission, { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + return { project, allowed }; +} + +export async function load({ parent, params }) { + const { project } = await parent(); + const roles = await roleService.listRoles('project', project.id); + const role = roles.find((row) => row.id === params.id); + if (!role) throw error(404, 'Role not found'); + return { project, role }; +} + +export const actions = { + async updateRole({ request, locals, params }) { + const { allowed } = await canManageProjectRole(locals.user, params.slug, 'stateiac:update'); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.updateRole(String(form.get('id') ?? ''), { + name: String(form.get('name') ?? ''), + permissions: parsePermissions(form.get('permissions')), + }); + return { success: true, role }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, + + async deleteRole({ request, locals, params }) { + const { allowed } = await canManageProjectRole(locals.user, params.slug, 'stateiac:delete'); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + await roleService.deleteRole(String(form.get('id') ?? '')); + return { success: true }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/[id]/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/[id]/+page.svelte new file mode 100644 index 00000000..a814b73d --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/[id]/+page.svelte @@ -0,0 +1,17 @@ + + + diff --git a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/new/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/new/+page.server.ts new file mode 100644 index 00000000..fd66f128 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/new/+page.server.ts @@ -0,0 +1,60 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../../../../../modules/auth'; +import { projectService } from '../../../../../../../../modules/projects'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(errorValue: unknown) { + return fail(400, { + error: errorValue instanceof Error ? errorValue.message : 'Role action failed.', + }); +} + +async function canManageProjectRole( + user: Parameters[0], + projectSlug: string, + permission: 'stateiac:create' | 'stateiac:update' | 'stateiac:delete', +) { + const project = await projectService.getProjectBySlug(projectSlug); + const allowed = await cancanService.canSessionUser(user, permission, { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + return { project, allowed }; +} + +export async function load({ parent }) { + const { project } = await parent(); + return { project }; +} + +export const actions = { + async createRole({ request, locals, params }) { + const { project, allowed } = await canManageProjectRole( + locals.user, + params.slug, + 'stateiac:create', + ); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const role = await roleService.createRole({ + name: String(form.get('name') ?? ''), + slug: String(form.get('slug') ?? ''), + permissions: parsePermissions(form.get('permissions')), + scope: 'project', + projectId: project.id, + }); + return { success: true, role }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/new/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/new/+page.svelte new file mode 100644 index 00000000..0048aa96 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/roles-permissions/new/+page.svelte @@ -0,0 +1,9 @@ + + + diff --git a/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.server.ts new file mode 100644 index 00000000..46855339 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.server.ts @@ -0,0 +1,99 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService, userAccessService } from '../../../../../../../modules/auth'; +import { projectService } from '../../../../../../../modules/projects'; + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'User action failed.' }); +} + +async function canUpdateProjectUsers(user: App.Locals['user'], projectSlug: string) { + const project = await projectService.getProjectBySlug(projectSlug); + const allowed = await cancanService.canSessionUser(user, 'stateiac:update', { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }); + return { project, allowed }; +} + +export async function load({ parent }) { + const { project } = await parent(); + const [users, roles, assignableUsers] = await Promise.all([ + userAccessService.listUsers('project', project.id), + roleService.listRoles('project', project.id), + userAccessService.listAssignableUsers(), + ]); + return { project, users, roles, assignableUsers }; +} + +export const actions = { + async addUser({ request, locals, params }) { + const { project, allowed } = await canUpdateProjectUsers(locals.user, params.slug); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const user = await userAccessService.assignProjectUser({ + projectId: project.id, + userId: String(form.get('userId') ?? ''), + roleId: String(form.get('roleId') ?? ''), + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async updateUserAccess({ request, locals, params }) { + const { project, allowed } = await canUpdateProjectUsers(locals.user, params.slug); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const user = await userAccessService.updateAccess({ + accessId: String(form.get('accessId') ?? ''), + scope: 'project', + scopeId: project.id, + roleId: String(form.get('roleId') ?? ''), + status: String(form.get('status') ?? ''), + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async removeUserAccess({ request, locals, params }) { + const { project, allowed } = await canUpdateProjectUsers(locals.user, params.slug); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + await userAccessService.removeAccess({ + accessId: String(form.get('accessId') ?? ''), + scope: 'project', + scopeId: project.id, + }); + return { success: true }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async resendInvitation({ request, locals, params }) { + const { project, allowed } = await canUpdateProjectUsers(locals.user, params.slug); + if (!allowed) return fail(403, { error: 'Forbidden' }); + + try { + const form = await request.formData(); + const user = await userAccessService.resendInvitation({ + accessId: String(form.get('accessId') ?? ''), + scope: 'project', + scopeId: project.id, + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.svelte index ab8313fa..023b75e3 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/users-groups/+page.svelte @@ -1,26 +1,19 @@ - - - Usuarios y Grupos - Projects - + import Users from '$lib/components/Users.svelte'; -
-
-

Usuarios y Grupos

-

- Gestiona qué usuarios y grupos tienen acceso a cada proyecto. -

-
+ export let data: { + users: any[]; + roles: any[]; + assignableUsers: any[]; + project: { name: string }; + }; + -
- -

Próximamente

-

- La gestión de usuarios y grupos por proyecto todavía no está disponible. -

-
-
+ diff --git a/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte b/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte index 1e7bf079..e4e1497e 100644 --- a/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte @@ -1,9 +1,8 @@ diff --git a/src/routes/org/[org]/projects/[slug]/vault/+page.svelte b/src/routes/org/[org]/projects/[slug]/vault/+page.svelte index 0e3fe4e8..4dd052e0 100644 --- a/src/routes/org/[org]/projects/[slug]/vault/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/vault/+page.svelte @@ -1,9 +1,8 @@ diff --git a/src/routes/settings/+layout.svelte b/src/routes/org/[org]/settings/+layout.svelte similarity index 65% rename from src/routes/settings/+layout.svelte rename to src/routes/org/[org]/settings/+layout.svelte index 2fbf1b7d..bd5c5e07 100644 --- a/src/routes/settings/+layout.svelte +++ b/src/routes/org/[org]/settings/+layout.svelte @@ -2,8 +2,8 @@ Settings - GitVault Suite -
-
+
+

Settings

diff --git a/src/routes/org/[org]/settings/+page.server.ts b/src/routes/org/[org]/settings/+page.server.ts new file mode 100644 index 00000000..4047b00b --- /dev/null +++ b/src/routes/org/[org]/settings/+page.server.ts @@ -0,0 +1,5 @@ +import { redirect } from '@sveltejs/kit'; + +export function load({ params }) { + throw redirect(302, `/org/${params.org}/settings/global`); +} diff --git a/src/routes/org/[org]/settings/global/+page.svelte b/src/routes/org/[org]/settings/global/+page.svelte new file mode 100644 index 00000000..dbc591f4 --- /dev/null +++ b/src/routes/org/[org]/settings/global/+page.svelte @@ -0,0 +1,279 @@ + + + + Global Settings - Settings + + +
+
+

Global Settings

+

+ Configure organization-wide authentication methods and security defaults. +

+
+ +
+
+

Authentication

+

+ Local login is always enabled. Optionally connect GCP Workspace and SAML as additional + providers. +

+
+ +
+
+ +
+

Local authentication: always ON

+

+ Username/password access remains available even when external providers are enabled. +

+
+
+
+ +
+
+ +
+ +

+ Allow users to authenticate with Google Workspace accounts. +

+
+
+ + {#if googleSsoEnabled} +
+
+ + +
+ +
+ + +
+
+ {/if} +
+ +
+
+ +
+ +

+ Connect an enterprise identity provider through SAML. +

+
+
+ + {#if samlEnabled} +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ {/if} +
+ + {#if configError} +
+ {configError} +
+ {/if} + + {#if saveSuccess} +
+ + Global settings saved. + +
+ {/if} + + +
+ +
+
+

Encryption

+

+ Organization encryption controls will be managed here. +

+
+ +
+
+
+ +
+
+

Coming soon

+

+ Key rotation, encryption policy, and scoped secret protection settings are planned for a + future release. +

+
+
+
+
+
diff --git a/src/routes/org/[org]/settings/projects/+page.server.ts b/src/routes/org/[org]/settings/projects/+page.server.ts new file mode 100644 index 00000000..4e61edf5 --- /dev/null +++ b/src/routes/org/[org]/settings/projects/+page.server.ts @@ -0,0 +1,7 @@ +import { organizationService } from '../../../../../modules/organization'; + +export async function load({ params }) { + const organization = await organizationService.findBySlug(params.org); + return { organization }; +} + diff --git a/src/routes/settings/projects/+page.svelte b/src/routes/org/[org]/settings/projects/+page.svelte similarity index 95% rename from src/routes/settings/projects/+page.svelte rename to src/routes/org/[org]/settings/projects/+page.svelte index d47cb1af..04783c05 100644 --- a/src/routes/settings/projects/+page.svelte +++ b/src/routes/org/[org]/settings/projects/+page.svelte @@ -2,7 +2,7 @@ import { onMount } from 'svelte'; import { CheckCircle, Eye, FolderKanban, Plus, Search, Trash2 } from 'lucide-svelte'; - export let data: { organization: { slug: string } }; + export let data: { organization: { id: string; slug: string } | null }; type ProjectRow = { id: string; @@ -41,7 +41,11 @@ error = ''; try { - const res = await fetch('/api/projects'); + const organizationId = data.organization?.id; + const url = organizationId + ? `/api/projects?organizationId=${organizationId}` + : '/api/projects'; + const res = await fetch(url); const payload = await res.json(); if (payload.error) throw new Error(payload.error); projects = payload.projects || []; @@ -91,12 +95,18 @@ return; } + if (!data.organization) { + createError = 'No organization selected.'; + return; + } + creating = true; try { const res = await fetch('/api/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + organizationId: data.organization.id, name: newName.trim(), slug: newSlug.trim() || undefined, description: newDescription.trim() || undefined, @@ -269,7 +279,9 @@
diff --git a/src/routes/org/[org]/settings/roles-permissions/+page.server.ts b/src/routes/org/[org]/settings/roles-permissions/+page.server.ts new file mode 100644 index 00000000..56da67a3 --- /dev/null +++ b/src/routes/org/[org]/settings/roles-permissions/+page.server.ts @@ -0,0 +1,76 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../../modules/auth'; +import { organizationService } from '../../../../../modules/organization'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'Role action failed.' }); +} + +export async function load({ parent }) { + const { organization } = await parent(); + const roles = await roleService.listRoles('organization', organization.id); + return { roles }; +} + +export const actions = { + async createRole({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const role = await roleService.createRole({ + name: String(form.get('name') ?? ''), + slug: String(form.get('slug') ?? ''), + permissions: parsePermissions(form.get('permissions')), + scope: 'organization', + organizationId: organization.id, + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async updateRole({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const role = await roleService.updateRole(String(form.get('id') ?? ''), { + name: String(form.get('name') ?? ''), + permissions: parsePermissions(form.get('permissions')), + }); + return { success: true, role }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async deleteRole({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + await roleService.deleteRole(String(form.get('id') ?? '')); + return { success: true }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/org/[org]/settings/roles-permissions/+page.svelte b/src/routes/org/[org]/settings/roles-permissions/+page.svelte new file mode 100644 index 00000000..c1921c1f --- /dev/null +++ b/src/routes/org/[org]/settings/roles-permissions/+page.svelte @@ -0,0 +1,10 @@ + + + diff --git a/src/routes/org/[org]/settings/roles-permissions/[id]/+page.server.ts b/src/routes/org/[org]/settings/roles-permissions/[id]/+page.server.ts new file mode 100644 index 00000000..b3847b15 --- /dev/null +++ b/src/routes/org/[org]/settings/roles-permissions/[id]/+page.server.ts @@ -0,0 +1,59 @@ +import { error, fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../../../modules/auth'; +import { organizationService } from '../../../../../../modules/organization'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(errorValue: unknown) { + return fail(400, { + error: errorValue instanceof Error ? errorValue.message : 'Role action failed.', + }); +} + +export async function load({ parent, params }) { + const { organization } = await parent(); + const roles = await roleService.listRoles('organization', organization.id); + const role = roles.find((row) => row.id === params.id); + if (!role) throw error(404, 'Role not found'); + return { organization, role }; +} + +export const actions = { + async updateRole({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const role = await roleService.updateRole(String(form.get('id') ?? ''), { + name: String(form.get('name') ?? ''), + permissions: parsePermissions(form.get('permissions')), + }); + return { success: true, role }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, + + async deleteRole({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + await roleService.deleteRole(String(form.get('id') ?? '')); + return { success: true }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, +}; diff --git a/src/routes/org/[org]/settings/roles-permissions/[id]/+page.svelte b/src/routes/org/[org]/settings/roles-permissions/[id]/+page.svelte new file mode 100644 index 00000000..983a9525 --- /dev/null +++ b/src/routes/org/[org]/settings/roles-permissions/[id]/+page.svelte @@ -0,0 +1,12 @@ + + + diff --git a/src/routes/org/[org]/settings/roles-permissions/new/+page.server.ts b/src/routes/org/[org]/settings/roles-permissions/new/+page.server.ts new file mode 100644 index 00000000..375fb42b --- /dev/null +++ b/src/routes/org/[org]/settings/roles-permissions/new/+page.server.ts @@ -0,0 +1,44 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService } from '../../../../../../modules/auth'; +import { organizationService } from '../../../../../../modules/organization'; + +function parsePermissions(value: unknown): string[] { + if (typeof value !== 'string') return []; + const permissions = JSON.parse(value) as unknown; + if (!Array.isArray(permissions)) return []; + return permissions.filter((permission): permission is string => typeof permission === 'string'); +} + +function errorResponse(errorValue: unknown) { + return fail(400, { + error: errorValue instanceof Error ? errorValue.message : 'Role action failed.', + }); +} + +export async function load({ parent }) { + const { organization } = await parent(); + return { organization }; +} + +export const actions = { + async createRole({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const role = await roleService.createRole({ + name: String(form.get('name') ?? ''), + slug: String(form.get('slug') ?? ''), + permissions: parsePermissions(form.get('permissions')), + scope: 'organization', + organizationId: organization.id, + }); + return { success: true, role }; + } catch (errorValue: unknown) { + return errorResponse(errorValue); + } + }, +}; diff --git a/src/routes/org/[org]/settings/roles-permissions/new/+page.svelte b/src/routes/org/[org]/settings/roles-permissions/new/+page.svelte new file mode 100644 index 00000000..3fee18d4 --- /dev/null +++ b/src/routes/org/[org]/settings/roles-permissions/new/+page.svelte @@ -0,0 +1,11 @@ + + + diff --git a/src/routes/settings/server-access-keys/+page.svelte b/src/routes/org/[org]/settings/server-access-keys/+page.svelte similarity index 100% rename from src/routes/settings/server-access-keys/+page.svelte rename to src/routes/org/[org]/settings/server-access-keys/+page.svelte diff --git a/src/routes/settings/storage/+page.server.ts b/src/routes/org/[org]/settings/storage/+page.server.ts similarity index 100% rename from src/routes/settings/storage/+page.server.ts rename to src/routes/org/[org]/settings/storage/+page.server.ts diff --git a/src/routes/settings/storage/+page.svelte b/src/routes/org/[org]/settings/storage/+page.svelte similarity index 100% rename from src/routes/settings/storage/+page.svelte rename to src/routes/org/[org]/settings/storage/+page.svelte diff --git a/src/routes/settings/system-backup/+page.svelte b/src/routes/org/[org]/settings/system-backup/+page.svelte similarity index 100% rename from src/routes/settings/system-backup/+page.svelte rename to src/routes/org/[org]/settings/system-backup/+page.svelte diff --git a/src/routes/org/[org]/settings/users/+page.server.ts b/src/routes/org/[org]/settings/users/+page.server.ts new file mode 100644 index 00000000..2f8dd3e4 --- /dev/null +++ b/src/routes/org/[org]/settings/users/+page.server.ts @@ -0,0 +1,98 @@ +import { fail } from '@sveltejs/kit'; +import { cancanService, roleService, userAccessService } from '../../../../../modules/auth'; +import { organizationService } from '../../../../../modules/organization'; + +function errorResponse(error: unknown) { + return fail(400, { error: error instanceof Error ? error.message : 'User action failed.' }); +} + +export async function load({ parent }) { + const { organization } = await parent(); + const [users, roles] = await Promise.all([ + userAccessService.listUsers('organization', organization.id), + roleService.listRoles('organization', organization.id), + ]); + return { users, roles }; +} + +export const actions = { + async addUser({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const user = await userAccessService.createOrganizationUser({ + organizationId: organization.id, + username: String(form.get('username') ?? ''), + email: String(form.get('email') ?? '') || null, + password: String(form.get('password') ?? ''), + roleId: String(form.get('roleId') ?? ''), + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async updateUserAccess({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const user = await userAccessService.updateAccess({ + accessId: String(form.get('accessId') ?? ''), + scope: 'organization', + scopeId: organization.id, + roleId: String(form.get('roleId') ?? ''), + status: String(form.get('status') ?? ''), + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async removeUserAccess({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + await userAccessService.removeAccess({ + accessId: String(form.get('accessId') ?? ''), + scope: 'organization', + scopeId: organization.id, + }); + return { success: true }; + } catch (error: unknown) { + return errorResponse(error); + } + }, + + async resendInvitation({ request, locals, params }) { + const organization = await organizationService.findBySlug(params.org); + if (!(await cancanService.canManageOrganization(locals.user, organization.id))) { + return fail(403, { error: 'Forbidden' }); + } + + try { + const form = await request.formData(); + const user = await userAccessService.resendInvitation({ + accessId: String(form.get('accessId') ?? ''), + scope: 'organization', + scopeId: organization.id, + }); + return { success: true, user }; + } catch (error: unknown) { + return errorResponse(error); + } + }, +}; diff --git a/src/routes/org/[org]/settings/users/+page.svelte b/src/routes/org/[org]/settings/users/+page.svelte new file mode 100644 index 00000000..2a131222 --- /dev/null +++ b/src/routes/org/[org]/settings/users/+page.svelte @@ -0,0 +1,13 @@ + + + diff --git a/src/routes/settings/authentication/+page.svelte b/src/routes/settings/authentication/+page.svelte deleted file mode 100644 index 92785657..00000000 --- a/src/routes/settings/authentication/+page.svelte +++ /dev/null @@ -1,731 +0,0 @@ - - - - Autentication - Settings - - -
-
-

Autentication

-

- Local login is always enabled. Optionally connect GCP Workspace and SAML as additional - providers. -

-
- -
-
- -
-

Local authentication: always ON

-

- Username/password access remains available even when external providers are enabled. -

-
-
-
- -
-
- -
- -

- Allow users to authenticate with Google Workspace accounts. -

-
-
- - {#if googleSsoEnabled} -
-
- - -
- -
- - -
-
- {/if} -
- -
-
- -
- -

- Connect an enterprise identity provider through SAML. -

-
-
- - {#if samlEnabled} -
-
- - -
- -
- - -
- -
- - -
-
- {/if} -
- - {#if configError} -
- {configError} -
- {/if} - - {#if saveSuccess} -
- Authentication settings saved. -
- {/if} - - - -
-
-
-
- -

Local users

-
- -
-
- - -
- - -
-
-
- -
- {#if userError} -
- {userError} -
- {/if} - - {#if userSuccess} -
- {userSuccess} -
- {/if} - - {#if usersLoading} -
- Loading users... -
- {:else if filteredUsers.length === 0} -
- No users found. -
- {:else} -
- {#each filteredUsers as user} -
-
-
-

{user.username}

-

{user.role.name} · created {user.created_at}

-
- -
- - - - - -
-
-
- {/each} -
- {/if} -
-
-
- -{#if createUserModalOpen} - -
- -
-{/if} - -{#if passwordModalUser} - -
- -
-{/if} - -{#if deleteModalUser} - -
- -
-{/if} \ No newline at end of file diff --git a/src/routes/settings/projects/+page.server.ts b/src/routes/settings/projects/+page.server.ts deleted file mode 100644 index e0edc9e8..00000000 --- a/src/routes/settings/projects/+page.server.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { organizationService } from '../../../modules/organization'; - -export async function load() { - const organization = await organizationService.findBySlug('gitops'); - return { organization }; -} diff --git a/src/routes/settings/roles-permissions/+page.svelte b/src/routes/settings/roles-permissions/+page.svelte deleted file mode 100644 index 57b0a53e..00000000 --- a/src/routes/settings/roles-permissions/+page.svelte +++ /dev/null @@ -1,444 +0,0 @@ - - - - Roles & Permissions - Settings - - -
-
-
-

Roles & Permissions

-

- Manage user roles and granular access policies across Vault, Open Report and State IaC. -

-
- - -
- - {#if rolesError} -
- {rolesError} -
- {/if} - - {#if rolesSuccess} -
- {rolesSuccess} -
- {/if} - - {#if rolesLoading} -
- Loading roles... -
- {:else if roles.length === 0} -
- No roles found. -
- {:else} -
- {#each roles as role (role.id)} -
-
-
- -
- -
-
- -
- - - -
-
- -
- - - - - {#each PERMISSION_ACTIONS as action} - - {/each} - - - - - {#each PERMISSION_SECTIONS as section} - - - {#each PERMISSION_ACTIONS as action} - - {/each} - - - {/each} - -
Section{PERMISSION_ACTION_LABELS[action]}All
{PERMISSION_SECTION_LABELS[section]} - onToggleAction(role, section, action)} - class="h-4 w-4 rounded border-slate-300 text-slate-900 focus:ring-slate-400" - /> - - onToggleAll(role, section)} - class="h-4 w-4 rounded border-slate-300 text-slate-900 focus:ring-slate-400" - /> -
-
-
- {/each} -
- {/if} -
- -{#if createModalOpen} - -
- -
-{/if} - -{#if deleteModalRole} - -
- -
-{/if}