mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 19:34:38 +00:00
refactor: extract core service domain layer to @shumai/core
This commit is contained in:
@@ -0,0 +1,400 @@
|
||||
import { setupTestDbHooks } from '@shumai/db'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { prisma } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
describe('AuthzService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('should test authorization permissions correctly', async () => {
|
||||
// Setup Data
|
||||
// Users
|
||||
const userOwner = await prisma.user.create({
|
||||
data: { name: 'owner', email: 'owner@example.com', password: 'pass' },
|
||||
})
|
||||
const userEditor = await prisma.user.create({
|
||||
data: { name: 'editor', email: 'editor@example.com', password: 'pass' },
|
||||
})
|
||||
const userReviewer = await prisma.user.create({
|
||||
data: { name: 'reviewer', email: 'reviewer@example.com', password: 'pass' },
|
||||
})
|
||||
const userOther = await prisma.user.create({
|
||||
data: { name: 'other', email: 'other@example.com', password: 'pass' },
|
||||
})
|
||||
|
||||
// Team
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Team A' },
|
||||
})
|
||||
|
||||
// Memberships
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userOwner.id, role: 'owner' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userEditor.id, role: 'editor' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userReviewer.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Project & Asset
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project A', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'File A',
|
||||
projectId: project.id,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
},
|
||||
})
|
||||
|
||||
// Collection
|
||||
const collection = await prisma.collection.create({
|
||||
data: {
|
||||
name: 'Collection A',
|
||||
projectId: project.id,
|
||||
filter: {
|
||||
sourceFolderId: 'root',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Project Scope User
|
||||
const userProjectEditor = await prisma.user.create({
|
||||
data: { name: 'p_editor', email: 'p_editor@example.com', password: 'pass' },
|
||||
})
|
||||
const tmPe = await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: userProjectEditor.id,
|
||||
role: 'reviewer',
|
||||
scope: 'project',
|
||||
},
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: tmPe.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const tests = [
|
||||
{
|
||||
name: 'Owner can Admin Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userOwner,
|
||||
permission: Permission.Admin,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Editor cannot Admin Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userEditor,
|
||||
permission: Permission.Admin,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: 'Editor can Edit Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userEditor,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Reviewer cannot Edit Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userReviewer,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: 'Reviewer can Read Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userReviewer,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Non-member cannot Read Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userOther,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
wantErr: true,
|
||||
errMessage: 'is not a member of the team',
|
||||
},
|
||||
{
|
||||
name: 'Project Editor can Edit Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Project Editor cannot Admin Project',
|
||||
req: {
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Admin,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: 'Project Scope User can Read Team',
|
||||
req: {
|
||||
type: ResourceType.Team,
|
||||
id: team.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Project Scope User cannot Edit Team',
|
||||
req: {
|
||||
type: ResourceType.Team,
|
||||
id: team.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: true,
|
||||
errMessage: 'User has only project scope',
|
||||
},
|
||||
{
|
||||
name: 'Resolve Context from Asset',
|
||||
req: {
|
||||
type: ResourceType.Asset,
|
||||
id: asset.id,
|
||||
user: userOwner,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Resolve Context from Collection',
|
||||
req: {
|
||||
type: ResourceType.Collection,
|
||||
id: collection.id,
|
||||
user: userOwner,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Asset Not Found',
|
||||
req: {
|
||||
type: ResourceType.Asset,
|
||||
id: '01HJXXW6A61234567890ABCDEF',
|
||||
user: userOwner,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
wantErr: true,
|
||||
errMessage: 'Asset not found',
|
||||
},
|
||||
]
|
||||
|
||||
for (const tt of tests) {
|
||||
if (tt.wantErr) {
|
||||
let err
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await authzService.hasPermission(tt.req as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
err = e
|
||||
}
|
||||
expect(err, tt.name).toBeDefined()
|
||||
if (tt.errMessage) {
|
||||
expect(err.message).include(tt.errMessage)
|
||||
}
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await expect(authzService.hasPermission(tt.req as any), tt.name).resolves.toBeUndefined()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('should resolve context correctly for each ResourceType', async () => {
|
||||
// Setup complete data graph for all types
|
||||
const team = await prisma.team.create({ data: { name: 'Team X' } })
|
||||
const project = await prisma.project.create({ data: { name: 'Project X', teamId: team.id } })
|
||||
|
||||
// Asset (Project-scoped)
|
||||
const assetProject = await prisma.asset.create({
|
||||
data: { name: 'Asset P', projectId: project.id, type: 'file', status: 'processed' },
|
||||
})
|
||||
|
||||
// Asset (Team-scoped root folder fallback)
|
||||
const assetTeam = await prisma.asset.create({
|
||||
data: { name: 'Team Root', type: 'root', status: 'processed' },
|
||||
})
|
||||
await prisma.team.update({
|
||||
where: { id: team.id },
|
||||
data: { rootFolderId: assetTeam.id },
|
||||
})
|
||||
|
||||
// Collection
|
||||
const collection = await prisma.collection.create({
|
||||
data: {
|
||||
name: 'Coll',
|
||||
projectId: project.id,
|
||||
filter: {
|
||||
sourceFolderId: 'root',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Agent & Session
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'BotUser2', email: 'bot2@example.com', password: 'p' },
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
config: { provider: 'openai', model: 'gpt-4o' },
|
||||
},
|
||||
})
|
||||
const agentSession = await prisma.agentSession.create({
|
||||
data: { agentId: agent.id, cwd: '/tmp' },
|
||||
})
|
||||
|
||||
// Share
|
||||
const share = await prisma.shareLink.create({
|
||||
data: { name: 'Share1', rootFolderId: assetProject.id, projectId: project.id },
|
||||
})
|
||||
|
||||
// Metadata Field
|
||||
const teamField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'field_t',
|
||||
scope: 'TEAM',
|
||||
teamId: team.id,
|
||||
config: { name: 'Field T', type: 'text' },
|
||||
},
|
||||
})
|
||||
const projectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'field_p',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
config: { name: 'Field P', type: 'text' },
|
||||
},
|
||||
})
|
||||
|
||||
// Skill
|
||||
const skill = await prisma.skill.create({
|
||||
data: { name: 'Skill 1', teamId: team.id, hash: '123', assetId: assetProject.id },
|
||||
})
|
||||
|
||||
// Provider
|
||||
const provider = await prisma.provider.create({
|
||||
data: { name: 'Prov 1', teamId: team.id, config: { api: 'openai' } },
|
||||
})
|
||||
|
||||
// Invite
|
||||
const inviteTeam = await prisma.invite.create({
|
||||
data: { code: 'inv_t', teamId: team.id, role: 'editor', inviterId: user.id },
|
||||
})
|
||||
const inviteProject = await prisma.invite.create({
|
||||
data: {
|
||||
code: 'inv_p',
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
role: 'editor',
|
||||
inviterId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Comment
|
||||
const comment = await prisma.assetComment.create({
|
||||
data: { assetId: assetProject.id, creatorId: user.id, message: 'hello' },
|
||||
})
|
||||
|
||||
// Test execution via cast
|
||||
const resolveContext = (type: ResourceType, id: string) =>
|
||||
(
|
||||
authzService as unknown as {
|
||||
resolveContext: (
|
||||
type: ResourceType,
|
||||
id: string,
|
||||
) => Promise<{ teamId: string; projectId?: string }>
|
||||
}
|
||||
).resolveContext(type, id)
|
||||
|
||||
// Tests
|
||||
await expect(resolveContext(ResourceType.Team, team.id)).resolves.toEqual({ teamId: team.id })
|
||||
await expect(resolveContext(ResourceType.Project, project.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Asset, assetProject.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Asset, assetTeam.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Collection, collection.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Agent, agent.id)).resolves.toEqual({ teamId: team.id })
|
||||
await expect(resolveContext(ResourceType.AgentSession, agentSession.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Share, share.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.MetadataField, teamField.key)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.MetadataField, projectField.key)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Skill, skill.id)).resolves.toEqual({ teamId: team.id })
|
||||
await expect(resolveContext(ResourceType.Provider, provider.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Invite, inviteTeam.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: undefined,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Invite, inviteProject.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
await expect(resolveContext(ResourceType.Comment, comment.id)).resolves.toEqual({
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export enum Permission {
|
||||
Read = 'Read',
|
||||
Edit = 'Edit',
|
||||
Admin = 'Admin',
|
||||
}
|
||||
|
||||
export enum ResourceType {
|
||||
Team = 'team',
|
||||
Project = 'project',
|
||||
Asset = 'asset',
|
||||
Collection = 'collection',
|
||||
Agent = 'agent',
|
||||
Share = 'share',
|
||||
MetadataField = 'metadataField',
|
||||
Skill = 'skill',
|
||||
Provider = 'provider',
|
||||
Invite = 'invite',
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
}
|
||||
|
||||
export interface AuthzRequest {
|
||||
user: User
|
||||
permission: Permission
|
||||
type: ResourceType
|
||||
id: string
|
||||
}
|
||||
|
||||
export class AuthzService {
|
||||
async hasPermission(req: AuthzRequest): Promise<void> {
|
||||
if (!req.user) throw new Error('User is required')
|
||||
|
||||
const { teamId, projectId } = await this.resolveContext(req.type, req.id)
|
||||
|
||||
// 1. Check Team Membership
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: teamId,
|
||||
userId: req.user.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new Error('User is not a member of the team')
|
||||
|
||||
// 2. Check Scope
|
||||
if (member.scope === 'team') {
|
||||
return this.checkRole(member.role, req.permission)
|
||||
}
|
||||
|
||||
// 3. Scope is Project
|
||||
if (!projectId) {
|
||||
// User has project scope but no project context provided (e.g. Team-level resource)
|
||||
// If it's a team-level resource, project-scoped users shouldn't have access except for Read maybe?
|
||||
// But usually team resources like Skills/Providers are managed by Team Owners/Editors.
|
||||
// For now, let's keep the logic: project-scoped users can't access team-level resources unless it's Read (like ListProjects).
|
||||
if (req.permission === Permission.Read) {
|
||||
return
|
||||
}
|
||||
throw new Error('User has only project scope')
|
||||
}
|
||||
|
||||
// Check Project Membership
|
||||
const pm = await prisma.projectMember.findUnique({
|
||||
where: {
|
||||
projectIdTeamMemberId: {
|
||||
projectId: projectId,
|
||||
teamMemberId: member.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!pm) throw new Error(`User is not a member of project ${projectId}`)
|
||||
|
||||
return this.checkRole(pm.role, req.permission)
|
||||
}
|
||||
|
||||
private async resolveContext(
|
||||
type: ResourceType,
|
||||
id: string,
|
||||
): Promise<{ teamId: string; projectId?: string }> {
|
||||
switch (type) {
|
||||
case ResourceType.Team:
|
||||
return { teamId: id }
|
||||
|
||||
case ResourceType.Project: {
|
||||
const proj = await prisma.project.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!proj) throw new Error('Project not found')
|
||||
return { teamId: proj.teamId, projectId: id }
|
||||
}
|
||||
|
||||
case ResourceType.Asset: {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
parentId: true,
|
||||
teamRootFolder: { select: { id: true } },
|
||||
project: { select: { id: true, teamId: true } },
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.project) {
|
||||
return { teamId: asset.project.teamId, projectId: asset.project.id }
|
||||
}
|
||||
if (asset.teamRootFolder) {
|
||||
return { teamId: asset.teamRootFolder.id }
|
||||
}
|
||||
if (asset.parentId) {
|
||||
// If it's a nested asset, we might need recursive lookup.
|
||||
// However, in this project, assets typically have projectId if they are in a project.
|
||||
// If parentId is set but no project, it might be in a team root folder.
|
||||
// For now, let's try to get context from parent.
|
||||
return this.resolveContext(ResourceType.Asset, asset.parentId)
|
||||
}
|
||||
throw new Error('Could not resolve context for asset')
|
||||
}
|
||||
|
||||
case ResourceType.Collection: {
|
||||
const coll = await prisma.collection.findUnique({
|
||||
where: { id },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!coll) throw new Error('Collection not found')
|
||||
return { teamId: coll.project.teamId, projectId: coll.projectId }
|
||||
}
|
||||
|
||||
case ResourceType.Agent: {
|
||||
const agent = await prisma.agent.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!agent) throw new Error('Agent not found')
|
||||
return { teamId: agent.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.AgentSession: {
|
||||
const session = await prisma.agentSession.findUnique({
|
||||
where: { id },
|
||||
include: { agent: true },
|
||||
})
|
||||
if (!session) throw new Error('Agent session not found')
|
||||
return { teamId: session.agent.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Share: {
|
||||
const share = await prisma.shareLink.findUnique({
|
||||
where: { id },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!share) throw new Error('Share not found')
|
||||
return { teamId: share.project.teamId, projectId: share.projectId }
|
||||
}
|
||||
|
||||
case ResourceType.MetadataField: {
|
||||
const field = await prisma.metadataField.findUnique({
|
||||
where: { key: id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!field) throw new Error('Metadata field not found')
|
||||
if (field.projectId) {
|
||||
const proj = await prisma.project.findUnique({
|
||||
where: { id: field.projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
return { teamId: proj!.teamId, projectId: field.projectId }
|
||||
}
|
||||
if (!field.teamId) throw new Error('Metadata field has no context')
|
||||
return { teamId: field.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Skill: {
|
||||
const skill = await prisma.skill.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!skill) throw new Error('Skill not found')
|
||||
return { teamId: skill.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Provider: {
|
||||
const provider = await prisma.provider.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!provider) throw new Error('Provider not found')
|
||||
return { teamId: provider.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Invite: {
|
||||
const invite = await prisma.invite.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!invite) throw new Error('Invite not found')
|
||||
return { teamId: invite.teamId, projectId: invite.projectId ?? undefined }
|
||||
}
|
||||
|
||||
case ResourceType.Comment: {
|
||||
const comment = await prisma.assetComment.findUnique({
|
||||
where: { id },
|
||||
include: { asset: { include: { project: true } } },
|
||||
})
|
||||
if (!comment) throw new Error('Comment not found')
|
||||
if (!comment.asset.project) throw new Error('Comment asset has no project')
|
||||
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported resource type: ${type}`)
|
||||
}
|
||||
}
|
||||
|
||||
private checkRole(role: string, permission: Permission): void {
|
||||
switch (permission) {
|
||||
case Permission.Read:
|
||||
return
|
||||
case Permission.Edit:
|
||||
if (role === 'owner' || role === 'editor') return
|
||||
break
|
||||
case Permission.Admin:
|
||||
if (role === 'owner') return
|
||||
break
|
||||
}
|
||||
throw new Error('Permission denied')
|
||||
}
|
||||
}
|
||||
|
||||
export const authzService = new AuthzService()
|
||||
Reference in New Issue
Block a user