Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { PolicyDefinition, PolicyAssignment, FieldPolicy, PermissionEvaluationLog, } from './schemas/permission.schema'; import { User } from '../user/schemas/user.schema'; @Injectable() export class PermissionEvaluationService { private readonly logger = new Logger(PermissionEvaluationService.name); private readonly cache = new Map< string, { decision: 'ALLOW' | 'DENY'; expiry: number } >(); constructor( @InjectModel(PolicyDefinition.name) private readonly policyModel: Model<PolicyDefinition>, @InjectModel(PolicyAssignment.name) private readonly assignmentModel: Model<PolicyAssignment>, @InjectModel(FieldPolicy.name) private readonly fieldPolicyModel: Model<FieldPolicy>, @InjectModel(PermissionEvaluationLog.name) private readonly logModel: Model<PermissionEvaluationLog>, @InjectModel(User.name) private readonly userModel: Model<User>, ) {} async evaluate(params: { tenantId: string; userId: string; resource: string; action: string; context?: any; }): Promise<{ decision: 'ALLOW' | 'DENY'; dataScope?: string; reason?: string; }> { const cacheKey = `${params.tenantId}:${params.userId}:${params.resource}:${params.action}`; const cached = this.cache.get(cacheKey); if (cached && cached.expiry > Date.now()) { return { decision: cached.decision, reason: 'CACHED' }; } const user = await this.userModel.findById(params.userId).lean().exec(); if (!user) { return { decision: 'DENY', reason: 'User not found' }; } // Resolve direct and role policy assignments const assignments = await this.assignmentModel .find({ tenantId: params.tenantId, $or: [{ userId: params.userId }, { roleId: { $in: user.roles || [] } }], }) .lean() .exec(); const policyIds = assignments.map((a) => a.policyId); const policies = await this.policyModel .find({ _id: { $in: policyIds }, tenantId: params.tenantId, }) .sort({ priority: -1 }) .lean() .exec(); let decision: 'ALLOW' | 'DENY' = 'DENY'; let activeDataScope: string | undefined = undefined; let matchFound = false; // Deny-overrides logic: Loop statements in order of priority for (const policy of policies) { for (const statement of policy.statements) { const actionMatch = statement.actions.includes('*') || statement.actions.includes(params.action); const resourceMatch = statement.resources.includes('*') || statement.resources.includes(params.resource); if (actionMatch && resourceMatch) { if (statement.effect === 'DENY') { // Explicit deny always overrides everything await this.logDecision( params.tenantId, params.userId, params.resource, params.action, 'DENY', `Explicit Deny by policy: ${policy.name}`, ); this.cache.set(cacheKey, { decision: 'DENY', expiry: Date.now() + 10000, }); // cache 10s return { decision: 'DENY', reason: `Explicit Deny by policy: ${policy.name}`, }; } if (statement.effect === 'ALLOW') { decision = 'ALLOW'; activeDataScope = statement.dataScope || activeDataScope; matchFound = true; } } } } const finalDecision = matchFound ? decision : 'DENY'; const reason = matchFound ? 'Match policies ALLOW' : 'No matching statements found'; await this.logDecision( params.tenantId, params.userId, params.resource, params.action, finalDecision, reason, ); this.cache.set(cacheKey, { decision: finalDecision, expiry: Date.now() + 10000, }); return { decision: finalDecision, dataScope: activeDataScope, reason }; } async getEvaluationLogs(tenantId: string): Promise<any[]> { return this.logModel .find({ tenantId }) .sort({ createdAt: -1 }) .limit(100) .lean() .exec(); } async createPolicy(params: { tenantId: string; name: string; description?: string; statements: any[]; priority?: number; }): Promise<any> { return this.policyModel.create(params); } async getPolicies(tenantId: string): Promise<any[]> { return this.policyModel.find({ tenantId }).lean().exec(); } async getPolicy(id: string, tenantId: string): Promise<any> { return this.policyModel.findOne({ _id: id, tenantId }).lean().exec(); } async deletePolicy(id: string, tenantId: string): Promise<any> { await this.assignmentModel.deleteMany({ policyId: id, tenantId }).exec(); return this.policyModel.deleteOne({ _id: id, tenantId }).exec(); } // ============================================================ // FIELD LEVEL FILTERING // ============================================================ async filterFields(params: { tenantId: string; userId: string; entity: string; data: any; }): Promise<any> { if (!params.data) return params.data; const user = await this.userModel.findById(params.userId).lean().exec(); if (!user) return params.data; const policies = await this.fieldPolicyModel .find({ tenantId: params.tenantId, roleId: { $in: user.roles || [] }, entity: params.entity, }) .lean() .exec(); if (!policies.length) return params.data; const result = Array.isArray(params.data) ? [...params.data] : { ...params.data }; const cleanObject = (obj: any) => { const copy = { ...obj }; for (const p of policies) { if (p.access === 'HIDE') { delete copy[p.field]; } } return copy; }; if (Array.isArray(result)) { return result.map(cleanObject); } return cleanObject(result); } private async logDecision( tenantId: string, userId: string, resource: string, action: string, decision: 'ALLOW' | 'DENY', reason: string, ) { this.logModel .create({ tenantId, userId, resource, action, decision, reason, }) .catch((err) => this.logger.error('Failed logging permission evaluation', err), ); } } @Injectable() export class QueryScopeService { constructor( private readonly permissionService: PermissionEvaluationService, ) {} async injectScope(params: { tenantId: string; userId: string; resource: string; action: string; }): Promise<any> { const evaluation = await this.permissionService.evaluate(params); if (evaluation.decision === 'DENY') { return { _id: '__BLOCKED__' }; // Return unmatchable query to block fetching } const query: any = { tenantId: params.tenantId }; if (evaluation.dataScope === 'OWN') { query.ownerId = params.userId; } else if (evaluation.dataScope === 'CREATED') { query.createdBy = params.userId; } return query; } } |