| | | 1 | | using System.Collections.ObjectModel; |
| | | 2 | | using AsiBackbone.Core.Constraints; |
| | | 3 | | using AsiBackbone.Core.Decisions; |
| | | 4 | | using AsiBackbone.Core.Results; |
| | | 5 | | using AsiBackbone.Core.ThreatModeling; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace AsiBackbone.Core.Evaluation; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Default policy evaluator that runs the active constraint structure and composes the result into a governance decisio |
| | | 12 | | /// </summary> |
| | | 13 | | /// <typeparam name="TContext">The framework-neutral evaluation context type.</typeparam> |
| | | 14 | | public sealed class DefaultGovernancePolicyEvaluator<TContext> : IGovernancePolicyEvaluator<TContext> |
| | | 15 | | where TContext : IGovernanceEvaluationContext |
| | | 16 | | { |
| | 17 | 17 | | private static readonly IReadOnlyList<ConstraintEvaluationResult> EmptyConstraintResults = |
| | 17 | 18 | | Array.AsReadOnly(Array.Empty<ConstraintEvaluationResult>()); |
| | | 19 | | |
| | | 20 | | private const string InvalidAllowedThreatOutcomeMessage = |
| | | 21 | | "Threat model contributors cannot return an Allowed outcome. Use ThreatAssessment.NoThreat() for no finding, or |
| | | 22 | | |
| | 17 | 23 | | private static readonly Action<ILogger, string, string, string, Exception?> EmptyPolicyAllowedWarning = |
| | 17 | 24 | | LoggerMessage.Define<string, string, string>( |
| | 17 | 25 | | LogLevel.Warning, |
| | 17 | 26 | | new EventId(4110, nameof(EmptyPolicyAllowedWarning)), |
| | 17 | 27 | | "Policy evaluation ran with zero constraints while DenyWhenNoConstraints is false; default empty-policy beha |
| | | 28 | | |
| | 17 | 29 | | private static readonly Action<ILogger, string, string, string, string, string, Exception?> ConstraintExceptionDenie |
| | 17 | 30 | | LoggerMessage.Define<string, string, string, string, string>( |
| | 17 | 31 | | LogLevel.Error, |
| | 17 | 32 | | new EventId(4120, nameof(ConstraintExceptionDeniedError)), |
| | 17 | 33 | | "Policy constraint '{ConstraintName}' threw during evaluation and was converted to a denied governance decis |
| | | 34 | | |
| | 17 | 35 | | private static readonly Action<ILogger, string, string, string, string, string, Exception?> ThreatContributorExcepti |
| | 17 | 36 | | LoggerMessage.Define<string, string, string, string, string>( |
| | 17 | 37 | | LogLevel.Error, |
| | 17 | 38 | | new EventId(4130, nameof(ThreatContributorExceptionDeniedError)), |
| | 17 | 39 | | "Threat model contributor '{ContributorName}' threw during evaluation and was converted to a denied governan |
| | | 40 | | |
| | | 41 | | private readonly IGovernanceConstraint<TContext>[] constraints; |
| | | 42 | | private readonly IThreatModelContributor<TContext>[] threatModelContributors; |
| | | 43 | | private readonly IGovernanceDecisionPolicy<TContext>? decisionPolicy; |
| | | 44 | | private readonly ILogger<DefaultGovernancePolicyEvaluator<TContext>>? logger; |
| | | 45 | | private readonly GovernancePolicyOptions options; |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Initializes a new instance of the <see cref="DefaultGovernancePolicyEvaluator{TContext}" /> class. |
| | | 49 | | /// </summary> |
| | | 50 | | /// <param name="constraints">The constraints that make up the active policy structure.</param> |
| | | 51 | | /// <param name="threatModelContributors">Threat model contributors that inspect the context before constraint compo |
| | | 52 | | /// <param name="decisionPolicy">Optional decision policy applied after composition.</param> |
| | | 53 | | /// <param name="options">Evaluator options applied during composition.</param> |
| | | 54 | | /// <param name="logger">Optional logger used to emit operational warning signals.</param> |
| | 156 | 55 | | public DefaultGovernancePolicyEvaluator( |
| | 156 | 56 | | IEnumerable<IGovernanceConstraint<TContext>> constraints, |
| | 156 | 57 | | IEnumerable<IThreatModelContributor<TContext>>? threatModelContributors, |
| | 156 | 58 | | IGovernanceDecisionPolicy<TContext>? decisionPolicy, |
| | 156 | 59 | | GovernancePolicyOptions? options, |
| | 156 | 60 | | ILogger<DefaultGovernancePolicyEvaluator<TContext>>? logger) |
| | | 61 | | { |
| | 156 | 62 | | ArgumentNullException.ThrowIfNull(constraints); |
| | | 63 | | |
| | | 64 | | // Keep exact-sized private snapshots rather than wrapping caller-owned lists. |
| | | 65 | | // This avoids per-evaluator ReadOnlyCollection<T> wrappers and prevents later caller mutations |
| | | 66 | | // from changing deterministic constraint/contributor order or behavior. |
| | 155 | 67 | | this.constraints = [.. constraints]; |
| | 155 | 68 | | this.threatModelContributors = threatModelContributors is null ? [] : [.. threatModelContributors]; |
| | 155 | 69 | | this.decisionPolicy = decisionPolicy; |
| | 155 | 70 | | this.logger = logger; |
| | 155 | 71 | | this.options = options ?? new GovernancePolicyOptions(); |
| | 155 | 72 | | this.options.Validate(); |
| | 143 | 73 | | } |
| | | 74 | | |
| | | 75 | | /// <inheritdoc /> |
| | | 76 | | public async ValueTask<GovernanceDecision> EvaluateAsync( |
| | | 77 | | TContext context, |
| | | 78 | | CancellationToken cancellationToken = default) |
| | | 79 | | { |
| | 206 | 80 | | ArgumentNullException.ThrowIfNull(context); |
| | 205 | 81 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 82 | | |
| | 203 | 83 | | ThreatEvaluationResult threatEvaluation = await EvaluateThreatModelContributorsAsync( |
| | 203 | 84 | | context, |
| | 203 | 85 | | cancellationToken) |
| | 203 | 86 | | .ConfigureAwait(false); |
| | | 87 | | |
| | 193 | 88 | | if (threatEvaluation.BlockingDecision is GovernanceDecision threatDecision) |
| | | 89 | | { |
| | 37 | 90 | | return await ApplyDecisionPolicyAsync( |
| | 37 | 91 | | context, |
| | 37 | 92 | | threatDecision, |
| | 37 | 93 | | EmptyConstraintResults, |
| | 37 | 94 | | protectedThreatDecision: threatDecision, |
| | 37 | 95 | | cancellationToken) |
| | 37 | 96 | | .ConfigureAwait(false); |
| | | 97 | | } |
| | | 98 | | |
| | 156 | 99 | | if (constraints.Length == 0) |
| | | 100 | | { |
| | 13 | 101 | | return await EvaluateEmptyPolicyAsync( |
| | 13 | 102 | | context, |
| | 13 | 103 | | threatEvaluation.WarningReasons, |
| | 13 | 104 | | cancellationToken) |
| | 13 | 105 | | .ConfigureAwait(false); |
| | | 106 | | } |
| | | 107 | | |
| | 143 | 108 | | List<ConstraintEvaluationResult>? results = CreateConstraintResultsBuffer(); |
| | 143 | 109 | | var denials = new OperationReasonAccumulator(); |
| | 143 | 110 | | var warnings = new OperationReasonAccumulator(); |
| | 143 | 111 | | warnings.AddRange(threatEvaluation.WarningReasons); |
| | | 112 | | |
| | 786 | 113 | | foreach (IGovernanceConstraint<TContext> constraint in constraints) |
| | | 114 | | { |
| | 265 | 115 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 116 | | |
| | | 117 | | ConstraintEvaluationResult result; |
| | | 118 | | try |
| | | 119 | | { |
| | 264 | 120 | | result = await constraint |
| | 264 | 121 | | .EvaluateAsync(context, cancellationToken) |
| | 264 | 122 | | .ConfigureAwait(false); |
| | 246 | 123 | | } |
| | 18 | 124 | | catch (Exception exception) when (ShouldConvertExceptionToDenial(exception, options.TreatConstraintException |
| | | 125 | | { |
| | 8 | 126 | | return await CreateConstraintExceptionDecisionAsync( |
| | 8 | 127 | | context, |
| | 8 | 128 | | constraint, |
| | 8 | 129 | | results, |
| | 8 | 130 | | exception, |
| | 8 | 131 | | cancellationToken) |
| | 8 | 132 | | .ConfigureAwait(false); |
| | | 133 | | } |
| | | 134 | | |
| | 246 | 135 | | results?.Add(result); |
| | | 136 | | |
| | 246 | 137 | | if (!AccumulateConstraintResult( |
| | 246 | 138 | | result, |
| | 246 | 139 | | ref denials, |
| | 246 | 140 | | ref warnings, |
| | 246 | 141 | | options.ShortCircuitOnFirstDenial)) |
| | | 142 | | { |
| | | 143 | | break; |
| | | 144 | | } |
| | 235 | 145 | | } |
| | | 146 | | |
| | 124 | 147 | | GovernanceDecision composedDecision = Compose( |
| | 124 | 148 | | context, |
| | 124 | 149 | | denials, |
| | 124 | 150 | | warnings, |
| | 124 | 151 | | includeWarningsWhenDenied: options.ShortCircuitOnFirstDenial); |
| | | 152 | | |
| | 124 | 153 | | return await ApplyDecisionPolicyAsync( |
| | 124 | 154 | | context, |
| | 124 | 155 | | composedDecision, |
| | 124 | 156 | | CreateConstraintResultsView(results), |
| | 124 | 157 | | CreateProtectedThreatWarningDecision(context, threatEvaluation.WarningReasons, composedDecision), |
| | 124 | 158 | | cancellationToken) |
| | 124 | 159 | | .ConfigureAwait(false); |
| | 182 | 160 | | } |
| | | 161 | | |
| | | 162 | | private static bool ShouldConvertExceptionToDenial(Exception exception, bool treatExceptionAsDenial) |
| | | 163 | | { |
| | 32 | 164 | | return treatExceptionAsDenial && |
| | 32 | 165 | | exception is not OperationCanceledException && |
| | 32 | 166 | | !IsCriticalException(exception); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private static bool IsCriticalException(Exception exception) |
| | | 170 | | { |
| | 29 | 171 | | return exception is OutOfMemoryException or |
| | 29 | 172 | | StackOverflowException or |
| | 29 | 173 | | AccessViolationException or |
| | 29 | 174 | | AppDomainUnloadedException or |
| | 29 | 175 | | BadImageFormatException or |
| | 29 | 176 | | InvalidProgramException || |
| | 29 | 177 | | (exception.InnerException is not null && IsCriticalException(exception.InnerException)); |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | private List<ConstraintEvaluationResult>? CreateConstraintResultsBuffer() |
| | | 181 | | { |
| | 143 | 182 | | return decisionPolicy is null |
| | 143 | 183 | | ? null |
| | 143 | 184 | | : new List<ConstraintEvaluationResult>(constraints.Length); |
| | | 185 | | } |
| | | 186 | | |
| | | 187 | | private static bool AccumulateConstraintResult( |
| | | 188 | | ConstraintEvaluationResult result, |
| | | 189 | | ref OperationReasonAccumulator denials, |
| | | 190 | | ref OperationReasonAccumulator warnings, |
| | | 191 | | bool shortCircuitOnFirstDenial) |
| | | 192 | | { |
| | 246 | 193 | | if (result.IsDenied) |
| | | 194 | | { |
| | 33 | 195 | | denials.AddRange(result.Reasons); |
| | | 196 | | |
| | 33 | 197 | | if (!shortCircuitOnFirstDenial) |
| | | 198 | | { |
| | 22 | 199 | | warnings = default; |
| | | 200 | | } |
| | | 201 | | |
| | 33 | 202 | | return !shortCircuitOnFirstDenial; |
| | | 203 | | } |
| | | 204 | | |
| | 213 | 205 | | if (result.IsWarning && denials.Count == 0) |
| | | 206 | | { |
| | 91 | 207 | | warnings.AddRange(result.Reasons); |
| | | 208 | | } |
| | | 209 | | |
| | 213 | 210 | | return true; |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | private async ValueTask<GovernanceDecision> EvaluateEmptyPolicyAsync( |
| | | 214 | | TContext context, |
| | | 215 | | IReadOnlyList<OperationReason> threatWarningReasons, |
| | | 216 | | CancellationToken cancellationToken) |
| | | 217 | | { |
| | 13 | 218 | | if (!options.DenyWhenNoConstraints) |
| | | 219 | | { |
| | 4 | 220 | | LogEmptyPolicyAllowed(context); |
| | | 221 | | } |
| | | 222 | | |
| | 13 | 223 | | GovernanceDecision noConstraintDecision = CreateNoConstraintDecision( |
| | 13 | 224 | | context, |
| | 13 | 225 | | threatWarningReasons, |
| | 13 | 226 | | options.DenyWhenNoConstraints); |
| | | 227 | | |
| | 13 | 228 | | return await ApplyDecisionPolicyAsync( |
| | 13 | 229 | | context, |
| | 13 | 230 | | noConstraintDecision, |
| | 13 | 231 | | EmptyConstraintResults, |
| | 13 | 232 | | protectedThreatDecision: threatWarningReasons.Count > 0 ? noConstraintDecision : null, |
| | 13 | 233 | | cancellationToken) |
| | 13 | 234 | | .ConfigureAwait(false); |
| | 13 | 235 | | } |
| | | 236 | | |
| | | 237 | | private static GovernanceDecision Compose( |
| | | 238 | | TContext context, |
| | | 239 | | OperationReasonAccumulator denials, |
| | | 240 | | OperationReasonAccumulator warnings, |
| | | 241 | | bool includeWarningsWhenDenied) |
| | | 242 | | { |
| | 124 | 243 | | return denials.Count > 0 |
| | 124 | 244 | | ? includeWarningsWhenDenied && warnings.Count > 0 |
| | 124 | 245 | | ? GovernanceDecision.Deny( |
| | 124 | 246 | | warnings.ConcatAsArray(denials), |
| | 124 | 247 | | correlationId: context.CorrelationId, |
| | 124 | 248 | | policyVersion: context.PolicyVersion, |
| | 124 | 249 | | policyHash: context.PolicyHash) |
| | 124 | 250 | | : CreateDeniedDecision(context, denials) |
| | 124 | 251 | | : warnings.Count > 0 |
| | 124 | 252 | | ? CreateWarningDecision(context, warnings) |
| | 124 | 253 | | : GovernanceDecision.Allow( |
| | 124 | 254 | | correlationId: context.CorrelationId, |
| | 124 | 255 | | policyVersion: context.PolicyVersion, |
| | 124 | 256 | | policyHash: context.PolicyHash); |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | private static GovernanceDecision CreateNoConstraintDecision( |
| | | 260 | | TContext context, |
| | | 261 | | IReadOnlyList<OperationReason> threatWarningReasons) |
| | | 262 | | { |
| | 4 | 263 | | return threatWarningReasons.Count > 0 |
| | 4 | 264 | | ? GovernanceDecision.Warning( |
| | 4 | 265 | | threatWarningReasons, |
| | 4 | 266 | | correlationId: context.CorrelationId, |
| | 4 | 267 | | policyVersion: context.PolicyVersion, |
| | 4 | 268 | | policyHash: context.PolicyHash) |
| | 4 | 269 | | : GovernanceDecision.Allow( |
| | 4 | 270 | | correlationId: context.CorrelationId, |
| | 4 | 271 | | policyVersion: context.PolicyVersion, |
| | 4 | 272 | | policyHash: context.PolicyHash); |
| | | 273 | | } |
| | | 274 | | |
| | | 275 | | private GovernanceDecision CreateNoConstraintDecision( |
| | | 276 | | TContext context, |
| | | 277 | | IReadOnlyList<OperationReason> threatWarningReasons, |
| | | 278 | | bool denyWhenNoConstraints) |
| | | 279 | | { |
| | 13 | 280 | | return !denyWhenNoConstraints |
| | 13 | 281 | | ? CreateNoConstraintDecision(context, threatWarningReasons) |
| | 13 | 282 | | : GovernanceDecision.Deny( |
| | 13 | 283 | | options.NoConstraintsReasonCode, |
| | 13 | 284 | | options.NoConstraintsReasonMessage, |
| | 13 | 285 | | correlationId: context.CorrelationId, |
| | 13 | 286 | | policyVersion: context.PolicyVersion, |
| | 13 | 287 | | policyHash: context.PolicyHash); |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | private static GovernanceDecision CreateDeniedDecision( |
| | | 291 | | TContext context, |
| | | 292 | | OperationReasonAccumulator denials) |
| | | 293 | | { |
| | 19 | 294 | | return denials.Count == 1 |
| | 19 | 295 | | ? GovernanceDecision.Deny( |
| | 19 | 296 | | denials.FirstReason!, |
| | 19 | 297 | | correlationId: context.CorrelationId, |
| | 19 | 298 | | policyVersion: context.PolicyVersion, |
| | 19 | 299 | | policyHash: context.PolicyHash) |
| | 19 | 300 | | : GovernanceDecision.Deny( |
| | 19 | 301 | | denials.AsReadOnlyList(), |
| | 19 | 302 | | correlationId: context.CorrelationId, |
| | 19 | 303 | | policyVersion: context.PolicyVersion, |
| | 19 | 304 | | policyHash: context.PolicyHash); |
| | | 305 | | } |
| | | 306 | | |
| | | 307 | | private static GovernanceDecision CreateWarningDecision( |
| | | 308 | | TContext context, |
| | | 309 | | OperationReasonAccumulator warnings) |
| | | 310 | | { |
| | 79 | 311 | | return warnings.Count == 1 |
| | 79 | 312 | | ? GovernanceDecision.Warning( |
| | 79 | 313 | | warnings.FirstReason!, |
| | 79 | 314 | | correlationId: context.CorrelationId, |
| | 79 | 315 | | policyVersion: context.PolicyVersion, |
| | 79 | 316 | | policyHash: context.PolicyHash) |
| | 79 | 317 | | : GovernanceDecision.Warning( |
| | 79 | 318 | | warnings.AsReadOnlyList(), |
| | 79 | 319 | | correlationId: context.CorrelationId, |
| | 79 | 320 | | policyVersion: context.PolicyVersion, |
| | 79 | 321 | | policyHash: context.PolicyHash); |
| | | 322 | | } |
| | | 323 | | |
| | | 324 | | private static IReadOnlyList<ConstraintEvaluationResult> CreateConstraintResultsView( |
| | | 325 | | List<ConstraintEvaluationResult>? results) |
| | | 326 | | { |
| | 132 | 327 | | return results is null || results.Count == 0 |
| | 132 | 328 | | ? EmptyConstraintResults |
| | 132 | 329 | | : results.AsReadOnly(); |
| | | 330 | | } |
| | | 331 | | |
| | | 332 | | private static GovernanceDecision? CreateProtectedThreatWarningDecision( |
| | | 333 | | TContext context, |
| | | 334 | | IReadOnlyList<OperationReason> threatWarningReasons, |
| | | 335 | | GovernanceDecision composedDecision) |
| | | 336 | | { |
| | 124 | 337 | | return threatWarningReasons.Count > 0 && composedDecision.CanProceed |
| | 124 | 338 | | ? GovernanceDecision.Warning( |
| | 124 | 339 | | threatWarningReasons, |
| | 124 | 340 | | correlationId: context.CorrelationId, |
| | 124 | 341 | | policyVersion: context.PolicyVersion, |
| | 124 | 342 | | policyHash: context.PolicyHash) |
| | 124 | 343 | | : null; |
| | | 344 | | } |
| | | 345 | | |
| | | 346 | | private async ValueTask<GovernanceDecision> ApplyDecisionPolicyAsync( |
| | | 347 | | TContext context, |
| | | 348 | | GovernanceDecision decision, |
| | | 349 | | IReadOnlyList<ConstraintEvaluationResult> results, |
| | | 350 | | GovernanceDecision? protectedThreatDecision, |
| | | 351 | | CancellationToken cancellationToken) |
| | | 352 | | { |
| | 182 | 353 | | if (decisionPolicy is null) |
| | | 354 | | { |
| | 157 | 355 | | return decision; |
| | | 356 | | } |
| | | 357 | | |
| | 25 | 358 | | GovernanceDecision policyDecision = await decisionPolicy |
| | 25 | 359 | | .ApplyAsync(context, decision, results, cancellationToken) |
| | 25 | 360 | | .ConfigureAwait(false); |
| | | 361 | | |
| | 25 | 362 | | return options.PreventThreatAssessmentAllowDowngrade && protectedThreatDecision is not null && policyDecision.Is |
| | 25 | 363 | | ? protectedThreatDecision |
| | 25 | 364 | | : policyDecision; |
| | 182 | 365 | | } |
| | | 366 | | |
| | | 367 | | private async ValueTask<ThreatEvaluationResult> EvaluateThreatModelContributorsAsync( |
| | | 368 | | TContext context, |
| | | 369 | | CancellationToken cancellationToken) |
| | | 370 | | { |
| | 203 | 371 | | if (threatModelContributors.Length == 0) |
| | | 372 | | { |
| | 138 | 373 | | return ThreatEvaluationResult.Empty; |
| | | 374 | | } |
| | | 375 | | |
| | 65 | 376 | | List<OperationReason>? reasons = null; |
| | 65 | 377 | | OperationReason? selectedReason = null; |
| | 65 | 378 | | GovernanceDecisionOutcome? selectedOutcome = null; |
| | | 379 | | |
| | 269 | 380 | | foreach (IThreatModelContributor<TContext> contributor in threatModelContributors) |
| | | 381 | | { |
| | 77 | 382 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 383 | | |
| | | 384 | | ThreatAssessment? assessment; |
| | | 385 | | try |
| | | 386 | | { |
| | 77 | 387 | | assessment = await contributor |
| | 77 | 388 | | .AssessAsync(context, cancellationToken) |
| | 77 | 389 | | .ConfigureAwait(false); |
| | 63 | 390 | | } |
| | 14 | 391 | | catch (Exception exception) when (ShouldConvertExceptionToDenial(exception, options.TreatThreatContributorEx |
| | | 392 | | { |
| | 5 | 393 | | return CreateThreatContributorExceptionResult(context, contributor, exception); |
| | | 394 | | } |
| | | 395 | | |
| | 63 | 396 | | if (assessment is null || !assessment.IsActionable) |
| | | 397 | | { |
| | | 398 | | continue; |
| | | 399 | | } |
| | | 400 | | |
| | 60 | 401 | | GovernanceDecisionOutcome effectiveOutcome = GetEffectiveThreatOutcome(assessment); |
| | 59 | 402 | | var reason = assessment.ToOperationReason(GetContributorName(contributor), effectiveOutcome); |
| | 59 | 403 | | GovernanceDecisionOutcome moreRestrictiveOutcome = SelectMoreRestrictiveOutcome(selectedOutcome, effectiveOu |
| | | 404 | | |
| | 59 | 405 | | if (selectedOutcome != moreRestrictiveOutcome) |
| | | 406 | | { |
| | 54 | 407 | | selectedOutcome = moreRestrictiveOutcome; |
| | 54 | 408 | | selectedReason = reason; |
| | | 409 | | } |
| | | 410 | | |
| | 59 | 411 | | reasons ??= []; |
| | 59 | 412 | | reasons.Add(reason); |
| | 59 | 413 | | } |
| | | 414 | | |
| | 50 | 415 | | return reasons is null || selectedOutcome is null |
| | 50 | 416 | | ? ThreatEvaluationResult.Empty |
| | 50 | 417 | | : CreateThreatEvaluationResult(context, selectedOutcome.Value, selectedReason!, reasons.AsReadOnly()); |
| | 193 | 418 | | } |
| | | 419 | | |
| | | 420 | | private ThreatEvaluationResult CreateThreatContributorExceptionResult( |
| | | 421 | | TContext context, |
| | | 422 | | IThreatModelContributor<TContext> contributor, |
| | | 423 | | Exception exception) |
| | | 424 | | { |
| | 5 | 425 | | string contributorName = GetContributorName(contributor); |
| | 5 | 426 | | LogThreatContributorExceptionDenied(context, contributorName, exception); |
| | | 427 | | |
| | 5 | 428 | | Dictionary<string, string> metadata = new(StringComparer.Ordinal) |
| | 5 | 429 | | { |
| | 5 | 430 | | ["threat.contributor"] = contributorName, |
| | 5 | 431 | | ["threat.failure"] = exception.GetType().Name |
| | 5 | 432 | | }; |
| | | 433 | | |
| | 5 | 434 | | var reason = OperationReason.Create( |
| | 5 | 435 | | options.ThreatContributorExceptionReasonCode, |
| | 5 | 436 | | options.ThreatContributorExceptionReasonMessage, |
| | 5 | 437 | | metadata); |
| | | 438 | | |
| | 5 | 439 | | var decision = GovernanceDecision.Deny( |
| | 5 | 440 | | reason, |
| | 5 | 441 | | correlationId: context.CorrelationId, |
| | 5 | 442 | | policyVersion: context.PolicyVersion, |
| | 5 | 443 | | policyHash: context.PolicyHash); |
| | | 444 | | |
| | 5 | 445 | | return ThreatEvaluationResult.ForBlockingDecision(decision); |
| | | 446 | | } |
| | | 447 | | |
| | | 448 | | private static ThreatEvaluationResult CreateThreatEvaluationResult( |
| | | 449 | | TContext context, |
| | | 450 | | GovernanceDecisionOutcome outcome, |
| | | 451 | | OperationReason selectedReason, |
| | | 452 | | ReadOnlyCollection<OperationReason> reasons) |
| | | 453 | | { |
| | 48 | 454 | | return outcome switch |
| | 48 | 455 | | { |
| | 22 | 456 | | GovernanceDecisionOutcome.Denied => ThreatEvaluationResult.ForBlockingDecision( |
| | 22 | 457 | | GovernanceDecision.Deny( |
| | 22 | 458 | | reasons, |
| | 22 | 459 | | correlationId: context.CorrelationId, |
| | 22 | 460 | | policyVersion: context.PolicyVersion, |
| | 22 | 461 | | policyHash: context.PolicyHash)), |
| | 5 | 462 | | GovernanceDecisionOutcome.Deferred => ThreatEvaluationResult.ForBlockingDecision( |
| | 5 | 463 | | GovernanceDecision.Defer( |
| | 5 | 464 | | selectedReason.Code, |
| | 5 | 465 | | selectedReason.Message, |
| | 5 | 466 | | correlationId: context.CorrelationId, |
| | 5 | 467 | | policyVersion: context.PolicyVersion, |
| | 5 | 468 | | policyHash: context.PolicyHash)), |
| | 3 | 469 | | GovernanceDecisionOutcome.AcknowledgmentRequired => ThreatEvaluationResult.ForBlockingDecision( |
| | 3 | 470 | | GovernanceDecision.RequireAcknowledgment( |
| | 3 | 471 | | selectedReason.Code, |
| | 3 | 472 | | selectedReason.Message, |
| | 3 | 473 | | correlationId: context.CorrelationId, |
| | 3 | 474 | | policyVersion: context.PolicyVersion, |
| | 3 | 475 | | policyHash: context.PolicyHash)), |
| | 2 | 476 | | GovernanceDecisionOutcome.EscalationRecommended => ThreatEvaluationResult.ForBlockingDecision( |
| | 2 | 477 | | GovernanceDecision.Escalate( |
| | 2 | 478 | | selectedReason.Code, |
| | 2 | 479 | | selectedReason.Message, |
| | 2 | 480 | | correlationId: context.CorrelationId, |
| | 2 | 481 | | policyVersion: context.PolicyVersion, |
| | 2 | 482 | | policyHash: context.PolicyHash)), |
| | 15 | 483 | | GovernanceDecisionOutcome.Warning => ThreatEvaluationResult.ForWarningReasons(reasons), |
| | 1 | 484 | | GovernanceDecisionOutcome.Allowed => throw CreateInvalidAllowedThreatOutcomeException(), |
| | 0 | 485 | | _ => ThreatEvaluationResult.Empty |
| | 48 | 486 | | }; |
| | | 487 | | } |
| | | 488 | | |
| | | 489 | | private static GovernanceDecisionOutcome GetEffectiveThreatOutcome(ThreatAssessment assessment) |
| | | 490 | | { |
| | 60 | 491 | | return assessment.RecommendedOutcome is GovernanceDecisionOutcome.Allowed |
| | 60 | 492 | | ? throw CreateInvalidAllowedThreatOutcomeException() |
| | 60 | 493 | | : assessment.RecommendedOutcome; |
| | | 494 | | } |
| | | 495 | | |
| | | 496 | | private static InvalidOperationException CreateInvalidAllowedThreatOutcomeException() |
| | | 497 | | { |
| | 3 | 498 | | return new InvalidOperationException(InvalidAllowedThreatOutcomeMessage); |
| | | 499 | | } |
| | | 500 | | |
| | | 501 | | private static GovernanceDecisionOutcome SelectMoreRestrictiveOutcome( |
| | | 502 | | GovernanceDecisionOutcome? current, |
| | | 503 | | GovernanceDecisionOutcome candidate) |
| | | 504 | | { |
| | 59 | 505 | | return current is null |
| | 59 | 506 | | ? candidate |
| | 59 | 507 | | : GetThreatOutcomeRank(candidate) > GetThreatOutcomeRank(current.Value) |
| | 59 | 508 | | ? candidate |
| | 59 | 509 | | : current.Value; |
| | | 510 | | } |
| | | 511 | | |
| | | 512 | | private static int GetThreatOutcomeRank(GovernanceDecisionOutcome outcome) |
| | | 513 | | { |
| | 25 | 514 | | return outcome switch |
| | 25 | 515 | | { |
| | 2 | 516 | | GovernanceDecisionOutcome.Denied => 5, |
| | 4 | 517 | | GovernanceDecisionOutcome.EscalationRecommended => 4, |
| | 4 | 518 | | GovernanceDecisionOutcome.AcknowledgmentRequired => 3, |
| | 4 | 519 | | GovernanceDecisionOutcome.Deferred => 2, |
| | 10 | 520 | | GovernanceDecisionOutcome.Warning => 1, |
| | 1 | 521 | | GovernanceDecisionOutcome.Allowed => throw CreateInvalidAllowedThreatOutcomeException(), |
| | 0 | 522 | | _ => 0 |
| | 25 | 523 | | }; |
| | | 524 | | } |
| | | 525 | | |
| | | 526 | | private static string GetContributorName(IThreatModelContributor<TContext> contributor) |
| | | 527 | | { |
| | 64 | 528 | | return string.IsNullOrWhiteSpace(contributor.Name) |
| | 64 | 529 | | ? "<unnamed>" |
| | 64 | 530 | | : contributor.Name.Trim(); |
| | | 531 | | } |
| | | 532 | | |
| | | 533 | | private async ValueTask<GovernanceDecision> CreateConstraintExceptionDecisionAsync( |
| | | 534 | | TContext context, |
| | | 535 | | IGovernanceConstraint<TContext> constraint, |
| | | 536 | | List<ConstraintEvaluationResult>? results, |
| | | 537 | | Exception exception, |
| | | 538 | | CancellationToken cancellationToken) |
| | | 539 | | { |
| | 8 | 540 | | LogConstraintExceptionDenied(context, constraint.Name, exception); |
| | | 541 | | |
| | 8 | 542 | | var exceptionResult = ConstraintEvaluationResult.Deny( |
| | 8 | 543 | | options.ConstraintExceptionReasonCode, |
| | 8 | 544 | | options.ConstraintExceptionReasonMessage); |
| | 8 | 545 | | results?.Add(exceptionResult); |
| | | 546 | | |
| | 8 | 547 | | var exceptionDecision = GovernanceDecision.Deny( |
| | 8 | 548 | | exceptionResult.Reasons, |
| | 8 | 549 | | correlationId: context.CorrelationId, |
| | 8 | 550 | | policyVersion: context.PolicyVersion, |
| | 8 | 551 | | policyHash: context.PolicyHash); |
| | | 552 | | |
| | 8 | 553 | | return await ApplyDecisionPolicyAsync( |
| | 8 | 554 | | context, |
| | 8 | 555 | | exceptionDecision, |
| | 8 | 556 | | CreateConstraintResultsView(results), |
| | 8 | 557 | | protectedThreatDecision: null, |
| | 8 | 558 | | cancellationToken) |
| | 8 | 559 | | .ConfigureAwait(false); |
| | 8 | 560 | | } |
| | | 561 | | |
| | | 562 | | private void LogEmptyPolicyAllowed(TContext context) |
| | | 563 | | { |
| | 4 | 564 | | if (logger is null) |
| | | 565 | | { |
| | 3 | 566 | | return; |
| | | 567 | | } |
| | | 568 | | |
| | 1 | 569 | | EmptyPolicyAllowedWarning( |
| | 1 | 570 | | logger, |
| | 1 | 571 | | context.CorrelationId ?? string.Empty, |
| | 1 | 572 | | context.PolicyVersion ?? string.Empty, |
| | 1 | 573 | | context.PolicyHash ?? string.Empty, |
| | 1 | 574 | | null); |
| | 1 | 575 | | } |
| | | 576 | | |
| | | 577 | | private void LogConstraintExceptionDenied( |
| | | 578 | | TContext context, |
| | | 579 | | string constraintName, |
| | | 580 | | Exception exception) |
| | | 581 | | { |
| | 8 | 582 | | if (logger is null) |
| | | 583 | | { |
| | 5 | 584 | | return; |
| | | 585 | | } |
| | | 586 | | |
| | 3 | 587 | | ConstraintExceptionDeniedError( |
| | 3 | 588 | | logger, |
| | 3 | 589 | | string.IsNullOrWhiteSpace(constraintName) ? "<unnamed>" : constraintName, |
| | 3 | 590 | | exception.GetType().Name, |
| | 3 | 591 | | context.CorrelationId ?? string.Empty, |
| | 3 | 592 | | context.PolicyVersion ?? string.Empty, |
| | 3 | 593 | | context.PolicyHash ?? string.Empty, |
| | 3 | 594 | | exception); |
| | 3 | 595 | | } |
| | | 596 | | |
| | | 597 | | private void LogThreatContributorExceptionDenied( |
| | | 598 | | TContext context, |
| | | 599 | | string contributorName, |
| | | 600 | | Exception exception) |
| | | 601 | | { |
| | 5 | 602 | | if (logger is null) |
| | | 603 | | { |
| | 5 | 604 | | return; |
| | | 605 | | } |
| | | 606 | | |
| | 0 | 607 | | ThreatContributorExceptionDeniedError( |
| | 0 | 608 | | logger, |
| | 0 | 609 | | contributorName, |
| | 0 | 610 | | exception.GetType().Name, |
| | 0 | 611 | | context.CorrelationId ?? string.Empty, |
| | 0 | 612 | | context.PolicyVersion ?? string.Empty, |
| | 0 | 613 | | context.PolicyHash ?? string.Empty, |
| | 0 | 614 | | exception); |
| | 0 | 615 | | } |
| | | 616 | | |
| | | 617 | | private sealed class ThreatEvaluationResult |
| | | 618 | | { |
| | 17 | 619 | | private static readonly IReadOnlyList<OperationReason> EmptyReasons = |
| | 17 | 620 | | Array.AsReadOnly(Array.Empty<OperationReason>()); |
| | | 621 | | |
| | 69 | 622 | | private ThreatEvaluationResult( |
| | 69 | 623 | | IReadOnlyList<OperationReason> warningReasons, |
| | 69 | 624 | | GovernanceDecision? blockingDecision) |
| | | 625 | | { |
| | 69 | 626 | | WarningReasons = warningReasons; |
| | 69 | 627 | | BlockingDecision = blockingDecision; |
| | 69 | 628 | | } |
| | | 629 | | |
| | | 630 | | public static ThreatEvaluationResult Empty { get; } = new(EmptyReasons, blockingDecision: null); |
| | | 631 | | |
| | | 632 | | public IReadOnlyList<OperationReason> WarningReasons { get; } |
| | | 633 | | |
| | | 634 | | public GovernanceDecision? BlockingDecision { get; } |
| | | 635 | | |
| | | 636 | | public static ThreatEvaluationResult ForWarningReasons(IReadOnlyList<OperationReason> reasons) |
| | | 637 | | { |
| | 15 | 638 | | return new ThreatEvaluationResult(reasons, blockingDecision: null); |
| | | 639 | | } |
| | | 640 | | |
| | | 641 | | public static ThreatEvaluationResult ForBlockingDecision(GovernanceDecision decision) |
| | | 642 | | { |
| | 37 | 643 | | return new ThreatEvaluationResult(EmptyReasons, decision); |
| | | 644 | | } |
| | | 645 | | } |
| | | 646 | | |
| | | 647 | | private struct OperationReasonAccumulator |
| | | 648 | | { |
| | | 649 | | private List<OperationReason>? additionalReasons; |
| | | 650 | | |
| | | 651 | | public OperationReason? FirstReason { get; private set; } |
| | | 652 | | |
| | | 653 | | public int Count { get; private set; } |
| | | 654 | | |
| | | 655 | | public void AddRange(IReadOnlyList<OperationReason> reasons) |
| | | 656 | | { |
| | 808 | 657 | | for (int index = 0; index < reasons.Count; index++) |
| | | 658 | | { |
| | 137 | 659 | | Add(reasons[index]); |
| | | 660 | | } |
| | 267 | 661 | | } |
| | | 662 | | |
| | | 663 | | public readonly OperationReason[] ConcatAsArray(OperationReasonAccumulator other) |
| | | 664 | | { |
| | 8 | 665 | | int totalCount = Count + other.Count; |
| | 8 | 666 | | if (totalCount == 0) |
| | | 667 | | { |
| | 0 | 668 | | return []; |
| | | 669 | | } |
| | | 670 | | |
| | 8 | 671 | | var reasons = new OperationReason[totalCount]; |
| | 8 | 672 | | int nextIndex = CopyTo(reasons, 0); |
| | 8 | 673 | | _ = other.CopyTo(reasons, nextIndex); |
| | | 674 | | |
| | 8 | 675 | | return reasons; |
| | | 676 | | } |
| | | 677 | | |
| | | 678 | | public readonly ReadOnlyCollection<OperationReason> AsReadOnlyList() |
| | | 679 | | { |
| | 10 | 680 | | return Count switch |
| | 10 | 681 | | { |
| | 0 | 682 | | 0 => Array.AsReadOnly(Array.Empty<OperationReason>()), |
| | 0 | 683 | | 1 => Array.AsReadOnly([FirstReason!]), |
| | 10 | 684 | | _ => additionalReasons!.AsReadOnly() |
| | 10 | 685 | | }; |
| | | 686 | | } |
| | | 687 | | |
| | | 688 | | private void Add(OperationReason? reason) |
| | | 689 | | { |
| | 137 | 690 | | if (reason is null) |
| | | 691 | | { |
| | 0 | 692 | | return; |
| | | 693 | | } |
| | | 694 | | |
| | 137 | 695 | | if (Count == 0) |
| | | 696 | | { |
| | 122 | 697 | | FirstReason = reason; |
| | 122 | 698 | | Count = 1; |
| | 122 | 699 | | return; |
| | | 700 | | } |
| | | 701 | | |
| | 15 | 702 | | additionalReasons ??= [FirstReason!]; |
| | 15 | 703 | | additionalReasons.Add(reason); |
| | 15 | 704 | | Count++; |
| | 15 | 705 | | } |
| | | 706 | | |
| | | 707 | | private readonly int CopyTo(OperationReason[] destination, int startIndex) |
| | | 708 | | { |
| | 16 | 709 | | if (Count == 0) |
| | | 710 | | { |
| | 0 | 711 | | return startIndex; |
| | | 712 | | } |
| | | 713 | | |
| | 16 | 714 | | if (Count == 1) |
| | | 715 | | { |
| | 13 | 716 | | destination[startIndex] = FirstReason!; |
| | 13 | 717 | | return startIndex + 1; |
| | | 718 | | } |
| | | 719 | | |
| | 3 | 720 | | additionalReasons!.CopyTo(destination, startIndex); |
| | 3 | 721 | | return startIndex + additionalReasons.Count; |
| | | 722 | | } |
| | | 723 | | } |
| | | 724 | | } |