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