semi implemented and features implemented save checkpoint

This commit is contained in:
master
2026-02-08 18:00:49 +02:00
parent 04360dff63
commit 1bf6bbf395
20895 changed files with 716795 additions and 64 deletions

View File

@@ -0,0 +1,32 @@
# Adversarial Input Validation for Scoring Inputs
## Module
Policy
## Status
IMPLEMENTED
## Description
Input validation and sanitization for scoring engine inputs to prevent adversarial manipulation of risk scores through crafted CVSS vectors, EPSS values, or other scoring parameters.
## Implementation Details
- **Scoring Engine**: `src/Policy/StellaOps.Policy.Engine/Scoring/` -- scoring engine with input validation
- `Engines/AdvancedScoringEngine.cs` -- advanced scoring with validation
- `Engines/ProofAwareScoringEngine.cs` -- proof-aware scoring with integrity checks
- `Engines/SimpleScoringEngine.cs` -- base scoring engine
- `IScoringEngine.cs` -- scoring engine interface
- `ScoringEngineFactory.cs` -- factory for scoring engine selection
- **CVSS Scoring Library**: `src/Policy/StellaOps.Policy.Scoring/` -- CVSS v4.0 scoring engine with vector validation
- **Determinism Guard**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/DeterminismGuardService.cs` -- guards against non-deterministic inputs
- `ProhibitedPatternAnalyzer.cs` -- detects prohibited patterns in policy expressions
- `DeterminismViolation.cs` -- violation model for detected issues
- **Score Provenance**: `src/Policy/StellaOps.Policy.Engine/Attestation/ScoreProvenanceChain.cs` -- tracks provenance of scoring inputs
- `ScoringDeterminismVerifier.cs` -- verifies scoring determinism
## E2E Test Plan
- [ ] Submit a crafted CVSS v4.0 vector with out-of-range metric values and verify rejection
- [ ] Submit an EPSS score outside [0,1] range and verify clamping or rejection
- [ ] Verify scoring engine produces identical scores for identical inputs (determinism)
- [ ] Submit duplicate scoring requests and verify idempotent results
- [ ] Verify score provenance chain records all input hashes
- [ ] Submit adversarial policy expressions and verify ProhibitedPatternAnalyzer catches them

View File

@@ -0,0 +1,33 @@
# Anchor-Aware Determinization Rules in Policy Engine
## Module
Policy
## Status
IMPLEMENTED
## Description
Determinization rules that are aware of trust anchors, ensuring policy evaluation produces consistent results based on the trust anchor configuration and signal snapshots.
## Implementation Details
- **Determinization Gate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs` -- determinization gate evaluator
- `DeterminizationGateMetrics.cs` -- gate metrics tracking
- `ISignalSnapshotBuilder.cs` / `SignalSnapshotBuilder.cs` -- builds signal snapshots for deterministic evaluation
- **Determinization Policy**: `src/Policy/StellaOps.Policy.Engine/Policies/DeterminizationPolicy.cs` -- determinization policy definition
- `DeterminizationRuleSet.cs` -- rule set for determinization
- `IDeterminizationPolicy.cs` -- policy interface
- **Determinization Library**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/` -- core determinization library
- `Models/` -- determinization models
- `Scoring/` -- determinization scoring
- `Evidence/` -- evidence-based determinization
- **DI Registration**: `src/Policy/StellaOps.Policy.Engine/DependencyInjection/DeterminizationEngineExtensions.cs` -- service registration
- **Configuration Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/DeterminizationConfigEndpoints.cs` -- API for determinization configuration
- **Events**: `src/Policy/StellaOps.Policy.Engine/Subscriptions/DeterminizationEvents.cs` -- determinization event subscriptions
## E2E Test Plan
- [ ] Configure determinization rules via API and verify they apply during evaluation
- [ ] Evaluate a policy with signal snapshots and verify deterministic output
- [ ] Change trust anchor configuration and verify determinization rules adapt
- [ ] Run same evaluation twice with identical snapshots and verify identical results
- [ ] Verify determinization metrics are emitted (gate pass/fail counts)
- [ ] Test determinization configuration endpoint returns current rule set

View File

@@ -0,0 +1,35 @@
# Auditable Exception Objects
## Module
Policy
## Status
IMPLEMENTED
## Description
Exception objects with full audit trail including creation, approval, application, expiry, and revocation events. Supports evidence-linked approval workflows and audit-grade persistence.
## Implementation Details
- **Exception Library**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/` -- core exception system
- `Models/` -- exception domain models (ExceptionRecord, ExceptionApproval, etc.)
- `Services/` -- exception services (ExceptionService, ExceptionApprovalService)
- `Repositories/` -- exception persistence (IExceptionRepository)
- **Exception Adapter**: `src/Policy/StellaOps.Policy.Engine/Adapters/ExceptionAdapter.cs` -- adapts exceptions for policy evaluation
- `ExceptionEffectRegistry.cs` -- tracks effects of applied exceptions
- **Exception Domain**: `src/Policy/StellaOps.Policy.Engine/Domain/ExceptionContracts.cs` -- exception contracts
- `ExceptionMapper.cs` -- maps between exception models
- **Exception Cache**: `src/Policy/StellaOps.Policy.Engine/ExceptionCache/` -- exception caching
- `ExceptionCacheModels.cs`, `IExceptionEffectiveCache.cs`, `MessagingExceptionEffectiveCache.cs`, `RedisExceptionEffectiveCache.cs`
- **Exception Events**: `src/Policy/StellaOps.Policy.Engine/Events/ExceptionEventPublisher.cs` -- publishes exception lifecycle events
- **Lifecycle Workers**: `src/Policy/StellaOps.Policy.Engine/Workers/ExceptionLifecycleService.cs`, `ExceptionLifecycleWorker.cs` -- background processing
- **Approval Rules**: `src/Policy/StellaOps.Policy.Engine/Services/ExceptionApprovalRulesService.cs` -- approval workflow rules
- **Exception-Aware Evaluation**: `src/Policy/StellaOps.Policy.Engine/Services/ExceptionAwareEvaluationService.cs` -- evaluation with exception awareness
## E2E Test Plan
- [ ] Create an exception object and verify audit trail records creation event
- [ ] Approve an exception with evidence links and verify approval audit record
- [ ] Apply an exception to a policy evaluation and verify it modifies the verdict
- [ ] Let an exception expire and verify expiry event is recorded
- [ ] Revoke an exception and verify revocation audit trail
- [ ] Query exception history via API and verify all lifecycle events present
- [ ] Verify exception cache invalidation on approval/revocation

View File

@@ -0,0 +1,25 @@
# Batch Exception Loading for Policy Evaluation
## Module
Policy
## Status
IMPLEMENTED
## Description
Efficient batch loading of policy exceptions for large-scale evaluation, avoiding N+1 queries when evaluating many findings against exception records.
## Implementation Details
- **Batch Exception Loader**: `src/Policy/StellaOps.Policy.Engine/BatchEvaluation/BatchExceptionLoader.cs` -- bulk exception loading
- `BatchEvaluationModels.cs` -- batch evaluation request/response models
- **Batch Evaluation Endpoint**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BatchEvaluationEndpoint.cs` -- API for batch evaluation
- **Batch Context**: `src/Policy/StellaOps.Policy.Engine/BatchContext/BatchContextService.cs` -- batch context management
- `BatchContextModels.cs` -- batch context models
- **Batch Context Endpoint**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BatchContextEndpoint.cs` -- API for batch contexts
## E2E Test Plan
- [ ] Submit a batch evaluation request with 100+ findings and verify all exceptions loaded efficiently
- [ ] Verify batch context is created and reused across evaluations in the same batch
- [ ] Measure evaluation latency for batch vs. individual exception loading
- [ ] Verify batch evaluation API returns results for all submitted findings
- [ ] Test batch context cleanup after evaluation completes

View File

@@ -0,0 +1,51 @@
# Batch Simulation Orchestration
## Module
Policy
## Status
IMPLEMENTED
## Description
Batch simulation orchestration for running multiple policy simulations in parallel with a dedicated simulation service in the policy registry.
## Implementation Details
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs` -- `RiskSimulationService` (sealed class)
- `Simulate(RiskSimulationRequest)` runs a single risk simulation with finding scores, distributions, top movers, and aggregate metrics
- `SimulateWithBreakdown(RiskSimulationRequest, RiskSimulationBreakdownOptions?)` runs with detailed breakdown analytics per POLICY-RISK-67-003
- `CompareProfilesWithBreakdown(baseProfileId, compareProfileId, findings)` runs comparison simulation between two risk profiles with trend analysis
- `GenerateBreakdown(result, findings)` generates standalone breakdown for existing simulation results
- Score formula: signal values * weights -> normalized to 0-100 range
- Signal types: Boolean (0/1), Numeric (direct), Categorical (mapped: none=0.0, low=0.3, medium=0.6, critical=1.0)
- Severity thresholds: Critical >= 90, High >= 70, Medium >= 40, Low >= 10, else Informational
- Actions: Critical/High -> Deny, Medium -> Review, Low/Info -> Allow
- Supports severity and decision overrides via predicate matching on signal values
- Produces distribution with 10 buckets and percentiles (p25, p50, p75, p90, p95, p99)
- Top 10 movers identified by score with primary driver signals
- **RiskSimulationBreakdownService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationBreakdownService.cs` -- generates detailed breakdown analytics and comparison breakdowns
- **SimulationAnalyticsService**: `src/Policy/StellaOps.Policy.Engine/Simulation/SimulationAnalyticsService.cs` -- simulation analytics with delta summary computation
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs` -- `WhatIfSimulationService` (internal sealed class)
- `SimulateAsync(WhatIfSimulationRequest)` executes what-if simulation without persisting results
- Supports hypothetical SBOM diffs (add/remove/upgrade/downgrade operations) and draft policy evaluation
- Computes decision changes between baseline and simulated: status_changed, severity_changed, new, removed
- Impact analysis: risk delta (increased/decreased/unchanged), blocked/warning deltas, recommendations
- VEX override handling: not_affected overrides deny to allow; unreachable downgrades deny to warn
- Uses EffectiveDecisionMap, PolicyCompilationService, PolicyPackRepository
- **Simulation Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskSimulationEndpoints.cs` -- REST API for simulation runs
- **Overlay Simulation**: `src/Policy/StellaOps.Policy.Engine/Endpoints/OverlaySimulationEndpoint.cs` -- overlay-based simulation
- **Console Simulation**: `src/Policy/StellaOps.Policy.Engine/Endpoints/ConsoleSimulationEndpoint.cs` -- console surface simulation
- **Path Scope Simulation**: `src/Policy/StellaOps.Policy.Engine/Endpoints/PathScopeSimulationEndpoint.cs` -- path-scoped simulation
- **Batch Evaluation**: `src/Policy/StellaOps.Policy.Engine/BatchEvaluation/BatchEvaluationModels.cs` -- models for batch evaluation runs
- **Telemetry**: `RiskSimulationsRun` counter via `PolicyEngineTelemetry`, activity tracing with `risk_simulation.run` and `policy.whatif.simulate`
## E2E Test Plan
- [ ] POST to risk simulation endpoint with a profile ID and list of findings; verify response contains simulation ID, finding scores, distributions, and aggregate metrics
- [ ] POST with `IncludeContributions=true` and verify signal contribution percentages sum to ~100% and override chain is returned
- [ ] POST with `IncludeDistribution=true` and verify 10 buckets, 6 percentile levels, severity breakdown covering all 5 levels
- [ ] Run `SimulateWithBreakdown` and verify breakdown analytics are present alongside the base simulation result
- [ ] Run `CompareProfilesWithBreakdown` with two profile IDs and verify baseline vs compare results with trend analysis
- [ ] POST what-if simulation with SBOM diff (add component with advisory) and verify new `deny` decision appears
- [ ] POST what-if simulation with SBOM diff (remove component) and verify `allow` decision and `removed` change type
- [ ] POST what-if simulation with draft policy YAML and verify simulated policy reference includes computed digest
- [ ] Verify simulation IDs are deterministic (same inputs produce same `rsim-*` prefix ID)
- [ ] Verify simulation with 0 findings returns zeroed aggregate metrics

View File

@@ -0,0 +1,54 @@
# Belnap K4 Trust Lattice Engine (VEX Resolution, Trust Algebra)
## Module
Policy
## Status
IMPLEMENTED
## Description
Full K4 lattice implementation with 4-valued logic (unknown/true/false/conflict), trust labels, lattice store, claim score merging, conflict penalization, and disposition selection. VEX normalization for OpenVEX and CSAF formats. Deterministic, commutative, idempotent merge operations. Comprehensive tests including property-based tests.
## Implementation Details
- **K4Lattice**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/K4Lattice.cs` -- Belnap four-valued logic implementation
- `K4Value` enum: Unknown (bottom), True, False, Conflict (top)
- Knowledge ordering: Unknown < True|False < Conflict; True and False are incomparable
- `Join(a, b)` -- knowledge join (union of support): T join F = Conflict; short-circuits on Conflict
- `JoinAll(values)` -- order-independent aggregation over sequence; short-circuits on Conflict
- `Meet(a, b)` -- knowledge meet (intersection): T meet F = Unknown; Conflict meet X = X
- `LessOrEqual(a, b)` -- knowledge ordering predicate
- `Negate(v)` -- swaps True/False; Unknown and Conflict are self-negating
- `FromSupport(hasTrueSupport, hasFalseSupport)` -- constructs K4 value from support flags
- Helper predicates: `HasTrueSupport`, `HasFalseSupport`, `IsDefinite`, `IsIndeterminate`
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs` -- orchestrates complete trust evaluation pipeline
- Pipeline: VEX normalization -> claim ingestion -> K4 lattice evaluation -> disposition selection -> proof bundle generation
- `IngestVex(document, format, principal, trustLabel?)` -- ingests VEX document via registered normalizers
- `IngestClaim(claim)` / `IngestClaims(claims)` -- direct claim ingestion into LatticeStore
- `GetDisposition(subject)` -- evaluates subject and returns DispositionResult
- `MergeClaims(scoredClaims, policy?)` -- merges scored VEX claims using ClaimScore-based algorithm
- `Evaluate(options?)` -- evaluates all subjects with optional proof bundle generation and subject filtering
- Fluent `ClaimBuilder` with `Assert(atom, value)`, `Present()`, `Applies()`, `Reachable()`, `Mitigated()`, `Fixed()`, `Misattributed()`
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs` -- lattice-based merge with conflict penalization
- `Merge(scoredClaims, policy)` -- orders by adjusted score, specificity, original score; selects winner
- `ConflictPenalizer` applies configurable penalty (default 0.25) to conflicting claims
- `MergePolicy` options: `ConflictPenalty`, `PreferSpecificity`, `RequireReplayProofOnConflict`
- Returns `MergeResult` with: winning claim, all scored claims, conflict records, confidence, RequiresReplayProof flag
- **LatticeStore**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/LatticeStore.cs` -- subject state storage and claim aggregation
- **DispositionSelector**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/DispositionSelector.cs` -- applies policy rules to select final disposition
- **ConflictPenalizer**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ConflictPenalizer.cs` -- applies configurable penalties to conflicting claims
- **SecurityAtom**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/SecurityAtom.cs` -- atomic propositions (Present, Applies, Reachable, Mitigated, Fixed, Misattributed)
- **VEX Normalizers**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/VexNormalizers.cs`, `OpenVexNormalizer.cs`, `CsafVexNormalizer.cs` -- normalize CycloneDX, OpenVEX, CSAF formats to claims
- **TrustLabel**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLabel.cs` -- trust level annotations for claims
- **PolicyBundle / ProofBundle**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/PolicyBundle.cs`, `ProofBundle.cs` -- policy configuration and proof bundles with decision traces
## E2E Test Plan
- [ ] Create TrustLatticeEngine with default policy; ingest two claims with True and False assertions for same subject; verify K4 value is Conflict
- [ ] Ingest claims from OpenVEX, CycloneDX, and CSAF documents; verify all three normalizers produce valid claims in the LatticeStore
- [ ] Verify Join commutativity: `Join(a, b) == Join(b, a)` for all K4Value combinations
- [ ] Verify Join idempotency: `Join(a, a) == a` for all K4Value values
- [ ] Verify Meet/Join absorption: `Join(a, Meet(a, b)) == a` for all K4Value combinations
- [ ] Verify conflict penalization: merge two claims with different VEX statuses; winning claim has lower adjusted score than original when conflict detected
- [ ] Verify `RequiresReplayProof` is set when `RequireReplayProofOnConflict=true` and conflicts exist
- [ ] Evaluate all subjects with `GenerateProofBundle=true` and verify proof bundle contains atom tables, claims, and decisions
- [ ] Verify subject filter: evaluate with SubjectFilter containing one digest; only that subject's disposition is returned
- [ ] Verify ClaimBuilder fluent API: create claim with `Present().Reachable().Mitigated()` and verify three assertions are ingested

View File

@@ -0,0 +1,37 @@
# Blast radius / fleet view
## Module
Policy
## Status
IMPLEMENTED
## Description
Blast radius containment schema and unknown ranker service assess impact across environments and services.
## Implementation Details
- **BlastRadius Model**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/BlastRadius.cs` -- `BlastRadius` (sealed record)
- `Dependents` (int) -- number of packages that directly or transitively depend on this package; 0 indicates isolation
- `NetFacing` (bool) -- whether the package is reachable from network-facing entrypoints
- `Privilege` (string?) -- privilege level: root, user, none
- **ContainmentSignals Model**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/ContainmentSignals.cs` -- runtime containment posture
- Seccomp enforcement status, filesystem mode (ro/rw), network policy (isolated/connected)
- **UnknownRanker Integration**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs` -- blast radius is integrated into the `ComputeContainmentReduction` method
- Isolated package (Dependents=0): 15% risk reduction
- Not network-facing: 5% risk reduction
- Non-root privilege (user/none): 5% risk reduction
- Seccomp enforced: 10% reduction; read-only filesystem: 10% reduction; network isolated: 5% reduction
- Maximum containment reduction capped at 40%
- Applied after time-based decay: `finalScore = decayedScore * (1 - containmentReduction)`
- **UnknownRankerOptions**: Configurable reductions via `IsolatedReduction`, `NotNetFacingReduction`, `NonRootReduction`, `SeccompEnforcedReduction`, `FsReadOnlyReduction`, `NetworkIsolatedReduction`, `MaxContainmentReduction`
- **Unknown Model**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/Unknown.cs` -- unknown entity with blast radius reference
- **Unknowns Budget Enforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/UnknownsBudgetEnforcer.cs` -- enforces blast radius-aware budget thresholds
- **Unknowns Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/UnknownsEndpoints.cs` -- REST API for querying unknowns with blast radius data
## E2E Test Plan
- [ ] Rank an unknown with `Dependents=0, NetFacing=false, Privilege="none"` and verify containment reduction is 25% (15+5+5)
- [ ] Rank an unknown with `Dependents=50, NetFacing=true, Privilege="root"` and verify containment reduction is 0%
- [ ] Rank an unknown with full containment signals (seccomp=enforced, fs=ro, network=isolated) and blast radius isolation; verify capped at 40% max reduction
- [ ] Query unknowns API and verify each unknown includes blast radius data (dependents, netFacing, privilege)
- [ ] Verify a high-score unknown (HOT band) drops to WARM band when isolated package containment is applied
- [ ] Verify containment reduction is disabled when `EnableContainmentReduction=false` in options

View File

@@ -0,0 +1,46 @@
# Blast Radius Scoring for Unknowns (Dependency Graph Impact)
## Module
Policy
## Status
IMPLEMENTED
## Description
Adds dependency graph impact scoring (dependent count, network-facing flag, privilege level) to the unknowns ranking algorithm. Isolated packages (0 dependents) get 15% risk reduction, non-network-facing gets 5%, non-root privilege gets 5%.
## Implementation Details
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs` -- `UnknownRanker` (sealed class implements `IUnknownRanker`)
- Sprint: SPRINT_4000_0001_0002_unknowns_blast_radius_containment
- Two-factor ranking formula: `Score = (Uncertainty * 50) + (ExploitPressure * 50)`
- Uncertainty factors: Missing VEX (+0.40), Missing reachability (+0.30), Conflicting sources (+0.20), Stale advisory (+0.10)
- Exploit pressure factors: In KEV (+0.50), EPSS >= 0.90 (+0.30), EPSS >= 0.50 (+0.15), CVSS >= 9.0 (+0.05)
- `ComputeContainmentReduction(input)` applies blast radius scoring:
- `BlastRadius.Dependents == 0` -> IsolatedReduction (default 15%)
- `BlastRadius.NetFacing == false` -> NotNetFacingReduction (default 5%)
- `BlastRadius.Privilege in ["user", "none"]` -> NonRootReduction (default 5%)
- ContainmentSignals scoring:
- `Seccomp == "enforced"` -> SeccompEnforcedReduction (default 10%)
- `FileSystem == "ro"` -> FsReadOnlyReduction (default 10%)
- `NetworkPolicy == "isolated"` -> NetworkIsolatedReduction (default 5%)
- Max total containment reduction capped at 40%
- Score = decayedScore * (1 - containmentReduction)
- **UnknownRankInput**: Includes `BlastRadius?` and `Containment?` fields for dependency graph impact and runtime containment posture
- **BlastRadius Record**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/BlastRadius.cs` -- `Dependents` (int), `NetFacing` (bool), `Privilege` (string?)
- **ContainmentSignals Record**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/ContainmentSignals.cs` -- `Seccomp`, `FileSystem`, `NetworkPolicy`
- **Band Assignment**: Hot >= 75, Warm >= 50, Cold >= 25, else Resolved (configurable via `UnknownRankerOptions`)
- **Decay Buckets**: Time-based score decay using basis points: 7d=100%, 30d=90%, 90d=75%, 180d=60%, 365d=40%, >365d=20%
- **Reason Codes**: `DetermineReasonCode` returns most actionable reason: AnalyzerLimit, Reachability, Identity, Provenance, VexConflict, FeedGap, ConfigUnknown
- **Remediation Hints**: `RemediationHintsRegistry` provides short remediation hints per reason code
## E2E Test Plan
- [ ] Rank unknown with isolated blast radius (Dependents=0, NetFacing=false, Privilege="none"); verify 25% containment reduction applied (15+5+5)
- [ ] Rank unknown with exposed blast radius (Dependents=100, NetFacing=true, Privilege="root"); verify 0% containment reduction
- [ ] Rank unknown with mixed signals (isolated but network-facing); verify only IsolatedReduction (15%) applied
- [ ] Rank unknown with full containment (blast radius + runtime signals); verify capped at MaxContainmentReduction (40%)
- [ ] Verify score 80 with 25% containment reduction produces final score of 60 (80 * 0.75)
- [ ] Verify HOT band unknown (score 80) drops to WARM band (score 60) after blast radius reduction
- [ ] Verify reason code is AnalyzerLimit when `IsAnalyzerSupported=false`
- [ ] Verify reason code is Reachability when `HasReachabilityData=false`
- [ ] Verify decay factor applied: unknown last evaluated 90 days ago gets 75% multiplier (7500 bps)
- [ ] Verify containment reduction is 0 when `EnableContainmentReduction=false`

View File

@@ -0,0 +1,47 @@
# CI/CD Gate Exit Code Convention
## Module
Policy
## Status
IMPLEMENTED
## Description
Standardized CI exit code convention for gate evaluation: 0=Pass, 1=Warn (configurable pass-through), 2=Fail/Block, 10+=errors. The `stella gate evaluate` CLI command returns these exit codes, enabling direct CI/CD pipeline integration without parsing output.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- `PolicyGateEvaluator` (sealed class implements `IPolicyGateEvaluator`)
- Sprint: SPRINT_20251226_001_BE_cicd_gate_integration
- `EvaluateAsync(PolicyGateRequest)` returns `PolicyGateDecision` with decision type: Allow, Warn, Block
- Evaluates gates in sequence: Evidence Completeness -> Lattice State -> VEX Trust -> Uncertainty Tier -> Confidence Threshold
- Short-circuits on first Block (subsequent gates skipped)
- Override support: `AllowOverride` with `OverrideJustification` and minimum length validation
- **PolicyGateDecision**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateDecision.cs` -- decision model
- `PolicyGateDecisionType`: Allow, Warn, Block
- Contains: GateId, RequestedStatus, Subject, Evidence, Gates (array of results), Advisory, BlockedBy, BlockReason, Suggestion
- **PolicyGateResultType**: Pass, PassWithNote, Warn, Block, Skip -- per-gate evaluation outcomes
- **Exit Code Mapping** (CLI integration):
- Allow -> exit 0 (CI pass)
- Warn -> exit 1 (CI configurable: pass-through or soft fail)
- Block -> exit 2 (CI hard fail)
- Error/Exception -> exit 10+ (CI infrastructure error)
- **Gate Types**:
- Evidence Completeness Gate: requires graphHash (DSSE-attested) and pathAnalysis for not_affected
- Lattice State Gate: checks lattice state compatibility (CU allows not_affected; SR/RO/CR block not_affected)
- VEX Trust Gate: minimum composite score and signature verification per environment
- Uncertainty Tier Gate: T1 blocks not_affected, T2 warns, T3 note, T4 pass
- Confidence Threshold Gate: warns below min confidence for not_affected
- **PolicyGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateOptions.cs` -- configuration for gate thresholds
- **CLI Gate Command**: `src/Cli/StellaOps.Cli/Commands/` -- `stella gate evaluate` translates decision type to process exit code
- **Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/PolicyDecisionEndpoint.cs` -- HTTP API for gate evaluation
## E2E Test Plan
- [ ] Run `stella gate evaluate` with a passing scenario (all evidence present, CU lattice state, T4 uncertainty); verify exit code 0
- [ ] Run `stella gate evaluate` with a warning scenario (SU lattice state for not_affected); verify exit code 1
- [ ] Run `stella gate evaluate` with a blocking scenario (no graphHash for not_affected); verify exit code 2
- [ ] Run `stella gate evaluate` with invalid input (missing required arguments); verify exit code >= 10
- [ ] POST to policy decision endpoint with Block decision; verify response includes `blockedBy`, `blockReason`, and `suggestion`
- [ ] POST with `AllowOverride=true` and valid justification; verify overridden Block becomes Warn with advisory message
- [ ] POST with `AllowOverride=true` but justification too short; verify Block is not overridden
- [ ] Verify VEX Trust gate returns Block when trust score below threshold for production environment
- [ ] Verify CI pipeline integration: use exit code in `if` statement to gate deployment

View File

@@ -0,0 +1,50 @@
# ClaimScore Merger and Policy Gate Registry
## Module
Policy
## Status
IMPLEMENTED
## Description
Implements a lattice-based ClaimScore merger with conflict penalization, plus four specialized policy gates (MinimumConfidenceGate, UnknownsBudgetGate, SourceQuotaGate, ReachabilityRequirementGate) registered through a PolicyGateRegistry. Distinct from existing "Policy Gates (G0-G4)" which is about gate levels; this is the trust lattice merge algebra and specific claim-score-aware gate implementations.
## Implementation Details
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs` -- `ClaimScoreMerger` (sealed class implements `IClaimScoreMerger`)
- Sprint: SPRINT_7100_0002_0001_policy_gates_merge
- `Merge(scoredClaims, policy, ct)` -- deterministic merge of scored VEX claims
- Ordering: descending adjusted score -> descending specificity (if enabled) -> descending original score -> source ID (ordinal) -> insertion index
- First claim in ordered list is the winner; all others marked non-accepted
- Produces `MergeResult`: Status, Confidence (clamped 0-1), HasConflicts, AllClaims, WinningClaim, Conflicts, RequiresReplayProof
- **ConflictPenalizer**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ConflictPenalizer.cs` -- applies conflict penalties
- Default penalty: 0.25 -- applied to claims with conflicting VEX statuses
- Detects conflicts when multiple distinct VEX statuses exist across claims
- **MergePolicy**: configurable options for merge behavior
- `ConflictPenalty` (double, default 0.25) -- score reduction for conflicting claims
- `PreferSpecificity` (bool, default true) -- tiebreak by ScopeSpecificity
- `RequireReplayProofOnConflict` (bool, default true) -- set RequiresReplayProof flag when conflicts detected
- **VexClaim Model**: SourceId, VexStatus, ScopeSpecificity, IssuedAt, StatementDigest, Reason
- **ClaimScoreResult Model**: Score, BaseTrust, StrengthMultiplier, FreshnessMultiplier
- **ScoredClaim Model**: SourceId, Status, OriginalScore, AdjustedScore, ScopeSpecificity, Accepted, Reason
- **ConflictRecord Model**: SourceId, Status, ConflictsWithSourceId, Reason
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- evaluates policy gates in sequence
- Evidence Completeness Gate: requires DSSE-attested graphHash and path analysis for not_affected
- Lattice State Gate: validates reachability lattice compatibility with requested VEX status
- VEX Trust Gate: minimum composite score and signature verification per environment with configurable thresholds
- Uncertainty Tier Gate: T1/T2/T3/T4 tier compatibility with VEX status transitions
- Confidence Threshold Gate: warns below configurable minimum confidence
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` -- dedicated VEX trust gate with metrics
- **StabilityDampingGate**: `src/Policy/StellaOps.Policy.Engine/Gates/StabilityDampingGate.cs` -- stability damping for gate decisions
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs` -- drift-based gate evaluation
## E2E Test Plan
- [ ] Merge two claims with same VEX status; verify no conflicts and winning claim has highest score
- [ ] Merge two claims with different VEX statuses; verify HasConflicts=true and ConflictPenalty applied to adjusted scores
- [ ] Merge three claims with two conflicting statuses; verify penalty applied to minority-status claims
- [ ] Merge with PreferSpecificity=true; verify higher ScopeSpecificity wins when scores are equal
- [ ] Merge empty claims list; verify result has Status=UnderInvestigation, Confidence=0, no conflicts
- [ ] Merge with RequireReplayProofOnConflict=true and conflicts present; verify RequiresReplayProof=true
- [ ] Evaluate policy gate with passing evidence for not_affected; verify Allow decision
- [ ] Evaluate policy gate with missing graphHash for not_affected; verify Block decision with suggestion to submit DSSE-attested call graph
- [ ] Evaluate VEX Trust gate below threshold for production; verify Block; same score passes for development environment
- [ ] Verify deterministic merge ordering: same inputs always produce same winner regardless of input order

View File

@@ -0,0 +1,48 @@
# Comprehensive Testing Strategy (Epic 5100)
## Module
Policy
## Status
IMPLEMENTED
## Description
The testing strategy advisory was translated into Epic 5100 with 12 sprints covering run manifests, evidence indexes, offline bundles, golden corpus, canonicalization, replay runners, delta verdicts, SBOM interop, no-egress enforcement, unknowns budget CI gates, router chaos, and audit pack export/import. Implementation evidence exists for all major themes.
## Implementation Details
- **Determinism Guards**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/` -- determinism verification infrastructure
- Ensures policy evaluation produces identical results given identical inputs
- Hash-based comparison of evaluation outputs across runs
- **Replay Infrastructure**: `src/Policy/__Libraries/StellaOps.Policy/Replay/` -- replay verdict evaluation
- Knowledge snapshot capture and replay for deterministic verdict reproduction
- Snapshot manifests for full evaluation state serialization
- **Simulation Services**: `src/Policy/StellaOps.Policy.Engine/Simulation/` -- risk simulation with breakdowns
- `RiskSimulationService`, `SimulationAnalyticsService`, `RiskSimulationBreakdownService`
- Simulation comparison and trend analysis
- **Delta Verdict Engine**: `src/Policy/StellaOps.Policy.Engine/Evaluation/` -- delta verdict computation
- Incremental evaluation detecting changes between policy versions
- **Unknowns Budget CI Gates**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/UnknownsBudgetEnforcer.cs`
- Budget enforcement with Hot/Warm/Cold band thresholds
- CI gate integration via exit code convention (0=pass, 1=warn, 2=block)
- **Attestation Services**: `src/Policy/StellaOps.Policy.Engine/Attestation/` -- verdict attestation and proof generation
- VerdictAttestationService, PolicyDecisionAttestationService
- DSSE-signed attestation bundles
- **Batch Evaluation**: `src/Policy/StellaOps.Policy.Engine/BatchEvaluation/` -- batch context and exception loading
- `BatchEvaluationModels.cs`, `BatchExceptionLoader.cs`
- **Console Export**: `src/Policy/StellaOps.Policy.Engine/ConsoleExport/` -- audit pack export/import
- `ConsoleExportJobService`, `ConsoleExportModels`, `IConsoleExportJobStore`
- **Verification Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/VerifyDeterminismEndpoints.cs` -- determinism verification API
- **CVSS Receipt Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/CvssReceiptEndpoints.cs` -- CVSS scoring receipts
- **Test Infrastructure**: `src/__Tests/` -- test projects covering policy evaluation, gates, simulation, and unknowns
## E2E Test Plan
- [ ] Run policy evaluation twice with identical inputs; verify determinism guard produces matching hashes
- [ ] Capture a knowledge snapshot; replay it; verify verdict matches original evaluation
- [ ] Run batch evaluation with multiple artifacts; verify all findings are processed and budget checked
- [ ] Run simulation comparison between two policy versions; verify delta summary shows added/removed/regressed findings
- [ ] Export audit pack via console export; re-import and verify all evidence artifacts are present
- [ ] Run unknowns budget check with CI gate; verify exit code 0 when within budget, exit code 2 when exceeded
- [ ] POST to determinism verification endpoint with two snapshots; verify diff report
- [ ] Verify CVSS receipt endpoint returns scoring breakdown with attestation reference
- [ ] Run delta verdict evaluation; verify only changed findings are re-evaluated
- [ ] Verify offline bundle contains all evidence needed for air-gap verdict replay

View File

@@ -0,0 +1,43 @@
# Console Simulation Diff (Shadow Gate Visual Output)
## Module
Policy
## Status
IMPLEMENTED
## Description
Console-based simulation diff output for visual comparison of policy simulation results.
## Implementation Details
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs` -- `ConsoleSimulationDiffService` (internal sealed class)
- Schema version: `console-policy-23-001` (POLICY-CONSOLE-23-002)
- `Compute(ConsoleSimulationDiffRequest)` generates deterministic before/after comparison
- Produces severity breakdown (critical/high/medium/low/unknown) for baseline and candidate policy versions
- Delta summary: added, removed, and regressed (escalated severity) finding counts
- Rule impact analysis: per-rule added/removed counts and severity shift tracking (e.g., "medium->high")
- Explain samples: deterministic trace IDs for drill-down investigation
- Budget caps: `MaxFindings` (1-50,000) and `MaxExplainSamples` (0-200) via `ConsoleDiffBudget`
- Deterministic ID generation using SHA-256 hashing of policy version + artifact digest
- All ordering is lexicographic by Ordinal for determinism
- **ConsoleSimulationDiffModels**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffModels.cs` -- request/response DTOs
- `ConsoleSimulationDiffRequest`: BaselinePolicyVersion, CandidatePolicyVersion, ArtifactScope, Budget, EvaluationTimestamp
- `ConsoleSimulationDiffResponse`: SchemaVersion, Summary (Before/After/Delta), RuleImpact, Samples, Provenance
- `ConsoleArtifactScope`: ArtifactDigest, Purl, AdvisoryId
- `ConsoleDiffDelta`: Added, Removed, Regressed
- `ConsoleRuleImpact`: RuleId, Added, Removed, SeverityShifts
- `ConsoleDiffProvenance`: BaselineVersion, CandidateVersion, EvaluationTimestamp
- **SimulationAnalyticsService Integration**: Uses `SimulationAnalyticsService.ComputeDeltaSummary` for severity change detection (escalated counts)
- **Console Simulation Endpoint**: `src/Policy/StellaOps.Policy.Engine/Endpoints/ConsoleSimulationEndpoint.cs` -- REST API for triggering console simulation diffs
## E2E Test Plan
- [ ] POST to console simulation endpoint with baseline and candidate policy versions; verify response contains schema version, summary, rule impact, and samples
- [ ] Verify severity breakdown: before and after both contain counts for all 5 severity levels (critical/high/medium/low/unknown)
- [ ] Verify delta: added count equals findings in candidate but not baseline; removed count is the inverse
- [ ] Verify rule impact: each rule entry shows added, removed, and severity shift details
- [ ] Verify samples: explain trace IDs are deterministic (same inputs produce same trace IDs)
- [ ] POST with MaxFindings=1; verify only 1 finding per policy version in the output
- [ ] POST with MaxExplainSamples=0; verify samples section contains empty arrays
- [ ] POST same request twice; verify identical response (deterministic output)
- [ ] Verify provenance section contains both policy versions and evaluation timestamp
- [ ] POST with multiple artifact scopes; verify findings are ordered by ArtifactDigest (ordinal)

View File

@@ -0,0 +1,43 @@
# Counterfactual Engine (Policy Diff Analysis)
## Module
Policy
## Status
IMPLEMENTED
## Description
Counterfactual engine that computes the difference between current and proposed policy configurations to show what would change.
## Implementation Details
- **CounterfactualEngine**: `src/Policy/__Libraries/StellaOps.Policy/Counterfactuals/CounterfactualEngine.cs` -- `CounterfactualEngine` (sealed class implements `ICounterfactualEngine`)
- `ComputeAsync(finding, verdict, document, scoringConfig, options?, ct)` computes counterfactual paths for a blocked finding
- Returns `CounterfactualResult` with paths to pass when finding is currently blocked
- Returns `AlreadyPassing` result when finding already has Pass verdict
- Five counterfactual path types:
- **VEX path**: simulates finding with `not_affected` VEX status; skipped if already not_affected
- **Exception path**: computes exception effort based on severity (Critical=5, High=4, Medium=3, Low=2)
- **Reachability path**: simulates finding with `reachability:no`; effort varies (2 if unknown, 4 if currently reachable)
- **Version upgrade path**: uses `FixedVersionLookup` delegate to find fixed version; extracts current version from PURL
- **Compensating control path**: suggests compensating controls (effort=4)
- VEX and reachability paths use `PolicyEvaluation.EvaluateFinding` to simulate what-if verdicts
- Tag-based signals: reads `vex:` and `reachability:` prefixed tags from finding
- **CounterfactualOptions**: `src/Policy/__Libraries/StellaOps.Policy/Counterfactuals/CounterfactualEngine.cs` -- options record
- `IncludeVexPaths`, `IncludeExceptionPaths`, `IncludeReachabilityPaths`, `IncludeVersionUpgradePaths`, `IncludeCompensatingControlPaths` (all default true)
- `PolicyAllowsExceptions`, `PolicyConsidersReachability`, `PolicyAllowsCompensatingControls` (all default true)
- `FixedVersionLookup` -- async delegate `(cve, purl, ct) => fixedVersion?` for version upgrade lookup
- **CounterfactualResult**: `src/Policy/__Libraries/StellaOps.Policy/Counterfactuals/CounterfactualResult.cs` -- result model with finding ID and list of `CounterfactualPath`
- **CounterfactualPath**: paths with type, description, and effort rating
- Factory methods: `Vex(currentStatus, cve, effort)`, `Exception(cve, effort)`, `Reachability(current, findingId, effort)`, `VersionUpgrade(current, fixed, purl, effort)`, `CompensatingControl(findingId, effort)`
## E2E Test Plan
- [ ] Compute counterfactuals for a blocked finding with VEX status=affected; verify VEX path suggests not_affected and simulated verdict would pass
- [ ] Compute counterfactuals for a finding already passing; verify AlreadyPassing result with no paths
- [ ] Compute counterfactuals with IncludeVexPaths=false; verify no VEX path in result
- [ ] Compute counterfactuals for a finding with reachability=unknown; verify reachability path with effort=2
- [ ] Compute counterfactuals for a finding with reachability=yes; verify reachability path with effort=4
- [ ] Compute counterfactuals with FixedVersionLookup providing a fixed version; verify version upgrade path with current and fixed versions
- [ ] Compute counterfactuals with FixedVersionLookup returning null; verify no version upgrade path
- [ ] Verify exception path effort: Critical finding has effort=5, Low finding has effort=2
- [ ] Compute counterfactuals with PolicyAllowsExceptions=false; verify no exception path
- [ ] Verify all five path types are present when all options are enabled and applicable

View File

@@ -0,0 +1,44 @@
# CVE-Aware Release Policy Gates (EPSS/KEV/Reachable/Delta/Aggregate)
## Module
Policy
## Status
IMPLEMENTED
## Description
Five specialized CVE-aware policy gates (EpssThresholdGate, KevBlockerGate, ReachableCveGate, CveDeltaGate, ReleaseAggregateCveGate) that use real-time EPSS scores, KEV catalog membership, reachability status, and cross-release delta to make gate decisions. Distinct from existing generic "CVSS Threshold Gate" or "EPSS Threshold Policy Gate" because these are an integrated multi-gate system with OPA/Rego support.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- orchestrates multi-gate evaluation
- Evaluates gates in sequence: Evidence -> Lattice State -> VEX Trust -> Uncertainty Tier -> Confidence
- Short-circuits on first Block; accumulates warnings from non-blocking gates
- Override support with justification requirement
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` -- VEX trust-based gate with per-environment thresholds
- `VexTrustGateOptions`: per-environment `VexTrustThresholds` with MinCompositeScore and RequireIssuerVerified
- `MissingTrustBehavior`: Block, Warn, or Allow when trust data absent
- Trust tiers: VeryHigh >= 0.9, High >= 0.7, Medium >= 0.5, Low >= 0.3, VeryLow < 0.3
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs` -- drift-based gate for cross-release delta
- `DriftGateOptions`: configurable via `DriftGateContext`
- **StabilityDampingGate**: `src/Policy/StellaOps.Policy.Engine/Gates/StabilityDampingGate.cs` -- stability damping for flapping prevention
- `StabilityDampingOptions`: configurable damping parameters
- **PolicyGateDecision Model**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateDecision.cs`
- Decision types: Allow, Warn, Block
- Contains: GateId, Subject (VulnId/Purl/SymbolId/ScanId), Evidence (LatticeState/UncertaintyTier/GraphHash/RiskScore/Confidence), Gates array, Advisory, BlockedBy, BlockReason, Suggestion
- **Reachability Lattice States**: U (Unknown), SR (StaticallyReachable), SU (StaticallyUnreachable), RO (RuntimeObserved), RU (RuntimeUnobserved), CR (ConfirmedReachable), CU (ConfirmedUnreachable), X (Contested)
- **Uncertainty Tiers**: T1 (High), T2 (Medium), T3 (Low), T4 (Negligible)
- **UnknownRanker Integration**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs` -- exploit pressure factors (KEV +0.50, EPSS >= 0.90 +0.30, EPSS >= 0.50 +0.15, CVSS >= 9.0 +0.05)
- **Scoring Integration**: `src/Policy/StellaOps.Policy.Engine/Scoring/` -- profile-aware scoring with EPSS/CVSS/KEV inputs
- **Gate Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/PolicyDecisionEndpoint.cs` -- REST API for gate evaluation
## E2E Test Plan
- [ ] Evaluate gate for not_affected with CU lattice state and T4 uncertainty; verify Allow decision
- [ ] Evaluate gate for not_affected with CR lattice state; verify Block with suggestion to submit unreachability evidence
- [ ] Evaluate gate for not_affected with missing graphHash; verify Block by EvidenceCompleteness gate
- [ ] Evaluate gate with VEX trust score below production threshold; verify Block by VexTrust gate
- [ ] Evaluate gate with VEX trust score above threshold but signature unverified; verify Block when RequireIssuerVerified=true
- [ ] Evaluate gate with T1 uncertainty for not_affected and BlockT1ForNotAffected=true; verify Block by UncertaintyTier gate
- [ ] Evaluate gate with KEV finding using UnknownRanker; verify exploit pressure includes +0.50 KEV factor
- [ ] Evaluate gate with EPSS=0.95; verify exploit pressure includes +0.30 EPSS factor
- [ ] Evaluate gate with override and valid justification; verify Block overridden to Warn with advisory
- [ ] Evaluate gate with Contested (X) lattice state for not_affected; verify Block with suggestion to resolve through triage

View File

@@ -0,0 +1,44 @@
# CVSS v4.0 Environmental Metrics Completion
## Module
Policy
## Status
IMPLEMENTED
## Description
Completes CVSS v4.0 scoring with all Modified Attack/Impact environmental metrics (MAV, MAC, MAT, MPR, MUI, MVC, MVI, MVA, MSC, MSI, MSA). Extends the existing MacroVector scoring engine with environment-specific risk adjustments. Includes receipt-based deterministic scoring and REST endpoints.
## Implementation Details
- **CvssV4Engine**: `src/Policy/StellaOps.Policy.Scoring/Engine/CvssV4Engine.cs` -- `CvssV4Engine` (sealed partial class implements `ICvssV4Engine`)
- Sprint: SPRINT_1227_0013_0002_LB_cvss_v4_environmental
- `ComputeScores(baseMetrics, threatMetrics?, environmentalMetrics?)` computes all score variants:
- CVSS-B (base score only)
- CVSS-BT (base + threat, when ExploitMaturity != NotDefined)
- CVSS-BE (base + environmental, when modified metrics present)
- CVSS-BTE (full: base + threat + environmental)
- `DetermineEffectiveScore` selects the most specific score type available
- MacroVector-based scoring per FIRST CVSS v4.0 specification
- **CvssEnvironmentalMetrics**: Modified metrics covering all attack/impact dimensions:
- Modified Attack metrics: MAV (Attack Vector), MAC (Attack Complexity), MAT (Attack Requirements), MPR (Privileges Required), MUI (User Interaction)
- Modified Impact metrics: MVC (Confidentiality), MVI (Integrity), MVA (Availability), MSC (Subsequent Confidentiality), MSI (Subsequent Integrity), MSA (Subsequent Availability)
- All values default to NotDefined (inherit base metric values)
- **MacroVectorLookup**: `src/Policy/StellaOps.Policy.Scoring/Engine/MacroVectorLookup.cs` -- lookup table for macro vector scoring
- **CvssScores Model**: BaseScore, ThreatScore, EnvironmentalScore, FullScore, EffectiveScore, EffectiveScoreType
- **CvssScoreReceipt**: `src/Policy/StellaOps.Policy.Scoring/CvssScoreReceipt.cs` -- deterministic receipt with input hashes and policy references
- **Receipts**: `src/Policy/StellaOps.Policy.Scoring/Receipts/` -- receipt persistence and generation
- **CVSS Receipt Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/CvssReceiptEndpoints.cs` -- REST API for scoring with receipts
- **CvssMetrics**: `src/Policy/StellaOps.Policy.Scoring/CvssMetrics.cs` -- metric definitions with CVSS v4.0 enums
- **CvssPolicy**: `src/Policy/StellaOps.Policy.Scoring/CvssPolicy.cs` -- policy-driven scoring thresholds
## E2E Test Plan
- [ ] Score a CVSS v4.0 vector with base metrics only; verify CVSS-B score matches FIRST specification
- [ ] Score with environmental metrics (MAV=Network modified to MAV=Local); verify CVSS-BE score is lower than CVSS-B
- [ ] Score with both threat (ExploitMaturity=Attacked) and environmental metrics; verify CVSS-BTE full score computed
- [ ] Score with threat metrics only (no environmental); verify CVSS-BT computed and CVSS-BE is null
- [ ] POST to CVSS receipt endpoint; verify receipt contains input hash, scoring policy reference, and deterministic score
- [ ] Score same vector twice; verify identical scores and matching receipt hashes
- [ ] Score with all Modified metrics set to NotDefined; verify environmental score equals base score
- [ ] Score with MSI=Safety; verify maximum environmental impact applied
- [ ] Verify effective score type selection: CVSS-BTE preferred when all metrics present
- [ ] Verify CvssEngineFactory returns CvssV4Engine for v4.0 vectors

View File

@@ -0,0 +1,48 @@
# CVSS v4.0 Scoring Engine (Multi-Version, Pipeline Integration, Receipts)
## Module
Policy
## Status
IMPLEMENTED
## Description
Full CVSS v4.0 engine with macro vector lookup, multi-version support (v3.x + v4.0), environmental scoring, policy-driven pipeline integration, and threshold gate for blocking promotions. Deterministic receipt system with audit-grade reproducibility (input hashes, policy references, cryptographic binding). Postgres persistence for score receipts. Extensive test coverage.
## Implementation Details
- **CVSS V4 Engine**: `src/Policy/StellaOps.Policy.Scoring/Engine/CvssV4Engine.cs` -- FIRST CVSS v4.0 specification implementation
- MacroVector-based scoring with lookup table
- Base, Threat, Environmental, and Full score computation
- Effective score type selection (most specific available)
- **CVSS V3 Engine**: `src/Policy/StellaOps.Policy.Scoring/Engine/CvssV3Engine.cs` -- CVSS v3.0/v3.1 scoring
- **CVSS V2 Engine**: `src/Policy/StellaOps.Policy.Scoring/Engine/CvssV2Engine.cs` -- legacy CVSS v2.0 scoring
- **CvssEngineFactory**: `src/Policy/StellaOps.Policy.Scoring/Engine/CvssEngineFactory.cs` -- version-aware engine selection
- **CvssVectorInterop**: `src/Policy/StellaOps.Policy.Scoring/Engine/CvssVectorInterop.cs` -- cross-version vector parsing and conversion
- **MacroVectorLookup**: `src/Policy/StellaOps.Policy.Scoring/Engine/MacroVectorLookup.cs` -- v4.0 macro vector distance lookup table
- **CvssMetrics**: `src/Policy/StellaOps.Policy.Scoring/CvssMetrics.cs` -- base, threat, and environmental metric enums
- **CvssPolicy**: `src/Policy/StellaOps.Policy.Scoring/CvssPolicy.cs` -- policy-driven scoring thresholds per environment
- **CvssScoreReceipt**: `src/Policy/StellaOps.Policy.Scoring/CvssScoreReceipt.cs` -- deterministic receipt with input hashes
- **Receipts**: `src/Policy/StellaOps.Policy.Scoring/Receipts/` -- receipt generation and persistence
- **Receipt Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/CvssReceiptEndpoints.cs` -- REST API for CVSS scoring with receipts
- **Scoring Integration**: `src/Policy/StellaOps.Policy.Engine/Scoring/` -- policy engine scoring integration
- `ScoringEngineFactory.cs` -- selects scoring engine based on configuration
- `ProfileAwareScoringService.cs` -- profile-aware scoring
- `ScorePolicyService.cs` -- policy-driven score evaluation
- `SimpleScoringEngine.cs`, `AdvancedScoringEngine.cs`, `ProofAwareScoringEngine.cs` -- scoring engines
- **Schemas**: `src/Policy/StellaOps.Policy.Scoring/Schemas/` -- JSON schemas for scoring models
- **Policies**: `src/Policy/StellaOps.Policy.Scoring/Policies/` -- policy definitions for scoring
- **Models**: `src/Policy/StellaOps.Policy.Scoring/Models/` -- scoring data models
## E2E Test Plan
- [ ] Score a CVSS v4.0 vector string; verify base score matches FIRST specification
- [ ] Score a CVSS v3.1 vector string; verify base score matches NVD reference
- [ ] Score a CVSS v2.0 vector string; verify backward compatibility
- [ ] Use CvssEngineFactory with a v4.0 vector; verify CvssV4Engine is selected
- [ ] Use CvssEngineFactory with a v3.1 vector; verify CvssV3Engine is selected
- [ ] POST to CVSS receipt endpoint with v4.0 vector; verify receipt includes input hash, computed score, and policy reference
- [ ] POST same vector twice; verify receipts have identical input hashes and scores (deterministic)
- [ ] Score v4.0 vector with environmental metrics; verify CVSS-BE score differs from CVSS-B
- [ ] Score v4.0 vector with threat metrics (ExploitMaturity=Attacked); verify CVSS-BT score higher than base
- [ ] Verify CvssVectorInterop can parse both v3.x and v4.0 vector strings
- [ ] Use ProfileAwareScoringService to score a finding; verify scoring profile weights are applied
- [ ] Verify ProofAwareScoringEngine includes proof references in scoring output

View File

@@ -0,0 +1,58 @@
# Declarative Multi-Modal Policy Engine
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy engine with 12+ gate types, trust lattice merge, OPA adapter integration, policy DSL, evidence-weighted scoring, and determinization gates covering CVSS, EPSS, VEX trust, reachability, unknowns, SBOM presence, and signature requirements.
## Implementation Details
- **Policy Evaluator**: `src/Policy/StellaOps.Policy.Engine/Evaluation/PolicyEvaluator.cs` -- core policy evaluation with expression evaluation
- `PolicyExpressionEvaluator.cs` -- evaluates policy expressions against findings
- `PolicyEvaluationContext.cs` -- evaluation context with tenant, snapshot, and environment info
- `VerdictSummary.cs` -- verdict summary generation
- **Policy Gates**: `src/Policy/StellaOps.Policy.Engine/Gates/`
- `PolicyGateEvaluator.cs` -- multi-gate orchestrator with 5 gate stages (Evidence, Lattice, VEX Trust, Uncertainty, Confidence)
- `VexTrustGate.cs` -- VEX trust score and signature verification per environment
- `DriftGateEvaluator.cs` -- drift-based gate for cross-release delta
- `StabilityDampingGate.cs` -- stability damping to prevent flapping
- `IDeterminizationGate.cs` -- interface for determinization gates
- `Gates/Determinization/` -- determinization gate implementations
- **Trust Lattice**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/`
- `TrustLatticeEngine.cs` -- K4 four-valued logic evaluation pipeline
- `ClaimScoreMerger.cs` -- lattice-based merge with conflict penalization
- VEX normalizers for CycloneDX, OpenVEX, CSAF formats
- **Policy DSL**: `src/Policy/StellaOps.PolicyDsl/` -- declarative policy language compiler
- Compiles YAML-based policy definitions into executable evaluation rules
- **Scoring Engines**: `src/Policy/StellaOps.Policy.Engine/Scoring/`
- `SimpleScoringEngine.cs`, `AdvancedScoringEngine.cs`, `ProofAwareScoringEngine.cs`
- `EvidenceWeightedScore/` -- evidence-weighted scoring with proof integration
- `ProfileAwareScoringService.cs` -- risk profile-driven scoring
- `ScoringEngineFactory.cs` -- engine selection based on configuration
- **CVSS Scoring**: `src/Policy/StellaOps.Policy.Scoring/` -- multi-version CVSS engine (v2, v3.x, v4.0)
- **Determinism Guards**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/`
- `DeterminismGuardService.cs` -- runtime determinism enforcement
- `ProhibitedPatternAnalyzer.cs` -- static analysis for non-deterministic patterns
- `GuardedPolicyEvaluator.cs` -- wraps evaluator with determinism checks
- **Policy Compilation**: `src/Policy/StellaOps.Policy.Engine/Compilation/` -- policy pack compilation
- `PolicyCompilationService` -- compiles policy YAML into evaluation bundles
- Endpoints: `PolicyCompilationEndpoints.cs`, `PolicyLintEndpoints.cs`
- **Effective Decision Map**: `src/Policy/StellaOps.Policy.Engine/EffectiveDecisionMap/` -- materialized decision lookup
- **Counterfactuals**: `src/Policy/__Libraries/StellaOps.Policy/Counterfactuals/` -- "what-if" analysis for blocked findings
- **Simulation**: `src/Policy/StellaOps.Policy.Engine/Simulation/` -- risk simulation with breakdowns
- **Unknowns Integration**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/` -- unknowns ranking and budget enforcement
## E2E Test Plan
- [ ] Compile a YAML policy with CVSS threshold, EPSS threshold, and VEX trust gates; verify compiled bundle is valid
- [ ] Evaluate a finding against compiled policy; verify verdict includes gate decisions from all applicable gates
- [ ] Evaluate with VEX trust gate; verify per-environment threshold enforcement (production stricter than development)
- [ ] Evaluate with determinism guard enabled; verify GuardedPolicyEvaluator wraps evaluation and reports no violations
- [ ] Submit policy YAML with wall-clock usage; verify ProhibitedPatternAnalyzer detects violation
- [ ] Evaluate finding with evidence-weighted scoring; verify proof-aware score includes evidence references
- [ ] Evaluate finding with ClaimScoreMerger; verify conflicting claims are penalized and winning claim selected
- [ ] Use counterfactual engine on blocked finding; verify paths to pass are returned
- [ ] POST policy lint endpoint with invalid YAML; verify lint errors returned
- [ ] Compile and evaluate same policy+finding twice; verify deterministic verdict (identical results)

View File

@@ -0,0 +1,48 @@
# Delta Verdict Engine
## Module
Policy
## Status
IMPLEMENTED
## Description
Full delta verdict computation comparing two evaluation states, with signed delta JSON, API endpoints for delta generation, and verdict ID generation.
## Implementation Details
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs` -- `WhatIfSimulationService` (internal sealed class)
- `SimulateAsync(WhatIfSimulationRequest)` computes delta between baseline and simulated evaluation states
- Supports SBOM diffs: add, remove, upgrade, downgrade operations
- Computes `WhatIfDecisionChange`: status_changed, severity_changed, new, removed
- Decision simulation: new components checked against advisory count, VEX override, reachability downgrade
- Upgrade simulation: fixed-all -> allow, remaining advisories -> warn
- Downgrade simulation: with advisories -> deny (higher priority 150)
- `WhatIfSummary`: TotalEvaluated, TotalChanged, NewlyAffected, NoLongerAffected, StatusChanges, SeverityChanges, Impact
- `WhatIfImpact`: risk delta (increased/decreased/unchanged), blocked/warning deltas, recommendation text
- Simulation ID generation: `whatif-{SHA256(seed)[..16]}`
- **WhatIfSimulationModels**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationModels.cs` -- request/response DTOs
- `WhatIfSimulationRequest`: TenantId, BaseSnapshotId, SbomDiffs, DraftPolicy, TargetPurls, IncludeExplanations, Limit, CorrelationId
- `WhatIfSbomDiff`: Purl, Operation, OriginalVersion, NewVersion, AdvisoryIds, VexStatus, Reachability
- `WhatIfDecision`: Status, Severity, RuleName, Priority, HasException
- `WhatIfExplanation`: MatchedRules, Factors, VexEvidence, Reachability
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs` -- deterministic delta diff for console surface
- Before/After severity breakdowns, delta (added/removed/regressed), rule impact, explain samples
- **SimulationAnalyticsService**: `src/Policy/StellaOps.Policy.Engine/Simulation/SimulationAnalyticsService.cs` -- delta summary computation with severity change tracking
- **Effective Decision Map**: `src/Policy/StellaOps.Policy.Engine/EffectiveDecisionMap/` -- materialized baseline decisions for delta comparison
- **Simulation Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/`
- `ConsoleSimulationEndpoint.cs` -- console surface simulation diff
- `OverlaySimulationEndpoint.cs` -- overlay-based simulation
- `RiskSimulationEndpoints.cs` -- risk simulation with breakdowns
- **Attestation**: `src/Policy/StellaOps.Policy.Engine/Attestation/` -- verdict attestation for signed delta output
## E2E Test Plan
- [ ] POST what-if simulation with add component (3 advisories); verify deny decision with severity=high
- [ ] POST what-if simulation with remove component; verify decision=allow and change_type=removed
- [ ] POST what-if simulation with upgrade component fixing all CVEs; verify decision=allow
- [ ] POST what-if simulation with downgrade component with advisories; verify decision=deny with priority 150
- [ ] POST what-if simulation with VEX not_affected override; verify deny overridden to allow
- [ ] POST what-if simulation with unreachable finding; verify deny downgraded to warn
- [ ] Verify delta summary: TotalChanged matches actual number of decision changes
- [ ] Verify impact: risk delta is "increased" when blocked count goes up, "decreased" when it goes down
- [ ] POST with IncludeExplanations=true; verify explanations contain matched rules, SBOM factors, VEX evidence, and reachability
- [ ] POST console simulation diff with two policy versions; verify deterministic before/after severity breakdowns and delta counts

View File

@@ -0,0 +1,48 @@
# Determinism Guards (Runtime Enforcement)
## Module
Policy
## Status
IMPLEMENTED
## Description
Runtime enforcement of determinism constraints during policy evaluation. Prohibited pattern analysis detects wall-clock, RNG, and network usage. A guarded evaluator wraps the policy engine.
## Implementation Details
- **DeterminismGuardService**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/DeterminismGuardService.cs` -- `DeterminismGuardService` (sealed class)
- `AnalyzeSource(sourceCode, fileName?)` performs static analysis for determinism violations
- `CreateScope(scopeId, evaluationTimestamp)` creates a guarded execution scope with frozen time
- `ValidateContext<TContext>(context, contextName)` validates evaluation context for determinism
- Combines static analysis (`ProhibitedPatternAnalyzer`) and runtime monitoring (`RuntimeDeterminismMonitor`)
- `DeterminismGuardOptions.Default` provides default configuration
- `EnforcementEnabled` controls whether violations cause failures or just warnings
- `FailOnSeverity` threshold for when violations become blocking
- **ProhibitedPatternAnalyzer**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/ProhibitedPatternAnalyzer.cs` -- static code analysis
- Regex-based pattern detection on source code lines
- Detects: wall-clock access (DateTime.Now, DateTimeOffset.Now), RNG usage (Random, Guid.NewGuid), network calls, file I/O
- Line-by-line scanning with line number tracking
- Skips comments (// and /* ... */)
- Reports: violation category, type, message, source file, line number, member context, severity, remediation
- File exclusion via `ExcludePatterns` in options
- `DeterminismViolationCategory`: WallClock, RandomNumber, NetworkAccess, FileSystem, Other
- `DeterminismViolationSeverity` enumeration for graduated enforcement
- **GuardedPolicyEvaluator**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/GuardedPolicyEvaluator.cs` -- wraps policy evaluator with determinism checks
- Pre-evaluation: validates context and checks for violations
- Post-evaluation: verifies no runtime determinism violations occurred during evaluation
- **DeterminismViolation**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/DeterminismViolation.cs` -- violation model
- Category, ViolationType, Message, SourceFile, LineNumber, MemberName, Severity, Remediation
- **DeterminismAnalysisResult**: Passed (bool), Violations (ImmutableArray), CountBySeverity, AnalysisDurationMs, EnforcementEnabled
- **Verification Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/VerifyDeterminismEndpoints.cs` -- REST API for determinism verification
## E2E Test Plan
- [ ] Analyze source code with `DateTime.Now` usage; verify WallClock violation detected with line number and remediation suggestion
- [ ] Analyze source code with `Random()` usage; verify RandomNumber violation detected
- [ ] Analyze clean source code (using TimeProvider, IGuidProvider); verify no violations and Passed=true
- [ ] Analyze source code with violations in comments; verify comments are skipped and no false positives
- [ ] Create guarded scope with frozen timestamp; verify evaluation uses frozen time not wall clock
- [ ] Evaluate with GuardedPolicyEvaluator; verify pre-evaluation and post-evaluation determinism checks pass
- [ ] Set EnforcementEnabled=false; verify violations are reported but Passed=true
- [ ] Set FailOnSeverity=Error; verify Warning-level violations do not cause failure
- [ ] POST to determinism verification endpoint with policy source; verify analysis result with violation counts by severity
- [ ] Analyze with ExcludePatterns matching test files; verify excluded files are skipped

View File

@@ -0,0 +1,45 @@
# Deterministic Evaluation with Knowledge Snapshots
## Module
Policy
## Status
IMPLEMENTED
## Description
Deterministic evaluation engine that pins all inputs via knowledge snapshot digests and can replay evaluations offline with identical results.
## Implementation Details
- **Knowledge Snapshot Manifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs` -- manifest containing all input digests
- Captures: SBOM digest, advisory feed digest, policy bundle digest, VEX document digests, reachability graph digest
- Content-addressed snapshot ID via `SnapshotIdGenerator.cs`
- **SnapshotBuilder**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotBuilder.cs` -- fluent builder for constructing knowledge snapshots
- **SnapshotAwarePolicyEvaluator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotAwarePolicyEvaluator.cs` -- evaluator that pins inputs to snapshot
- Evaluation uses frozen state from snapshot (no live data fetching)
- Results are reproducible: same snapshot always produces same verdicts
- **SnapshotIdGenerator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotIdGenerator.cs` -- deterministic ID from snapshot content
- **KnowledgeSourceDescriptor**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSourceDescriptor.cs` -- describes a knowledge source (type, URI, digest, timestamp)
- **SnapshotService (Library)**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotService.cs` -- snapshot lifecycle management
- **SnapshotService (Engine)**: `src/Policy/StellaOps.Policy.Engine/Snapshots/SnapshotService.cs` -- engine-level snapshot operations
- **SnapshotStore**: `src/Policy/StellaOps.Policy.Engine/Snapshots/SnapshotStore.cs` -- snapshot persistence
- **SnapshotModels**: `src/Policy/StellaOps.Policy.Engine/Snapshots/SnapshotModels.cs` -- snapshot DTOs
- **Replay Engine**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayEngine.cs` -- replays evaluation from snapshot
- `ReplayRequest.cs` -- replay parameters including snapshot reference
- `ReplayResult.cs` -- replay outcome with verdict comparison
- `VerdictComparer.cs` -- compares original and replayed verdicts for drift detection
- `ReplayReport.cs` -- detailed replay report with match/mismatch analysis
- `KnowledgeSourceResolver.cs` -- resolves snapshot references to evaluation inputs
- **Snapshot Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/SnapshotEndpoint.cs`, `SnapshotEndpoints.cs`, `PolicySnapshotEndpoints.cs` -- REST API for snapshot CRUD
- **Determinism Guards Integration**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/` -- ensures no wall-clock or RNG leaks into snapshot-pinned evaluation
## E2E Test Plan
- [ ] Build a knowledge snapshot with SBOM, advisory feed, and policy bundle digests; verify snapshot ID is content-addressed
- [ ] Evaluate finding using SnapshotAwarePolicyEvaluator with pinned snapshot; verify deterministic verdict
- [ ] Re-evaluate same snapshot; verify identical verdict (byte-for-byte match)
- [ ] Replay evaluation from snapshot using ReplayEngine; verify VerdictComparer shows no drift
- [ ] Modify advisory feed and replay with original snapshot; verify replay uses original feed (not modified)
- [ ] POST snapshot to snapshot endpoint; verify snapshot is persisted and retrievable by ID
- [ ] Verify KnowledgeSourceDescriptor contains type, URI, digest, and timestamp for each source
- [ ] Build snapshot with SnapshotBuilder; verify manifest contains all expected source descriptors
- [ ] Replay evaluation with intentionally modified policy; verify VerdictComparer detects mismatch
- [ ] Verify snapshot ID changes when any input digest changes

View File

@@ -0,0 +1,51 @@
# Deterministic SBOM-to-VEX Pipeline with Signed State Transitions
## Module
Policy
## Status
IMPLEMENTED
## Description
Full verdict pipeline determinism tests, SBOM determinism validation, determinism gate infrastructure, baseline store, and manifest writer for verifying byte-identical outputs from identical inputs.
## Implementation Details
- **Determinization Gate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs` -- determinization gate implementation
- `ISignalSnapshotBuilder` interface for building signal snapshots
- `SignalSnapshotBuilder.cs` -- builds signal snapshots for deterministic evaluation
- `DeterminizationGateMetrics.cs` -- metrics tracking for determinization gates
- **Determinism Guard Service**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/DeterminismGuardService.cs`
- Static analysis via `ProhibitedPatternAnalyzer` detects non-deterministic patterns
- Runtime monitoring via `RuntimeDeterminismMonitor`
- `GuardedPolicyEvaluator` wraps evaluation with pre/post determinism checks
- **Determinization Library**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/`
- `DeterminizationOptions.cs` -- configuration for determinization behavior
- `IDeterminizationConfigStore.cs` -- persisted configuration for reanalysis rules
- `Evidence/` -- evidence models for determinization decisions
- `Models/` -- determinization data models
- `Scoring/` -- scoring models for determinization
- **Knowledge Snapshot Pipeline**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/`
- `KnowledgeSnapshotManifest.cs` -- pins all inputs (SBOM, feeds, policy) via digests
- `SnapshotAwarePolicyEvaluator.cs` -- evaluates against frozen snapshot state
- `SnapshotIdGenerator.cs` -- content-addressed snapshot IDs
- **VEX State Transitions**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Validates VEX status transitions (not_affected, affected, under_investigation, fixed)
- Requires DSSE-attested graphHash and path analysis for not_affected transitions
- **Attestation Services**: `src/Policy/StellaOps.Policy.Engine/Attestation/`
- `VerdictAttestationService.cs` -- signs verdict decisions with DSSE
- `PolicyDecisionAttestationService.cs` -- signs policy decisions
- `ScoringDeterminismVerifier.cs` -- verifies scoring determinism
- **Determinism Verification Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/VerifyDeterminismEndpoints.cs`
- **Determinization Config Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/DeterminizationConfigEndpoints.cs`
## E2E Test Plan
- [ ] Run verdict pipeline twice with identical SBOM and advisory inputs; verify byte-identical output digests
- [ ] Build signal snapshot using SignalSnapshotBuilder; verify snapshot captures all evaluation signals
- [ ] Run determinism guard analysis on evaluation code; verify no prohibited patterns detected
- [ ] Modify SBOM input and re-run pipeline; verify output digest changes
- [ ] Verify VEX state transition from under_investigation to not_affected requires graphHash and pathAnalysis evidence
- [ ] Sign verdict with VerdictAttestationService; verify DSSE envelope is valid
- [ ] Verify ScoringDeterminismVerifier detects scoring drift when weights change
- [ ] POST to determinization config endpoint; verify configuration is persisted and retrievable
- [ ] Run determinization gate with signal snapshot; verify gate uses snapshot signals not live data
- [ ] Verify knowledge snapshot manifest contains content-addressed IDs for all input sources

View File

@@ -0,0 +1,39 @@
# Determinization Reanalysis Configuration (Persisted Policy Config)
## Module
Policy
## Status
IMPLEMENTED
## Description
Persisted configuration for the determinization reanalysis pipeline, controlling how grey-queue unknowns are re-evaluated (interval, thresholds, auto-promote rules). Includes API client and backend persistence for policy-driven reanalysis schedules.
## Implementation Details
- **Determinization Config Store**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/IDeterminizationConfigStore.cs` -- interface for persisted configuration
- Sprint: SPRINT_20260112_012_POLICY_determinization_reanalysis_config
- Stores reanalysis interval, scoring thresholds, and auto-promote rules
- **DeterminizationOptions**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/DeterminizationOptions.cs` -- configuration options
- Reanalysis interval (how often grey-queue unknowns are re-evaluated)
- Score thresholds for band transitions (Hot->Warm, Warm->Cold, Cold->Resolved)
- Auto-promote rules for automatic resolution when criteria are met
- **Determinization Evidence**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Evidence/` -- evidence models for reanalysis decisions
- **Determinization Models**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Models/` -- data models for determinization state
- **Determinization Scoring**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Scoring/` -- scoring models for reanalysis
- **Determinization Gate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs`
- Uses persisted configuration to control gate behavior
- Signal snapshot builder captures evaluation state for reproducibility
- **Determinization Config Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/DeterminizationConfigEndpoints.cs` -- REST API for configuration CRUD
- GET/PUT configuration for reanalysis schedules
- Configuration scoped per tenant
- **Service Registration**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/ServiceCollectionExtensions.cs` -- DI registration
## E2E Test Plan
- [ ] GET determinization config endpoint; verify default configuration returned with reanalysis interval and thresholds
- [ ] PUT determinization config with custom reanalysis interval; verify configuration is persisted
- [ ] GET config after PUT; verify updated values are returned
- [ ] Verify determinization gate uses persisted configuration (not hardcoded defaults)
- [ ] Update auto-promote rules; verify unknowns meeting criteria are automatically promoted
- [ ] Update score thresholds; verify band assignment uses new thresholds
- [ ] Verify configuration is tenant-scoped: tenant A config does not affect tenant B
- [ ] Verify DeterminizationOptions default values are applied when no config is persisted

View File

@@ -0,0 +1,42 @@
# Diff-Aware Release Gates (Semantic Delta Computation)
## Module
Policy
## Status
IMPLEMENTED
## Description
Full delta computation engine that computes semantic diffs across SBOMs, vulnerabilities, and risk scores. Includes component deltas, vulnerability status deltas, and risk score deltas.
## Implementation Details
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs` -- computes delta between baseline and hypothetical states
- SBOM diff operations: add, remove, upgrade, downgrade
- Decision changes: status_changed, severity_changed, new, removed
- Risk delta computation: increased/decreased/unchanged with blocked/warning deltas
- VEX and reachability override handling in simulated decisions
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs` -- drift-based gate for cross-release delta
- `DriftGateContext.cs` -- drift evaluation context with base/target references
- `DriftGateOptions.cs` -- configurable drift thresholds
- Evaluates whether drift between releases exceeds acceptable thresholds
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs` -- deterministic delta diff
- Before/After severity breakdown, delta (added/removed/regressed), rule impact analysis
- **SimulationAnalyticsService**: `src/Policy/StellaOps.Policy.Engine/Simulation/SimulationAnalyticsService.cs` -- delta summary computation with severity escalation tracking
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs` -- `CompareProfilesWithBreakdown` for profile-level delta
- Compares baseline and comparison risk profiles with trend analysis
- Top movers analysis: identifies findings with greatest score change
- **Effective Decision Map**: `src/Policy/StellaOps.Policy.Engine/EffectiveDecisionMap/` -- materialized baseline decisions for delta comparison
- **Overlay Simulation**: `src/Policy/StellaOps.Policy.Engine/Endpoints/OverlaySimulationEndpoint.cs` -- overlay-based simulation
- **Merge Preview**: `src/Policy/StellaOps.Policy.Engine/Endpoints/MergePreviewEndpoints.cs` -- merge preview for policy changes
## E2E Test Plan
- [ ] Run what-if simulation with SBOM upgrade; verify component delta shows version change and advisory resolution
- [ ] Run what-if simulation with SBOM downgrade; verify new advisories detected and severity escalated
- [ ] Evaluate drift gate with base and target digests; verify gate passes when drift is within threshold
- [ ] Evaluate drift gate with excessive drift; verify gate blocks with explanation
- [ ] Run console simulation diff; verify severity breakdown before and after policy change
- [ ] Compare two risk profiles; verify trend analysis shows score deltas and top movers
- [ ] Run overlay simulation; verify hypothetical overlay applied without persisting
- [ ] Verify delta summary correctly counts: added, removed, regressed (escalated severity)
- [ ] Run merge preview; verify predicted impact of policy merge
- [ ] Verify what-if summary recommendation: "risk profile increases" when more blocks, "improves" when fewer

View File

@@ -0,0 +1,37 @@
# Dry-Run Policy Application API
## Status
IMPLEMENTED
## Description
Backend support for dry-run policy application with diff preview and rollback plan generation. Not yet implemented.
## Why Marked as Dropped (Correction)
**FINDING: Policy simulation / dry-run IS implemented.** The following exist:
- `src/Policy/StellaOps.Policy.Registry/Services/PolicySimulationService.cs` -- core simulation service
- `src/Policy/StellaOps.Policy.Registry/Services/IPolicySimulationService.cs` -- interface
- `src/Policy/StellaOps.Policy.Registry/Services/BatchSimulationOrchestrator.cs` -- batch simulation support
- `src/Policy/StellaOps.Policy.Registry/Services/IBatchSimulationOrchestrator.cs` -- interface
- `src/Policy/StellaOps.Policy.Registry/Testing/PolicyRegistryTestHarness.cs` -- test harness
- Tools library: `src/__Libraries/StellaOps.Policy.Tools/PolicySimulationSmokeCommand.cs`, `PolicySimulationSmokeModels.cs`, `PolicySimulationSmokeApp.cs`
- Web UI dry-run support: setup wizard includes dry-run functionality per `src/Web/StellaOps.Web/src/app/features/setup-wizard/`
- Database migration support: `src/__Libraries/StellaOps.Infrastructure.Postgres/Migrations/MigrationRunner.cs` has dry-run mode
## Implementation Details
- Simulation service: `src/Policy/StellaOps.Policy.Registry/Services/PolicySimulationService.cs`
- Batch orchestrator: `src/Policy/StellaOps.Policy.Registry/Services/BatchSimulationOrchestrator.cs`
- Smoke test tools: `src/__Libraries/StellaOps.Policy.Tools/PolicySimulationSmoke*.cs`
- Test harness: `src/Policy/StellaOps.Policy.Registry/Testing/PolicyRegistryTestHarness.cs`
## E2E Test Plan
- Verify policy simulation produces expected diff output
- Test batch simulation across multiple policies
- Validate dry-run mode prevents actual policy application
## Source
- Feature matrix scan
## Notes
- Module: Policy
- Modules referenced: `src/Policy/StellaOps.Policy.Registry/`
- **Status should be reclassified from NOT_FOUND to IMPLEMENTED**

View File

@@ -0,0 +1,50 @@
# DSSE-signed reversible decisions (MUTE_REACH, MUTE_VEX, ACK, EXCEPTION)
## Module
Policy
## Status
IMPLEMENTED
## Description
VEX decision signing service produces DSSE-signed decisions; exception objects model scoped, time-boxed exceptions with evidence requirements.
## Implementation Details
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs` -- signs verdict decisions with DSSE envelopes
- `IVerdictAttestationService` interface
- `VerdictPredicate.cs` -- verdict predicate for attestation payload
- `VerdictPredicateBuilder.cs` -- fluent builder for verdict predicates
- `VerdictReasonCode.cs` -- reason codes for verdict decisions
- **PolicyDecisionAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/PolicyDecisionAttestationService.cs` -- signs policy decisions
- `IPolicyDecisionAttestationService` interface
- `PolicyDecisionPredicate.cs` -- decision predicate payload
- `PolicyDecisionAttestationOptions.cs` -- signing options
- **Exception Objects**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionObject.cs` -- scoped, time-boxed exception model
- Scope: CVE-level, package-level, or finding-level
- Time-boxing: ExpiresAt, auto-expire enforcement
- Evidence requirements: required evidence types per exception
- Status: Active, Expired, Revoked
- **Exception Application**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionApplication.cs` -- tracks when exceptions are applied to findings
- **Exception Events**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionEvent.cs` -- audit trail of exception lifecycle events (create, apply, expire, revoke)
- **Evidence Hooks**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/EvidenceHook.cs` -- hooks for evidence validation on exception approval
- **RecheckPolicy**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/RecheckPolicy.cs` -- recheck policy for exception revalidation
- **Exception Evaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs` -- evaluates exception applicability
- **Evidence Requirement Validator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs` -- validates evidence requirements are met
- **Recheck Evaluation Service**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/RecheckEvaluationService.cs` -- periodic recheck of exception validity
- **ExceptionRecheckGate**: `src/Policy/StellaOps.Policy.Engine/BuildGate/ExceptionRecheckGate.cs` -- build gate that rechecks exception validity
- **RVA Service**: `src/Policy/StellaOps.Policy.Engine/Attestation/RvaService.cs` -- Risk Verdict Attestation service
- `RvaBuilder.cs` -- builds RVA attestations
- `RvaVerifier.cs` -- verifies RVA attestation integrity
- `RvaPredicate.cs` -- RVA predicate model
## E2E Test Plan
- [ ] Create an exception with ExpiresAt in the future; verify exception is Active
- [ ] Apply exception to a finding; verify DSSE-signed decision envelope is produced
- [ ] Verify exception application is recorded in ExceptionEvent audit trail
- [ ] Wait for exception expiry; verify ExceptionRecheckGate detects expiration and re-evaluates finding
- [ ] Create exception with evidence requirements; verify EvidenceRequirementValidator blocks approval when evidence missing
- [ ] Verify signed verdict predicate contains: finding ID, CVE, decision, reason code, timestamp
- [ ] Verify PolicyDecisionAttestationService signs decisions with correct predicate payload
- [ ] Revoke an active exception; verify finding is re-evaluated without exception
- [ ] Run RecheckEvaluationService; verify exceptions past recheck policy interval are revalidated
- [ ] Verify RvaService builds and verifies Risk Verdict Attestation with scoring determinism

View File

@@ -0,0 +1,40 @@
# Earned Capacity Replenishment for Risk Budgets
## Module
Policy
## Status
IMPLEMENTED
## Description
Extends Risk Budget Management with automated enforcement: BudgetLedger for tracking risk point consumption, BudgetConstraintEnforcer for policy gate integration, and EarnedCapacityReplenishment for automatically restoring budget when vulnerabilities are remediated. Includes PostgreSQL persistence and REST endpoints. Goes beyond the known "Risk Budget Management" (which covers configuration/dashboard) by adding the enforcement automation and earned capacity mechanism.
## Implementation Details
- **Budget Ledger**: `src/Policy/StellaOps.Policy.Engine/Ledger/`
- Sprint: SPRINT_20251226_002_BE_budget_enforcement
- `LedgerModels.cs` -- ledger entry models for tracking risk point consumption and replenishment
- `LedgerExportService.cs` -- export ledger data for audit
- `LedgerExportStore.cs` -- persistence for ledger exports
- **Budget Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BudgetEndpoints.cs` -- REST API for budget operations
- Budget status, consumption tracking, and replenishment triggers
- **Risk Budget Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskBudgetEndpoints.cs` -- risk budget management API
- Budget configuration, threshold management, and earned capacity rules
- **Unknowns Budget Enforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/UnknownsBudgetEnforcer.cs` -- enforces budget constraints
- Tracks Hot/Warm/Cold band consumption against budget limits
- Blocks releases when budget is exceeded
- **Unknown Budget Service**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownBudgetService.cs` -- budget calculation and management
- **Unknown Budget Model**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/UnknownBudget.cs` -- budget configuration with per-band limits
- **Verdict Budget Check**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictBudgetCheck.cs` -- budget verification during verdict attestation
- **Ledger Export Endpoint**: `src/Policy/StellaOps.Policy.Engine/Endpoints/LedgerExportEndpoint.cs` -- REST API for exporting ledger entries
## E2E Test Plan
- [ ] GET risk budget status; verify budget shows total capacity, consumed points, and remaining capacity
- [ ] Consume risk points by adding a new finding; verify budget consumption increases
- [ ] Remediate a vulnerability; verify earned capacity replenishment restores budget points
- [ ] Exceed budget limit; verify budget enforcer blocks the release gate
- [ ] Verify budget enforcer integrates with policy gate: gate returns Block when budget exceeded
- [ ] Export budget ledger; verify ledger contains all consumption and replenishment entries with timestamps
- [ ] Configure per-band limits (Hot=10, Warm=25, Cold=100); verify enforcement respects band-specific limits
- [ ] Verify verdict attestation includes budget check result
- [ ] POST to risk budget endpoint to update capacity; verify new capacity takes effect
- [ ] Verify earned capacity calculation: remediated critical finding replenishes more points than low finding

View File

@@ -0,0 +1,36 @@
# EPSS Raw Feed Layer (Immutable Storage)
## Module
Policy
## Status
IMPLEMENTED
## Description
EPSS feed ingestion with CSV parsing, repository storage, and enrichment jobs. Database migrations exist for EPSS risk scores storage.
## Implementation Details
- **UnknownRanker Integration**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs` -- uses EPSS scores in exploit pressure calculation
- EPSS >= 0.90: +0.30 exploit pressure factor
- EPSS >= 0.50: +0.15 exploit pressure factor
- `UnknownRankInput.EpssScore` (decimal 0.0-1.0) feeds into scoring
- **Risk Scoring Integration**: `src/Policy/StellaOps.Policy.Engine/Scoring/` -- EPSS scores used in risk profile scoring
- `ProfileAwareScoringService.cs` -- includes EPSS in profile-aware scoring
- `RiskScoringModels.cs` -- risk scoring models with EPSS data
- `RiskScoringTriggerService.cs` -- triggers re-scoring when EPSS data updates
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs` -- EPSS used as a signal in risk simulations
- Categorical signal mapping: EPSS score mapped to signal weight contributions
- **Policy Gate Integration**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- EPSS thresholds used in gate evaluation
- **Staleness Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/StalenessEndpoints.cs` -- feed staleness monitoring
- **Risk Profile Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskProfileEndpoints.cs` -- profiles include EPSS configuration
- **Evidence Weighted Score**: `src/Policy/StellaOps.Policy.Engine/Scoring/EvidenceWeightedScore/` -- EPSS contributes to evidence-weighted scoring
## E2E Test Plan
- [ ] Verify EPSS score (0.95) contributes +0.30 exploit pressure factor in unknown ranking
- [ ] Verify EPSS score (0.50) contributes +0.15 exploit pressure factor
- [ ] Verify EPSS score (0.10) contributes 0 exploit pressure factor (below threshold)
- [ ] Verify risk simulation includes EPSS as a signal with weight contribution
- [ ] Verify risk scoring trigger fires when EPSS data updates
- [ ] Check staleness endpoint for EPSS feed; verify freshness status is reported
- [ ] Verify evidence-weighted score includes EPSS contribution
- [ ] Verify policy gate evaluates EPSS threshold per configuration

View File

@@ -0,0 +1,39 @@
# EPSS Threshold Policy Gate
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy gate that evaluates EPSS probability thresholds to block or allow releases based on configurable risk bands and delta thresholds.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- multi-gate evaluation including EPSS-aware gates
- EPSS thresholds integrated into evidence and confidence gate evaluation
- Gate result types: Pass, PassWithNote, Warn, Block, Skip
- **UnknownRanker EPSS Scoring**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs` -- EPSS exploit pressure
- EPSS >= 0.90: +0.30 (critical exploit likelihood)
- EPSS >= 0.50: +0.15 (significant exploit likelihood)
- CVSS >= 9.0: +0.05 (additional severity factor)
- Combined with KEV status (+0.50) for total exploit pressure
- Exploit pressure feeds into band assignment: Hot >= 75, Warm >= 50, Cold >= 25
- **Risk Profile Scoring**: `src/Policy/StellaOps.Policy.Engine/Scoring/` -- EPSS as scoring signal
- `ScoringProfileService.cs` -- profile configuration includes EPSS weights
- `ScorePolicyService.cs` -- EPSS threshold evaluation per policy
- `IScoringEngine.cs` interface with EPSS-aware implementations
- **CVSS + EPSS Combined Scoring**: `src/Policy/StellaOps.Policy.Scoring/` -- CVSS and EPSS used together
- CVSS provides severity; EPSS provides exploit probability
- Combined score informs gate decisions
- **Risk Budget Integration**: EPSS-driven unknowns affect budget consumption
## E2E Test Plan
- [ ] Configure EPSS threshold gate at 0.80; evaluate finding with EPSS=0.85; verify gate blocks
- [ ] Configure EPSS threshold gate at 0.80; evaluate finding with EPSS=0.50; verify gate allows
- [ ] Verify EPSS + KEV combination: KEV=true with EPSS=0.95 produces exploit pressure 0.80 (0.50+0.30)
- [ ] Verify EPSS + KEV combination: KEV=true with EPSS=0.50 produces exploit pressure 0.65 (0.50+0.15)
- [ ] Verify HOT band assignment for finding with total score >= 75 (high EPSS + high uncertainty)
- [ ] Verify band transition from WARM to HOT when EPSS score increases above 0.90
- [ ] Verify EPSS delta: finding with rising EPSS triggers re-evaluation
- [ ] Verify scoring profile weights EPSS contribution correctly

View File

@@ -0,0 +1,46 @@
# Evidence Freshness and Time-Decay Scoring
## Module
Policy
## Status
IMPLEMENTED
## Description
Evidence freshness calculation with time-decay models and freshness-aware scoring service, matching the advisory's half-life decay model.
## Implementation Details
- **EvidenceTtlEnforcer**: `src/Policy/__Libraries/StellaOps.Policy/Freshness/EvidenceTtlEnforcer.cs` -- `EvidenceTtlEnforcer` (sealed class implements `IEvidenceTtlEnforcer`)
- `CheckFreshness(bundle, asOf)` checks freshness of all evidence in a bundle
- Evidence types checked: Reachability (ComputedAt), CallStack (CapturedAt), VEX (Timestamp), SBOM/Provenance (BuildTime), Boundary (ObservedAt)
- Freshness statuses: Fresh, Warning, Stale
- Overall status: Stale if any stale, Warning if any warning, else Fresh
- Configurable stale action: Warn or Block via `EvidenceTtlOptions.StaleAction`
- `GetTtl(type)` returns TTL for specific evidence type
- `ComputeExpiration(type, createdAt)` computes expiration timestamp
- **EvidenceTtlOptions**: `src/Policy/__Libraries/StellaOps.Policy/Freshness/EvidenceTtlOptions.cs` -- TTL configuration per evidence type
- Per-type TTL durations (e.g., reachability analysis valid for 7 days, VEX for 30 days)
- Configurable staleness action (warn vs block)
- **UnknownRanker Time Decay**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Decay buckets with basis points: 7d=100%, 30d=90%, 90d=75%, 180d=60%, 365d=40%, >365d=20%
- Applied multiplicatively: `decayedScore = rawScore * decayFactor`
- Configurable via `UnknownRankerOptions.DecayBuckets`
- `ComputeDecayFactor(input)` selects bucket based on days since LastEvaluatedAt
- **Evidence Weighted Score**: `src/Policy/StellaOps.Policy.Engine/Scoring/EvidenceWeightedScore/`
- `EvidenceWeightedScoreEnricher.cs` -- enriches findings with evidence-weighted scores
- `ConfidenceToEwsAdapter.cs` -- adapts confidence scores to evidence-weighted format
- `DualEmitVerdictEnricher.cs` -- dual emission for migration period
- `PolicyEvidenceWeightedScoreOptions.cs` -- configurable weights per evidence type
- **Staleness Endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/StalenessEndpoints.cs` -- REST API for checking evidence freshness
## E2E Test Plan
- [ ] Check freshness with all evidence types within TTL; verify overall status is Fresh
- [ ] Check freshness with reachability evidence older than TTL; verify overall status is Stale
- [ ] Check freshness with VEX evidence approaching TTL; verify Warning status
- [ ] Verify GetTtl returns configured TTL for each evidence type
- [ ] Verify ComputeExpiration: evidence created now with 7-day TTL expires in 7 days
- [ ] Rank unknown last evaluated 90 days ago; verify decay factor is 0.75 (7500 bps)
- [ ] Rank unknown last evaluated 365 days ago; verify decay factor is 0.40 (4000 bps)
- [ ] Verify decay disabled when EnableDecay=false (decay factor always 1.0)
- [ ] GET staleness endpoint; verify freshness status for all evidence types
- [ ] Verify evidence-weighted score includes freshness-adjusted confidence

View File

@@ -0,0 +1,41 @@
# Evidence Hooks for Exception Approval
## Module
Policy
## Status
IMPLEMENTED
## Description
Requires specific attestations before exception approval with 7 evidence types (feature flag disabled, backport merged, compensating control, security review, runtime mitigation, WAF rule deployed, custom attestation). Validates evidence freshness (MaxAge), trust score, DSSE signature verification, and schema compliance. Mandatory hooks block approval until satisfied.
## Implementation Details
- **EvidenceHook Model**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/EvidenceHook.cs`
- Sprint: SPRINT_3900_0003_0002_recheck_policy_evidence_hooks
- Evidence types: feature_flag_disabled, backport_merged, compensating_control, security_review, runtime_mitigation, waf_rule_deployed, custom_attestation
- Mandatory flag: blocks exception approval until hook is satisfied
- MaxAge: maximum evidence age for freshness validation
- Trust score threshold: minimum trust score for evidence acceptance
- DSSE signature verification: requires valid signature on evidence attestation
- Schema compliance: validates evidence against expected schema
- **EvidenceRequirementValidator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs`
- Validates all required evidence is present and valid
- Checks freshness (evidence age vs MaxAge)
- Checks trust score against threshold
- Checks DSSE signature verification status
- Returns validation result with per-hook pass/fail status
- **ExceptionObject**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionObject.cs` -- contains evidence hook configuration
- **ExceptionEvaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs` -- evaluates exception with hooks
- **RecheckPolicy**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/RecheckPolicy.cs` -- recheck policy including evidence hook revalidation
## E2E Test Plan
- [ ] Configure exception with mandatory evidence hook (security_review); attempt approval without evidence; verify blocked
- [ ] Provide security_review attestation; verify exception approval succeeds
- [ ] Provide evidence with age exceeding MaxAge; verify freshness validation fails
- [ ] Provide evidence with trust score below threshold; verify trust validation fails
- [ ] Provide evidence without DSSE signature when signature required; verify signature validation fails
- [ ] Configure 3 hooks (2 mandatory, 1 optional); satisfy mandatory hooks only; verify approval succeeds
- [ ] Configure custom_attestation hook with schema; provide non-compliant evidence; verify schema validation fails
- [ ] Verify all 7 evidence types are accepted by the validator
- [ ] Recheck exception after evidence expires (MaxAge exceeded); verify recheck fails
- [ ] Verify EvidenceRequirementValidator returns per-hook pass/fail status in result

View File

@@ -0,0 +1,38 @@
# Evidence Requirement Validation for Exceptions
## Module
Policy
## Status
IMPLEMENTED
## Description
Validates that exceptions include required evidence (attestation IDs, VEX notes, reachability proofs) before approval.
## Implementation Details
- **EvidenceRequirementValidator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs`
- Validates all required evidence is present for exception approval
- Checks: attestation IDs, VEX notes, reachability proofs, security review evidence
- Evidence freshness validation: age vs MaxAge threshold
- Trust score validation: minimum score for evidence acceptance
- DSSE signature verification: validates signed evidence
- Returns detailed validation result with per-requirement status
- **ExceptionObject**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionObject.cs` -- exception model with evidence requirements
- Required evidence types defined per exception scope
- Scopes: CVE-level, package-level, finding-level
- **EvidenceHook**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/EvidenceHook.cs` -- evidence hook configuration
- Mandatory flag, MaxAge, trust score threshold, DSSE requirement
- **ExceptionEvaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs` -- evaluates exception applicability with evidence checks
- **ExceptionApplication**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionApplication.cs` -- tracks exception applications with evidence snapshot
- **Exception Repositories**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Repositories/` -- persistence for exceptions and evidence
## E2E Test Plan
- [ ] Create exception requiring attestation ID; verify validation fails when attestation ID is missing
- [ ] Create exception requiring VEX note; provide valid VEX note; verify validation passes
- [ ] Create exception requiring reachability proof; provide proof; verify validation passes
- [ ] Validate evidence with expired MaxAge; verify freshness check fails
- [ ] Validate evidence with trust score below minimum; verify trust check fails
- [ ] Create exception with multiple required evidence types; provide all; verify validation passes
- [ ] Create exception with multiple required evidence types; omit one; verify validation fails with specific missing requirement
- [ ] Verify ExceptionApplication records the evidence snapshot at time of application
- [ ] Verify exception evaluator checks evidence requirements before determining applicability

View File

@@ -0,0 +1,36 @@
# Exception Application Audit Trail (policy.exception_applications)
## Module
Policy
## Status
IMPLEMENTED
## Description
Records every instance of an exception being applied to a finding in a dedicated `policy.exception_applications` table, capturing exception ID, finding context, original and applied status, purl, vulnerability ID, and evaluation run ID. Exposed via ledger export for compliance.
## Implementation Details
- **ExceptionApplication Model**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionApplication.cs`
- Sealed record with fields: Id (Guid), TenantId, ExceptionId, FindingId, VulnerabilityId, OriginalStatus, AppliedStatus, EffectName, EffectType, EvaluationRunId, PolicyBundleDigest, AppliedAt, Metadata
- `Create()` static factory method enforces non-null ExceptionId/FindingId, accepts deterministic applicationId and appliedAt timestamps
- Metadata stored as `ImmutableDictionary<string, string>` for extensibility
- **IExceptionApplicationRepository**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Repositories/IExceptionApplicationRepository.cs`
- `RecordAsync(application)` -- persists a single application record
- `RecordBatchAsync(applications)` -- bulk persist for batch evaluation
- Query by ExceptionId, FindingId, VulnerabilityId, EvaluationRunId, TimeRange
- `GetStatisticsAsync(tenantId, filter?)` returns `ExceptionApplicationStatistics` (TotalApplications, UniqueExceptions, UniqueFindings, UniqueVulnerabilities, ByEffectType counts, ByAppliedStatus counts, EarliestApplication, LatestApplication)
- `CountAsync(tenantId, filter?)` for total count with optional filter
- `ExceptionApplicationFilter` record supports paging (Limit/Offset), date range (FromDate/ToDate), and field filters
- **PostgresExceptionApplicationRepository**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Repositories/PostgresExceptionApplicationRepository.cs` -- Postgres persistence for the `policy.exception_applications` table
- **ExceptionEvaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs` -- creates ExceptionApplication records when exceptions match findings during policy evaluation
## E2E Test Plan
- [ ] Apply exception to finding; query `GetByExceptionIdAsync(tenantId, exceptionId)`; verify record includes correct ExceptionId, FindingId, OriginalStatus, AppliedStatus, EffectName, EffectType
- [ ] Apply exception with VulnerabilityId; query `GetByVulnerabilityIdAsync(tenantId, vulnId)`; verify record returned with correct VulnerabilityId
- [ ] Apply exception during batch evaluation; verify EvaluationRunId is populated; query `GetByEvaluationRunIdAsync(tenantId, runId)` and verify all applications for that run
- [ ] Apply exception; verify AppliedAt timestamp matches evaluation time (deterministic)
- [ ] Apply exception with PolicyBundleDigest; verify digest is recorded in the application record
- [ ] Call `RecordBatchAsync` with 5 applications; verify all 5 are persisted
- [ ] Call `GetByTimeRangeAsync(tenantId, from, to)` with a range encompassing 3 applications; verify exactly 3 returned
- [ ] Call `GetStatisticsAsync(tenantId)` after 10 applications across 3 exceptions and 5 findings; verify TotalApplications=10, UniqueExceptions=3, UniqueFindings=5, ByEffectType counts sum to 10
- [ ] Call `CountAsync(tenantId, filter)` with EffectType="suppress" filter; verify count matches expected

View File

@@ -0,0 +1,39 @@
# Exception Effect Registry (Type-to-Effect Mapping)
## Module
Policy
## Status
IMPLEMENTED
## Description
Registry mapping (ExceptionType + ExceptionReason) pairs to policy effects (Suppress, Defer, RequireControl). Covers 11 predefined mappings including false_positive, wont_fix, vendor_pending, compensating_control, license_waiver, etc. Extensible via DI configuration with max-duration constraints.
## Implementation Details
- **ExceptionEffectRegistry**: `src/Policy/StellaOps.Policy.Engine/Adapters/ExceptionEffectRegistry.cs` (sealed class implements `IExceptionEffectRegistry`)
- Uses `FrozenDictionary<(ExceptionType, ExceptionReason), PolicyExceptionEffect>` for immutable O(1) lookups
- `GetEffect(type, reason)` returns effect for type+reason pair; falls back to `defer-default` effect if unmapped
- `GetAllEffects()` returns all registered effects
- `GetEffectById(effectId)` returns effect by ID (case-insensitive lookup)
- 8 distinct effect templates: suppress, defer, require-control, downgrade-low, downgrade-medium, defer-vendor, suppress-deprecation, suppress-license
- 40 total mappings across 4 ExceptionTypes (Vulnerability, Policy, Unknown, Component) x 10 ExceptionReasons
- `PolicyExceptionEffectType` enum: Suppress, Defer, Downgrade, RequireControl
- MaxDurationDays per effect: suppress=365, defer=90, require-control=180, downgrade=365, defer-vendor=180, suppress-deprecation=90, suppress-license=365, defer-default=30
- RoutingTemplate per effect for workflow routing (e.g., "deferred-review", "control-verification", "vendor-tracking", "legal-review", "manual-review")
- **ExceptionType enum**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionObject.cs`
- Vulnerability, Policy, Unknown, Component
- **ExceptionReason enum**: same file
- FalsePositive, AcceptedRisk, CompensatingControl, TestOnly, VendorNotAffected, ScheduledFix, DeprecationInProgress, RuntimeMitigation, NetworkIsolation, Other
## E2E Test Plan
- [ ] `GetEffect(Vulnerability, FalsePositive)` returns effect with Id="suppress", Effect=Suppress, MaxDurationDays=365
- [ ] `GetEffect(Vulnerability, CompensatingControl)` returns effect with Id="require-control", Effect=RequireControl, RequiredControlId="compensating-control-verification"
- [ ] `GetEffect(Vulnerability, RuntimeMitigation)` returns effect with Id="downgrade-low", Effect=Downgrade, DowngradeSeverity=Low
- [ ] `GetEffect(Vulnerability, NetworkIsolation)` returns effect with Id="downgrade-medium", DowngradeSeverity=Medium
- [ ] `GetEffect(Vulnerability, ScheduledFix)` returns effect with Id="defer", Effect=Defer, MaxDurationDays=90
- [ ] `GetEffect(Component, DeprecationInProgress)` returns effect with Id="suppress-deprecation", MaxDurationDays=90
- [ ] `GetEffect(Component, Other)` returns effect with Id="suppress-license", RoutingTemplate="legal-review"
- [ ] `GetEffect(Vulnerability, VendorNotAffected)` returns effect with Id="suppress"
- [ ] `GetEffectById("require-control")` returns non-null effect with matching ID
- [ ] `GetAllEffects()` returns exactly 8 distinct effects (suppress, defer, require-control, downgrade-low, downgrade-medium, defer-vendor, suppress-deprecation, suppress-license)
- [ ] Unmapped type/reason pair (if any) returns defer-default with MaxDurationDays=30, RoutingTemplate="manual-review"

View File

@@ -0,0 +1,34 @@
# Exception Recheck Build Gate
## Module
Policy
## Status
IMPLEMENTED
## Description
CI/CD build gate that evaluates recheck policies for all active exceptions on an artifact before deployment. Fails the pipeline if any Block-action conditions are triggered (e.g., EPSS exceeds threshold, KEV flagged). Returns warnings for non-blocking conditions.
## Implementation Details
- **ExceptionRecheckGate**: `src/Policy/StellaOps.Policy.Engine/BuildGate/ExceptionRecheckGate.cs` (sealed class implements `IBuildGate`)
- GateName: `"exception-recheck"`, Priority: 100
- `EvaluateAsync(BuildGateContext)` evaluates all active exceptions for the artifact
- Uses `IExceptionEvaluator` to find matching exceptions, then `IRecheckEvaluationService` to evaluate recheck conditions
- Aggregates blockers (Block, Revoke, RequireReapproval actions) and warnings (Warn action)
- Returns `BuildGateResult` with Passed=false if any blockers exist; Passed=true otherwise
- Message includes blocker details: `"Recheck policy blocking: {details}"`
- **IBuildGate interface**: defined in same file
- `GateName` (string), `Priority` (int), `EvaluateAsync(BuildGateContext, CancellationToken)`
- **BuildGateContext**: record with ArtifactDigest, Environment, Branch, PipelineId, TenantId, EvaluatedAt, and all recheck signal fields (ReachGraphChanged, EpssScore, CvssScore, UnknownsCount, NewCveInPackage, KevFlagged, VexStatusChanged, PackageVersionChanged)
- **BuildGateResult**: record with Passed, GateName, Message, Blockers (`ImmutableArray<string>`), Warnings (`ImmutableArray<string>`)
- **RecheckEvaluationService**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/RecheckEvaluationService.cs` -- evaluates recheck conditions (see exception-recheck-policy-system feature)
## E2E Test Plan
- [ ] Create exception with RecheckPolicy containing EPSSAbove=0.80 (Block action); set EpssScore=0.85 in BuildGateContext; verify EvaluateAsync returns Passed=false with blocker message mentioning EPSS
- [ ] Create exception with RecheckPolicy containing KEVFlagged (Block action); set KevFlagged=true; verify gate returns Passed=false
- [ ] Create exception with no RecheckPolicy; verify gate returns Passed=true with message "All exception recheck policies satisfied"
- [ ] Create exception with RecheckPolicy containing CVSSAbove=9.0 (Warn action); set CvssScore=9.5; verify gate returns Passed=true with 1 warning
- [ ] Create 2 exceptions: one with Block condition triggered, one with Warn condition triggered; verify gate returns Passed=false with 1 blocker and 1 warning
- [ ] Create exception with environment-scoped condition (prod only); evaluate in staging; verify condition does not trigger
- [ ] Create exception with RequireReapproval action triggered; verify it is classified as a blocker (not a warning)
- [ ] Verify gate includes exception ID in blocker/warning messages for traceability

View File

@@ -0,0 +1,52 @@
# Exception Recheck Policy System
## Module
Policy
## Status
IMPLEMENTED
## Description
Auto-invalidation policies for exceptions with 9 condition types (EPSS threshold, CVSS threshold, reachability graph change, unknowns budget, new CVE in package, KEV flagging, expiry proximity, VEX status change, package version change). Actions: Warn, RequireReapproval, Revoke, Block. Environment-scoped conditions with per-condition action overrides.
## Implementation Details
- **RecheckPolicy**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/RecheckPolicy.cs` (sealed record)
- PolicyId, Name, Conditions (`ImmutableArray<RecheckCondition>`), DefaultAction, IsActive, CreatedAt
- **RecheckCondition**: same file (sealed record)
- Type (`RecheckConditionType`), Threshold (decimal?), EnvironmentScope (`ImmutableArray<string>`), Action (per-condition override, nullable), Description
- **RecheckConditionType enum** (9 types):
- `ReachGraphChange` -- reachability graph changes (new paths discovered)
- `EPSSAbove` -- EPSS score exceeds threshold
- `CVSSAbove` -- CVSS score exceeds threshold
- `UnknownsAbove` -- unknown budget exceeds threshold
- `NewCVEInPackage` -- new CVE added to same package
- `KEVFlagged` -- KEV flag set
- `ExpiryWithin` -- exception nearing expiry (days before)
- `VEXStatusChange` -- VEX status changes
- `PackageVersionChange` -- package version changes
- **RecheckAction enum**: Warn (priority 1), RequireReapproval (priority 2), Revoke (priority 3), Block (priority 4)
- **RecheckEvaluationService**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/RecheckEvaluationService.cs` (sealed class implements `IRecheckEvaluationService`)
- `EvaluateAsync(exception, context)` iterates conditions, checks environment scope, evaluates each condition type
- Returns `RecheckEvaluationResult` with IsTriggered, TriggeredConditions, RecommendedAction (highest priority among triggered)
- Environment scoping: condition applies only if EnvironmentScope is empty or contains the evaluation environment
- Per-condition action override: uses condition.Action if set, otherwise falls back to policy DefaultAction
- Action priority ordering: Block (4) > Revoke (3) > RequireReapproval (2) > Warn (1)
- **RecheckEvaluationResult**: sealed record with IsTriggered, TriggeredConditions (`ImmutableArray<TriggeredCondition>`), RecommendedAction, EvaluatedAt, Summary
- **TriggeredCondition**: record with Type, Description, CurrentValue, ThresholdValue, Action
- **ExceptionObject integration**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionObject.cs`
- `RecheckPolicy?` property on ExceptionObject
- `LastRecheckResult?` and `LastRecheckAt?` for tracking last evaluation
- `IsBlockedByRecheck` computed property (triggered + Block action)
- `RequiresReapproval` computed property (triggered + RequireReapproval action)
## E2E Test Plan
- [ ] Configure RecheckPolicy with EPSSAbove=0.80 (Block); provide context with EpssScore=0.85; verify IsTriggered=true, RecommendedAction=Block, TriggeredConditions contains EPSSAbove with CurrentValue=0.85 and ThresholdValue=0.80
- [ ] Configure RecheckPolicy with CVSSAbove=9.0 (Warn); provide context with CvssScore=8.5; verify IsTriggered=false
- [ ] Configure RecheckPolicy with KEVFlagged (Revoke); provide context with KevFlagged=true; verify IsTriggered=true, RecommendedAction=Revoke
- [ ] Configure RecheckPolicy with ExpiryWithin=7 days (Warn); exception expires in 5 days; verify triggered with CurrentValue~5 and ThresholdValue=7
- [ ] Configure RecheckPolicy with 2 conditions: EPSSAbove=0.50 (Warn) and KEVFlagged (Block); trigger both; verify RecommendedAction=Block (highest priority)
- [ ] Configure condition with EnvironmentScope=["prod"]; evaluate in "staging"; verify condition is NOT triggered
- [ ] Configure condition with EnvironmentScope=["prod"]; evaluate in "prod"; verify condition IS triggered
- [ ] Configure condition with per-condition Action=RequireReapproval overriding policy DefaultAction=Warn; verify triggered condition uses RequireReapproval
- [ ] Configure RecheckPolicy with ReachGraphChange condition; provide context with ReachGraphChanged=true; verify triggered
- [ ] Configure all 9 condition types; trigger each one individually; verify each produces correct TriggeredCondition type

View File

@@ -0,0 +1,46 @@
# Exception System (API, Lifecycle, Policy Integration, Evidence-Backed Workflow)
## Module
Policy
## Status
IMPLEMENTED
## Description
Full exception system: CRUD API with query by scope/owner/expiry/environment, auto-expiry with lifecycle state transitions and background workers, policy engine integration (deterministic outcome alteration with recheck gate), and auditable workflow with entity model (scope, subject, evidence refs, expiry), evidence requirement validation, and persistence (Postgres + in-memory).
## Implementation Details
- **ExceptionObject**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionObject.cs` (sealed record)
- Id format: `EXC-{ulid}`, Version (optimistic concurrency), Status, Type, Scope, OwnerId, RequesterId, ApproverIds, CreatedAt, UpdatedAt, ApprovedAt, ExpiresAt (required, max 1 year), ReasonCode, Rationale (min 50 chars), EvidenceRefs (sha256 or attestation URIs), EvidenceRequirements, CompensatingControls, Metadata, TicketRef, RecheckPolicyId, RecheckPolicy, LastRecheckResult, LastRecheckAt
- `IsEffectiveAt(referenceTime)` -- Active status AND not expired
- `HasExpiredAt(referenceTime)` -- referenceTime >= ExpiresAt
- `IsBlockedByRecheck` / `RequiresReapproval` computed properties
- **ExceptionStatus enum**: Proposed -> Approved -> Active -> Expired/Revoked (governed state machine)
- **ExceptionType enum**: Vulnerability, Policy, Unknown, Component
- **ExceptionReason enum**: FalsePositive, AcceptedRisk, CompensatingControl, TestOnly, VendorNotAffected, ScheduledFix, DeprecationInProgress, RuntimeMitigation, NetworkIsolation, Other
- **ExceptionScope**: ArtifactDigest, PurlPattern (wildcards: `pkg:npm/lodash@*`), VulnerabilityId, PolicyRuleId, Environments, TenantId; AND logic for multiple constraints; `IsValid` checks at least one constraint
- **ExceptionEvaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs` (sealed class implements `IExceptionEvaluator`)
- `EvaluateAsync(FindingContext)` -- queries active exceptions by scope, filters by context match (artifact, vuln, PURL pattern, policy rule, environment, tenant), orders by specificity
- `EvaluateBatchAsync(contexts)` -- evaluates multiple findings
- Specificity scoring: ArtifactDigest=100, exact PURL=50, PURL pattern=20, VulnerabilityId=40, PolicyRuleId=30, Environments=10
- PURL wildcard matching via regex conversion
- Returns `ExceptionEvaluationResult` with HasException, MatchingExceptions, PrimaryReason, PrimaryRationale, AllEvidenceRefs
- **EvidenceRequirementValidator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs` -- validates evidence hooks before approval
- **RecheckEvaluationService**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/RecheckEvaluationService.cs` -- 9 recheck condition types
- **Repositories**:
- `IExceptionRepository` / `PostgresExceptionRepository`: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Repositories/`
- `IExceptionApplicationRepository` / `PostgresExceptionApplicationRepository`: same directory -- audit trail persistence
- **ExceptionEffectRegistry**: `src/Policy/StellaOps.Policy.Engine/Adapters/ExceptionEffectRegistry.cs` -- 40 type+reason -> effect mappings
- **ExceptionRecheckGate**: `src/Policy/StellaOps.Policy.Engine/BuildGate/ExceptionRecheckGate.cs` -- CI/CD build gate for recheck policies
## E2E Test Plan
- [ ] Create exception with Type=Vulnerability, Scope=(VulnerabilityId="CVE-2024-1234", PurlPattern="pkg:npm/lodash@*"), Reason=FalsePositive; verify Status=Proposed
- [ ] Approve exception; verify Status transitions to Approved, ApprovedAt is set, ApproverIds populated
- [ ] Activate exception; verify Status=Active; evaluate finding with matching CVE and PURL; verify HasException=true
- [ ] Verify exception with PurlPattern="pkg:npm/lodash@*" matches "pkg:npm/lodash@4.17.21" but not "pkg:npm/underscore@1.0.0"
- [ ] Create two exceptions for same finding: one with ArtifactDigest (specificity=100) and one with VulnerabilityId (specificity=40); verify most specific is PrimaryReason
- [ ] Set exception ExpiresAt to past; call IsEffectiveAt(now); verify returns false; verify EvaluateAsync does not match
- [ ] Create exception with EnvironmentScope=["prod"]; evaluate in "dev"; verify no match
- [ ] Create exception with EvidenceRefs=["sha256:abc"]; verify AllEvidenceRefs in EvaluationResult contains the ref
- [ ] Use EvaluateBatchAsync with 3 FindingContexts; verify dictionary contains entries for indices 0, 1, 2
- [ ] Verify Scope.IsValid returns false when no constraints are set; returns true when VulnerabilityId is set

View File

@@ -0,0 +1,42 @@
# Explainability Testing Framework
## Module
Policy
## Status
IMPLEMENTED
## Description
Explainability testing framework with assertion helpers and verdict rationale rendering, ensuring decisions can be traced back to evidence and assumptions.
## Implementation Details
- **VerdictRationaleRenderer**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/VerdictRationaleRenderer.cs` (sealed class implements `IVerdictRationaleRenderer`)
- `Render(VerdictRationaleInput)` produces structured 4-line rationale with content-addressed RationaleId
- `RenderPlainText(rationale)` produces plain text output (4 lines)
- `RenderMarkdown(rationale)` produces Markdown with headers (Evidence, Policy Clause, Attestations, Decision)
- `RenderJson(rationale)` produces canonical JSON (RFC 8785) via `CanonJson.Serialize`
- Content-addressed ID: `rat:sha256:{hash}` computed from SHA256 of canonical JSON (with empty RationaleId for self-referential hashing)
- **VerdictRationale model**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/VerdictRationale.cs`
- 4-line template structure:
- Line 1 (`RationaleEvidence`): CVE, Component (PURL, name, version, ecosystem), Reachability (vulnerable function, entry point, path summary)
- Line 2 (`RationalePolicyClause`): ClauseId, RuleDescription, Conditions
- Line 3 (`RationaleAttestations`): PathWitness, VexStatements, Provenance (each as AttestationReference with Id, Type, Digest, Summary)
- Line 4 (`RationaleDecision`): Verdict, Score, Recommendation, Mitigation (Action, Details)
- `RationaleInputDigests` for reproducibility: VerdictDigest, PolicyDigest, EvidenceDigest
- SchemaVersion: "1.0"
- **VerdictRationaleInput**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/IVerdictRationaleRenderer.cs`
- Full input record with VerdictRef, Cve, Component, Reachability, PolicyClauseId, PolicyRuleDescription, PolicyConditions, attestation references, Verdict, Score, Recommendation, Mitigation, GeneratedAt, digest fields
- **Property-based tests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/PropertyTests/DeterminismPropertyTests.cs` -- tests determinism of rationale rendering
- **Explainability integration tests**: verify that `Render` followed by `RenderPlainText`, `RenderMarkdown`, and `RenderJson` all produce deterministic output for identical inputs
## E2E Test Plan
- [ ] Render rationale with CVE, component, reachability; verify Evidence.FormattedText contains CVE ID, component name, vulnerable function, entry point
- [ ] Render rationale with policy clause; verify PolicyClause.FormattedText contains ClauseId and conditions
- [ ] Render rationale with path witness and VEX statements; verify Attestations.FormattedText includes both references
- [ ] Render rationale without attestations; verify FormattedText is "No attestations available."
- [ ] Render rationale with score and mitigation; verify Decision.FormattedText includes score value and mitigation action
- [ ] Render same input twice; verify RationaleId is identical (content-addressed determinism)
- [ ] Render different inputs; verify RationaleIds differ
- [ ] RenderMarkdown produces valid Markdown with ## headers for each section
- [ ] RenderJson produces valid JSON parseable by standard JSON parser
- [ ] Verify RationaleId format matches `rat:sha256:{64 hex chars}`

View File

@@ -0,0 +1,38 @@
# Explainability with Proof Extracts
## Module
Policy
## Status
IMPLEMENTED
## Description
Verdict rationale rendering with full explainability system, reachability explanation UI with "why" drawer for interactive proof browsing.
## Implementation Details
- **VerdictRationaleRenderer**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/VerdictRationaleRenderer.cs` (sealed class implements `IVerdictRationaleRenderer`)
- 4-line template rendering with structured evidence, policy clause, attestations, and decision sections
- Evidence section includes reachability details: vulnerable function symbol, entry point, path summary
- Attestation section references: path witnesses (reachability proofs), VEX statements, provenance attestations
- Each attestation includes Id, Type, Digest, and Summary for browsing
- Content-addressed RationaleId (`rat:sha256:{hash}`) enables proof linking
- Multi-format output: PlainText, Markdown, canonical JSON (RFC 8785)
- **VerdictRationale model**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/VerdictRationale.cs`
- `RationaleEvidence` with ComponentIdentity (PURL, name, version, ecosystem) and ReachabilityDetail (VulnerableFunction, EntryPoint, PathSummary)
- `RationaleAttestations` with PathWitness (reachability proof reference), VexStatements (list of VEX attestation references), Provenance
- `RationaleInputDigests` with VerdictDigest, PolicyDigest, EvidenceDigest for full proof chain
- **PolicyExplainTrace**: `src/Policy/StellaOps.Policy.Engine/Materialization/PolicyExplainTrace.cs` -- trace objects for materialized explanations
- **Counterfactual paths**: `src/Policy/__Libraries/StellaOps.Policy/Counterfactuals/CounterfactualEngine.cs` -- "what would fix this" paths linked to rationale
- **Verdict attestation**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs` -- DSSE-signed verdicts that rationale references
## E2E Test Plan
- [ ] Render verdict rationale for finding with reachability proof; verify Evidence section includes vulnerable function symbol and entry point
- [ ] Render rationale with path witness attestation; verify Attestations.PathWitness.Id and Digest are populated
- [ ] Render rationale with 3 VEX statements; verify all 3 appear in Attestations.VexStatements
- [ ] Render rationale with provenance attestation; verify Provenance.Type and Summary are set
- [ ] Verify RenderMarkdown output includes clickable attestation IDs in Attestations section
- [ ] Verify InputDigests.VerdictDigest matches the actual verdict's content digest
- [ ] Verify InputDigests.EvidenceDigest matches the evidence bundle digest
- [ ] Render rationale for finding without reachability; verify Evidence.Reachability is null and FormattedText omits reachability details
- [ ] Verify RenderJson output can be re-parsed and matches original rationale structure
- [ ] Verify content-addressed RationaleId is stable across serialization roundtrips

View File

@@ -0,0 +1,43 @@
# Exponential Confidence Decay for Unknown Reachability (Half-Life Calculator)
## Module
Policy
## Status
IMPLEMENTED
## Description
Exponential half-life decay of confidence scores implemented in DecayedConfidenceCalculator with formula exp(-ln(2) * ageDays / halfLifeDays), configurable half-life (default 14 days), floor value, and metrics emission. Includes ObservationDecay models, uncertainty scoring, signal state tracking, and property-based tests. Integrated into policy determinization gate.
## Implementation Details
- **DecayedConfidenceCalculator**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Scoring/DecayedConfidenceCalculator.cs` (sealed class implements `IDecayedConfidenceCalculator`)
- `Calculate(baseConfidence, ageDays, halfLifeDays=14.0, floor=0.1)` -- applies exponential decay: `max(floor, baseConfidence * exp(-ln(2) * ageDays / halfLifeDays))`
- `CalculateDecayFactor(ageDays, halfLifeDays=14.0)` -- returns raw decay factor clamped to [0.0, 1.0]
- Parameter validation: baseConfidence [0.0-1.0], ageDays >= 0, halfLifeDays > 0, floor [0.0-1.0]
- Metrics emission: `stellaops_determinization_decay_multiplier` histogram with half_life_days and age_days tags
- **ObservationDecay**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Models/ObservationDecay.cs` (sealed record)
- ObservedAt, RefreshedAt, HalfLifeDays (default 14.0), Floor (default 0.35), StalenessThreshold (default 0.50)
- `CalculateDecay(now)` computes current multiplier: `max(Floor, exp(-ln(2) * ageDays / HalfLifeDays))`
- `CheckIsStale(now)` returns true if decay multiplier < StalenessThreshold
- Factory methods: `Create(observedAt, refreshedAt?)`, `Fresh(now)`, `WithSettings(observedAt, refreshedAt, halfLifeDays, floor, stalenessThreshold)`
- Pre-computed fields: AgeDays, DecayedMultiplier, IsStale, LastSignalUpdate
- **DeterminizationOptions**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/DeterminizationOptions.cs` -- global decay configuration
- **DeterminizationContext**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Models/DeterminizationContext.cs` -- evaluation context with observation state
- **DeterminizationResult**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Models/DeterminizationResult.cs` -- result including decayed confidence
- **DeterminizationGate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs` -- policy gate using DecayedConfidenceCalculator
- **Property-based tests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/PropertyTests/DecayPropertyTests.cs` -- FsCheck property tests for decay formula
- **Unit tests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/DecayedConfidenceCalculatorTests.cs`
- **ObservationDecay tests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/Models/ObservationDecayTests.cs`
## E2E Test Plan
- [ ] Calculate decay with baseConfidence=1.0, ageDays=0: verify result=1.0 (no decay)
- [ ] Calculate decay with baseConfidence=1.0, ageDays=14.0, halfLifeDays=14.0: verify result~0.5 (one half-life)
- [ ] Calculate decay with baseConfidence=1.0, ageDays=28.0, halfLifeDays=14.0: verify result~0.25 (two half-lives)
- [ ] Calculate decay with baseConfidence=0.8, ageDays=100.0, halfLifeDays=14.0: verify result=floor (0.1)
- [ ] Calculate decay with custom floor=0.3: verify result never drops below 0.3
- [ ] CalculateDecayFactor with ageDays=7, halfLifeDays=14: verify factor~0.707
- [ ] ObservationDecay.Create with observedAt 30 days ago: verify CheckIsStale(now)=true (decay < 0.50 staleness threshold)
- [ ] ObservationDecay.Fresh(now): verify CalculateDecay(now)=1.0, CheckIsStale(now)=false
- [ ] ObservationDecay.WithSettings(halfLifeDays=7, floor=0.2, stalenessThreshold=0.60): verify custom settings applied
- [ ] Verify DeterminizationGate uses decayed confidence in gate evaluation; stale observation triggers gate warning or block
- [ ] Verify `stellaops_determinization_decay_multiplier` histogram metric is recorded after Calculate() call

View File

@@ -0,0 +1,36 @@
# Gate Bypass Audit Logging
## Module
Policy
## Status
IMPLEMENTED
## Description
Dedicated gate bypass audit system that records who/when/why for any gate override, persisting actor identity, justification text, IP address, and CI context to an audit repository. Includes rate limiting support for bypass abuse prevention.
## Implementation Details
- **PolicyGateEvaluator override support**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Override mechanism integrated into multi-gate evaluation pipeline
- Override requires justification string (non-empty)
- Gate result types include PassWithNote for approved bypasses with audit trail
- Each gate decision is logged with full context (gate name, decision, justification)
- **PolicyGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateOptions.cs` -- gate configuration including override policies
- **ExceptionEffectRegistry**: `src/Policy/StellaOps.Policy.Engine/Adapters/ExceptionEffectRegistry.cs` -- maps exception types to effects with audit trail
- **ExceptionApplication audit**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Models/ExceptionApplication.cs`
- Records every exception application with ExceptionId, FindingId, OriginalStatus, AppliedStatus, EffectName, EffectType, EvaluationRunId, PolicyBundleDigest, AppliedAt, Metadata
- Metadata dictionary supports arbitrary context (IP address, CI pipeline ID, actor identity)
- **IExceptionApplicationRepository**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Repositories/IExceptionApplicationRepository.cs`
- Query by ExceptionId, FindingId, EvaluationRunId, time range for audit review
- Statistics: total applications, unique exceptions/findings/vulnerabilities, breakdowns by effect type and status
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs` -- DSSE-signed attestations for all verdict decisions including bypasses
## E2E Test Plan
- [ ] Apply gate override with justification; verify ExceptionApplication record includes justification in Metadata
- [ ] Apply gate override; verify Metadata contains actor identity, IP address, and timestamp
- [ ] Query `GetByExceptionIdAsync` for override exception; verify full audit trail returned
- [ ] Apply 3 overrides in same evaluation run; query `GetByEvaluationRunIdAsync`; verify all 3 returned
- [ ] Apply override with empty justification; verify override is rejected (justification required)
- [ ] Query `GetStatisticsAsync` after multiple overrides; verify ByEffectType counts include override effects
- [ ] Verify VerdictAttestationService creates DSSE-signed attestation for override decisions
- [ ] Verify override decisions are included in `GetByTimeRangeAsync` query results for compliance export

View File

@@ -0,0 +1,39 @@
# Gate Level Selection (G0-G4)
## Module
Policy
## Status
IMPLEMENTED
## Description
Diff-aware release gate levels G0-G4 with automatic gate selection based on RRS score and budget status, exposed via API endpoints.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Multi-gate evaluation pipeline with 5 sequential gates: Evidence Completeness, Lattice State, VEX Trust, Uncertainty Tier, Confidence Threshold
- Gate result types: Pass, PassWithNote, Warn, Block, Skip
- Short-circuits on first Block; accumulates warnings
- Override support with justification requirements
- Gate decision model: `PolicyGateDecision.cs` with overall decision and per-gate details
- **PolicyGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateOptions.cs` -- configurable gate thresholds and behaviors
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` -- per-environment trust thresholds (prod: 0.80, staging: 0.60, dev: 0.40)
- **DeterminizationGate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs` -- determinism verification gate using DecayedConfidenceCalculator
- **StabilityDampingGate**: `src/Policy/StellaOps.Policy.Engine/Gates/StabilityDampingGate.cs` -- prevents oscillation in gate decisions
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs` -- evaluates SBOM drift for diff-aware gating
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs` -- signal-based scoring that feeds gate selection
- Severity mapping: Critical>=90, High>=70, Medium>=40, Low>=10
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs` -- delta computation for diff-aware gates
- **Gate endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/` -- REST API for gate evaluation results
## E2E Test Plan
- [ ] Evaluate artifact with all evidence present and high confidence; verify all gates pass (G0 level)
- [ ] Evaluate artifact with missing VEX evidence; verify Evidence Completeness gate warns or blocks
- [ ] Evaluate artifact with VEX trust score below production threshold (0.80); verify VexTrustGate blocks in prod
- [ ] Evaluate artifact with VEX trust score 0.65 in staging; verify VexTrustGate passes (threshold 0.60)
- [ ] Evaluate artifact with unknown reachability (U state); verify Lattice State gate applies appropriate action
- [ ] Evaluate artifact with Uncertainty Tier T1 (high uncertainty); verify Uncertainty gate blocks
- [ ] Evaluate artifact with confidence below threshold; verify Confidence gate blocks
- [ ] Override a blocked gate with justification; verify PassWithNote result
- [ ] Evaluate with DriftGateEvaluator detecting SBOM changes; verify drift-aware gating triggers
- [ ] Verify StabilityDampingGate prevents rapid oscillation between Pass and Block

View File

@@ -0,0 +1,44 @@
# Jurisdiction-Specific VEX Trust Rules (US/EU/RU/CN)
## Module
Policy
## Status
IMPLEMENTED
## Description
Configurable jurisdiction-specific trust rules for VEX statements, enabling different trust levels and source preferences for US, EU, Russia, and China regulatory contexts.
## Implementation Details
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` (implements `IVexTrustGate`)
- `EvaluateAsync(VexTrustGateRequest)` evaluates trust score against per-environment thresholds
- VexTrustStatus with TrustScore (0.0-1.0), PolicyTrustThreshold, MeetsPolicyThreshold, TrustBreakdown
- Checks: composite score >= threshold, issuer verification, accuracy rate, freshness
- **VexTrustGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateOptions.cs`
- Per-environment thresholds: production (MinCompositeScore=0.80, RequireIssuerVerified=true, MinAccuracyRate=0.85, FailureAction=Block), staging (0.60, verified, Warn), development (0.40, unverified OK, Warn), default (0.70, verified, Warn)
- `ApplyToStatuses`: ["not_affected", "fixed"]
- `MissingTrustBehavior`: Allow, Warn, or Block when VEX trust data is absent
- `TenantOverrides`: tenant-specific threshold overrides per environment
- Acceptable freshness states per environment (prod: fresh only; dev: fresh, stale, superseded)
- MaxAge per environment (optional time-based freshness)
- FailureAction enum: Warn, Block
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- Three VEX normalizers for different formats: CycloneDX, OpenVEX, CSAF
- Jurisdiction-aware VEX source trust via normalizer selection and claim scoring
- ClaimScoreMerger with conflict penalization for multi-source VEX
- **PolicyGateEvaluator VEX Trust gate**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- VEX Trust gate evaluates per-environment thresholds with MissingTrustBehavior fallback
- Integrated into 5-gate sequential pipeline
- **VexTrustGateMetrics**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateMetrics.cs` -- OpenTelemetry metrics for gate decisions
## E2E Test Plan
- [ ] Configure production threshold MinCompositeScore=0.80; evaluate VEX with score 0.75; verify gate blocks
- [ ] Configure staging threshold MinCompositeScore=0.60; evaluate VEX with score 0.65; verify gate passes
- [ ] Configure production RequireIssuerVerified=true; evaluate unsigned VEX; verify gate blocks
- [ ] Configure development RequireIssuerVerified=false; evaluate unsigned VEX; verify gate passes
- [ ] Configure production MinAccuracyRate=0.85; evaluate issuer with 0.80 accuracy; verify gate warns/blocks
- [ ] Configure production AcceptableFreshness=["fresh"]; evaluate stale VEX; verify gate blocks
- [ ] Configure MissingTrustBehavior=Block; evaluate without VEX trust data; verify gate blocks
- [ ] Configure MissingTrustBehavior=Allow; evaluate without VEX trust data; verify gate passes
- [ ] Configure TenantOverrides with custom thresholds for tenant-A; verify tenant-A uses custom thresholds
- [ ] Verify VexTrustGateMetrics records gate decisions with trust_score, environment, and decision tags

View File

@@ -0,0 +1,46 @@
# Knowledge Snapshot Manifest
## Module
Policy
## Status
IMPLEMENTED
## Description
Knowledge Snapshot Manifest as a content-addressed sealed record containing source descriptors with hashes/digests, policy IDs, engine versions, plugin versions, and trust anchor set hashes.
## Implementation Details
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs` (sealed record)
- SnapshotId: content-addressed `ksm:sha256:{hash}`
- CreatedAt (UTC timestamp)
- Engine: `EngineInfo` record (Name, Version, Commit)
- Plugins: list of `PluginInfo` records (Name, Version, Type)
- Policy: `PolicyBundleRef` record (PolicyId, Digest, Uri)
- Scoring: `ScoringRulesRef` record (RulesId, Digest, Uri)
- Trust: `TrustBundleRef` record (BundleId, Digest, Uri) -- optional
- Sources: list of `KnowledgeSourceDescriptor` -- all knowledge inputs
- Environment: `DeterminismProfile` record (TimezoneOffset, Locale, Platform, EnvironmentVars)
- Signature: optional DSSE signature over the manifest
- ManifestVersion: "1.0"
- **KnowledgeSourceDescriptor**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSourceDescriptor.cs` (sealed record)
- Name, Type ("advisory-feed", "vex", "sbom", "reachability", "policy"), Epoch, Digest, Origin, LastUpdatedAt, RecordCount
- InclusionMode: Referenced (digest only), Bundled (embedded), BundledCompressed
- BundlePath for embedded sources
- Well-known types in `KnowledgeSourceTypes` static class: AdvisoryFeed, Vex, Sbom, Reachability, Policy
- **SnapshotBuilder**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotBuilder.cs` -- fluent builder for constructing snapshots
- **SnapshotIdGenerator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotIdGenerator.cs` -- content-addressed ID generation
- **SnapshotService**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotService.cs` -- snapshot lifecycle management
- **SnapshotAwarePolicyEvaluator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotAwarePolicyEvaluator.cs` -- evaluates policy using pinned snapshot inputs
## E2E Test Plan
- [ ] Build snapshot with 3 knowledge sources (NVD advisory-feed, vendor VEX, SBOM); verify SnapshotId is content-addressed `ksm:sha256:...`
- [ ] Build snapshot; change one source digest; rebuild; verify SnapshotId changes (content-addressed)
- [ ] Build identical snapshot twice; verify SnapshotId is identical (deterministic)
- [ ] Verify Engine field contains correct Name, Version, and Commit
- [ ] Add 2 plugins to snapshot; verify Plugins list contains both with correct Name/Version/Type
- [ ] Set Policy.Digest and Scoring.Digest; verify PolicyBundleRef and ScoringRulesRef are populated
- [ ] Set Trust.BundleId and Trust.Digest; verify TrustBundleRef is populated
- [ ] Add source with InclusionMode=Bundled; verify BundlePath is set
- [ ] Add source with InclusionMode=Referenced; verify BundlePath is null
- [ ] Set Environment DeterminismProfile; verify TimezoneOffset, Locale, Platform are captured
- [ ] Use SnapshotAwarePolicyEvaluator with snapshot; verify evaluation uses pinned source data

View File

@@ -0,0 +1,47 @@
# License Compliance Evaluation Engine
## Module
Policy
## Status
IMPLEMENTED
## Description
Full license compliance evaluation with SPDX expression parsing, license compatibility matrix checking against configurable allow/deny/copyleft lists, attribution report generation, and policy engine integration. While the known list has SPDX license expression parsers in the Attestor writers, this is a distinct policy-engine-integrated compliance evaluator with attribution generation capabilities.
## Implementation Details
- **LicenseComplianceEvaluator**: `src/Policy/__Libraries/StellaOps.Policy/Licensing/LicenseComplianceEvaluator.cs` (sealed class implements `ILicenseComplianceEvaluator`)
- `EvaluateAsync(components, policy)` evaluates license compliance for all components
- SPDX expression parsing via `SpdxLicenseExpressionParser.Parse()`
- License expression evaluation via `LicenseExpressionEvaluator` with compatibility checking
- Exemption support: per-component pattern-based license exemptions
- Obligation tracking: Attribution, SourceDisclosure, PatentGrant, TrademarkNotice
- Overall status: Pass (no issues), Warn (missing/unknown licenses, obligations), Fail (prohibited, copyleft conflict, commercial restriction)
- **LicenseComplianceReport**: `src/Policy/__Libraries/StellaOps.Policy/Licensing/LicenseComplianceModels.cs`
- Inventory: LicenseUsage records with LicenseId, Expression, Category, Components list, Count; ByCategory counts; UnknownLicenseCount; NoLicenseCount
- Findings: LicenseFinding records with Type, LicenseId, ComponentName, ComponentPurl, Category, Message
- Conflicts: LicenseConflict records with conflicting LicenseIds and Reason
- AttributionRequirements: ComponentName, LicenseId, Notices, IncludeLicenseText flag
- **LicenseFindingType enum**: ProhibitedLicense, CopyleftInProprietaryContext, LicenseConflict, UnknownLicense, MissingLicense, AttributionRequired, SourceDisclosureRequired, PatentClauseRisk, CommercialRestriction, ConditionalLicenseViolation
- **LicenseCategory enum**: Unknown, Permissive, WeakCopyleft, StrongCopyleft, Proprietary, PublicDomain
- **Supporting classes**:
- `LicenseKnowledgeBase`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/LicenseKnowledgeBase.cs` -- license metadata database
- `LicenseCompatibilityChecker`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/LicenseCompatibilityChecker.cs` -- compatibility matrix
- `LicenseExpressionEvaluator`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/LicenseExpressionEvaluator.cs` -- evaluates parsed expressions
- `ProjectContextAnalyzer`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/ProjectContextAnalyzer.cs` -- project context for compatibility
- `LicensePolicy` / `LicensePolicyLoader`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/LicensePolicy.cs` / `LicensePolicyLoader.cs` -- policy configuration
- `AttributionGenerator`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/AttributionGenerator.cs` -- NOTICE file generation
- `SpdxLicenseExpressionParser`: `src/Policy/__Libraries/StellaOps.Policy/Licensing/SpdxLicenseExpressionParser.cs` -- SPDX expression parsing
## E2E Test Plan
- [ ] Evaluate component with "MIT" license; verify OverallStatus=Pass, Category=Permissive
- [ ] Evaluate component with "GPL-3.0-only" in proprietary context; verify finding type CopyleftInProprietaryContext, OverallStatus=Fail
- [ ] Evaluate component with prohibited license (in deny list); verify finding type ProhibitedLicense, OverallStatus=Fail
- [ ] Evaluate component with no license data; verify finding type MissingLicense, OverallStatus=Warn
- [ ] Evaluate component with unparseable license expression; verify finding type UnknownLicense
- [ ] Evaluate component with "Apache-2.0 OR MIT" dual license; verify parser resolves expression, one license selected
- [ ] Evaluate 3 components: MIT, GPL-3.0, Apache-2.0; verify Inventory contains all 3 with correct categories and ByCategory counts
- [ ] Evaluate with license requiring attribution; verify AttributionRequirements populated with ComponentName and Notices
- [ ] Configure exemption for component pattern "internal-*" allowing GPL-3.0; verify ProhibitedLicense finding suppressed
- [ ] Evaluate with UnknownLicenseHandling=Deny in policy; verify unknown licenses produce OverallStatus=Fail
- [ ] Evaluate component with conflicting dual licenses; verify LicenseConflict finding with reason

View File

@@ -0,0 +1,41 @@
# NTIA Compliance Validation with Supplier Trust Verification
## Status
IMPLEMENTED
## Description
Sprint described NTIA minimum element compliance checking with supplier trust scoring and regulatory framework mapping (FDA/CISA/EU CRA). No dedicated implementation library found. May have been folded into the SBOM validation layer or deferred despite DONE status in the sprint.
## Why Marked as Dropped (Correction)
**FINDING: NTIA compliance validation IS implemented.** A dedicated namespace exists under `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/`:
- `NtiaBaselineValidator.cs` -- validates NTIA minimum elements baseline compliance
- `NtiaComplianceModels.cs` -- compliance data models
- `NtiaComplianceReporter.cs` -- generates compliance reports
- `RegulatoryFrameworkMapper.cs` -- maps to regulatory frameworks (FDA/CISA/EU CRA)
- `SupplierValidator.cs` -- supplier trust verification
Additional integration:
- CLI integration: `src/Cli/StellaOps.Cli/Commands/SbomCommandGroup.cs` references NTIA compliance
- Policy engine integration: `src/Policy/StellaOps.Policy.Engine/Evaluation/PolicyExpressionEvaluator.cs`, `PolicyEvaluationContext.cs`, `PolicyRuntimeEvaluationService.cs`
- DI registration: `src/Policy/StellaOps.Policy.Engine/DependencyInjection/PolicyEngineServiceCollectionExtensions.cs`
## Implementation Details
- NTIA baseline validator: `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/NtiaBaselineValidator.cs`
- Compliance models: `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/NtiaComplianceModels.cs`
- Compliance reporter: `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/NtiaComplianceReporter.cs`
- Regulatory framework mapper: `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/RegulatoryFrameworkMapper.cs`
- Supplier validator: `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/SupplierValidator.cs`
## E2E Test Plan
- Verify NTIA baseline validation against compliant and non-compliant SBOMs
- Test regulatory framework mapping for FDA, CISA, EU CRA
- Validate supplier trust scoring
- Test CLI SBOM commands include NTIA compliance checks
## Source
- SPRINT_20260119_023_Compliance_ntia_supplier.md
## Notes
- Module: Policy
- Modules referenced: `src/Policy/__Libraries/StellaOps.Policy/NtiaCompliance/`
- **Status should be reclassified from NOT_FOUND to IMPLEMENTED**

View File

@@ -0,0 +1,36 @@
# Path-Scope Simulation Bridge
## Module
Policy
## Status
IMPLEMENTED
## Description
Scoped simulation that evaluates policy changes against specific artifact paths rather than the entire estate.
## Implementation Details
- **PathScopeSimulationEndpoint**: `src/Policy/StellaOps.Policy.Engine/Endpoints/PathScopeSimulationEndpoint.cs` -- REST endpoint for path-scoped simulation
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs`
- `SimulateAsync()` computes baseline vs simulated decisions for targeted artifacts
- SBOM diff operations (add/remove/upgrade/downgrade) scoped to specific artifact paths
- Decision changes: status_changed, severity_changed, new, removed
- Impact summary: risk delta (increased/decreased/unchanged), blocked/warning deltas, recommendations
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs`
- `SimulateWithBreakdown()` -- full simulation with severity distribution and top movers
- `CompareProfilesWithBreakdown()` -- profile comparison with delta analysis
- Signal-based scoring for targeted paths
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs`
- Schema version: console-policy-23-001
- Deterministic before/after severity breakdowns for scoped paths
- **OverlaySimulationEndpoint**: `src/Policy/StellaOps.Policy.Engine/Endpoints/OverlaySimulationEndpoint.cs` -- overlay simulation for policy rule changes
## E2E Test Plan
- [ ] POST path-scope simulation for specific artifact digest; verify simulation results scoped to that artifact only
- [ ] Simulate adding a component to a specific path; verify delta shows new findings for that path
- [ ] Simulate removing a component from a specific path; verify delta shows removed findings
- [ ] Simulate upgrade on path A; verify path B findings are unchanged in delta
- [ ] Verify simulation response includes before/after severity breakdowns for the scoped path
- [ ] Verify simulation response includes risk delta (increased/decreased/unchanged)
- [ ] Verify simulation response includes top movers within the scoped path
- [ ] Verify console simulation diff produces deterministic output for same inputs

View File

@@ -0,0 +1,44 @@
# Policy Bundles with Proof Objects
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy bundles with proof objects, security atoms, claims, and subjects forming the trust lattice algebra substrate.
## Implementation Details
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- Pipeline: VEX normalization -> claim ingestion -> K4 evaluation -> disposition selection -> proof bundle generation
- `Evaluate()` returns TrustLatticeResult with proof bundle containing all claims, evidence, and K4 lattice evaluations
- Proof bundle includes: claims with scores, VEX sources, reachability signals, K4 lattice values per subject
- Claims built via fluent ClaimBuilder: Assert, Present, Applies, Reachable, Mitigated, Fixed, Misattributed
- **K4Lattice**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/K4Lattice.cs`
- Four-valued logic (Unknown=0, True=1, False=2, Conflict=3)
- Algebraic operations: Join (T join F = Conflict), Meet (T meet F = Unknown), Negate, LessOrEqual
- `FromSupport()` converts evidence support to K4 value
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs`
- Deterministic merge with conflict penalization (0.25 penalty)
- Ordering: adjusted score -> specificity -> original score -> source ID -> index
- Returns MergeResult with winning claim, conflicts, RequiresReplayProof flag
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs`
- Content-addressed bundle capturing all policy evaluation inputs
- PolicyBundleRef (PolicyId, Digest, Uri) for bundle identification
- ScoringRulesRef, TrustBundleRef for scoring and trust configuration
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Uses trust lattice results in Lattice State gate
- Uses proof bundles for evidence completeness verification
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs` -- DSSE-signed attestations referencing proof bundles
## E2E Test Plan
- [ ] Evaluate trust lattice with 3 VEX claims; verify proof bundle contains all 3 claims with scores
- [ ] Evaluate trust lattice with conflicting claims; verify proof bundle includes conflict markers and K4 Conflict value
- [ ] Build policy bundle with PolicyBundleRef; verify Digest is content-addressed
- [ ] Verify proof bundle includes K4 lattice values for each subject (CVE + component)
- [ ] Verify ClaimScoreMerger produces deterministic merge result for identical inputs
- [ ] Verify claim with higher specificity wins over claim with higher raw score when conflict exists
- [ ] Evaluate with RequiresReplayProof=true; verify proof bundle is flagged for replay verification
- [ ] Reference proof bundle from VerdictAttestationService; verify attestation includes bundle digest
- [ ] Evaluate PolicyGateEvaluator Evidence gate; verify it checks proof bundle completeness

View File

@@ -0,0 +1,43 @@
# Policy Engine with Proofs (Moat Score 3)
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy engine with gate levels, delta verdict statements, gateway endpoints, and exception approval rules.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- 5 sequential gates: Evidence Completeness, Lattice State, VEX Trust, Uncertainty Tier, Confidence Threshold
- Gate results: Pass, PassWithNote, Warn, Block, Skip
- Short-circuits on first Block; accumulates warnings
- Lattice states: U (Unknown), SR (Safe-Reachable), SU (Safe-Unknown), RO (Reachable-Open), RU (Reachable-Unknown), CR (Conflicting-Reachable), CU (Conflicting-Unknown), X (Exploitable)
- Uncertainty tiers: T1 (High), T2 (Medium), T3 (Low), T4 (Negligible)
- Override support with justification requirements
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` -- per-environment VEX trust thresholds with TrustBreakdown
- **DeterminizationGate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs` -- confidence decay verification
- **StabilityDampingGate**: `src/Policy/StellaOps.Policy.Engine/Gates/StabilityDampingGate.cs` -- oscillation prevention
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs` -- SBOM drift evaluation
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs` -- delta verdict computation
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs` -- deterministic delta statements
- **ExceptionEvaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs` -- exception approval and application
- **ExceptionEffectRegistry**: `src/Policy/StellaOps.Policy.Engine/Adapters/ExceptionEffectRegistry.cs` -- 40 type+reason to effect mappings
- **ExceptionRecheckGate**: `src/Policy/StellaOps.Policy.Engine/BuildGate/ExceptionRecheckGate.cs` -- CI/CD recheck gate
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs` -- DSSE-signed verdict proofs
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs` -- content-addressed evaluation input manifests
- **Gateway endpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/` -- 45+ endpoint files for policy evaluation, simulation, scoring, risk budgets, exceptions, staleness
## E2E Test Plan
- [ ] Evaluate artifact through full 5-gate pipeline; verify each gate produces Pass/Warn/Block result
- [ ] Evaluate artifact with reachable vulnerability (RO state); verify Lattice State gate applies correct action
- [ ] Evaluate artifact with conflicting VEX claims (CR state); verify gate handles conflict appropriately
- [ ] Compute delta verdict via WhatIfSimulation; verify before/after decision changes are tracked
- [ ] Apply exception to finding; verify ExceptionEffectRegistry maps to correct effect (Suppress/Defer/Downgrade/RequireControl)
- [ ] Evaluate ExceptionRecheckGate with EPSSAbove condition triggered; verify gate blocks
- [ ] Generate DSSE-signed verdict attestation; verify signature and payload integrity
- [ ] Build KnowledgeSnapshotManifest; verify content-addressed SnapshotId is deterministic
- [ ] Override blocked gate with justification; verify PassWithNote result
- [ ] Verify StabilityDampingGate prevents oscillation between Pass and Block decisions

View File

@@ -0,0 +1,42 @@
# Policy gate with evidence-linked approval
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy gates (CVE, EPSS, budget, reachability, signature-required) evaluate artifacts against configurable rules and produce evidence-linked attestations.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- 5 sequential gates: Evidence Completeness, Lattice State, VEX Trust, Uncertainty Tier, Confidence Threshold
- Each gate produces evidence-linked results with attestation references
- Gate results: Pass, PassWithNote, Warn, Block, Skip
- Override support with justification text and evidence requirements
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs`
- Evaluates VEX trust score against per-environment thresholds
- Links VEX attestation references to gate decisions
- VexTrustStatus with TrustScore, PolicyTrustThreshold, TrustBreakdown
- **ExceptionEvaluator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/ExceptionEvaluator.cs`
- Exception-based approvals with evidence references (sha256 digests, attestation URIs)
- EvidenceRefs from all matching exceptions aggregated in result
- **EvidenceRequirementValidator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs`
- Validates required evidence before approval: attestation IDs, VEX notes, reachability proofs
- Evidence freshness (MaxAge), trust score threshold, DSSE signature verification
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs`
- DSSE-signed attestations linking verdicts to evidence bundles
- Each gate decision produces an attestation with proof references
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs`
- Content-addressed bundle linking all evaluation inputs to gate decisions
## E2E Test Plan
- [ ] Evaluate artifact through all gates; verify each gate result includes attestation references
- [ ] Evaluate with VexTrustGate; verify VEX attestation IDs are linked in gate result
- [ ] Approve exception with evidence refs; verify EvidenceRefs appear in ExceptionEvaluationResult.AllEvidenceRefs
- [ ] Require attestation ID evidence for approval; provide valid attestation; verify validation passes
- [ ] Require evidence with MaxAge; provide expired evidence; verify validation fails
- [ ] Generate verdict attestation; verify DSSE signature covers gate decisions and evidence refs
- [ ] Override gate with justification; verify PassWithNote result includes justification attestation
- [ ] Verify KnowledgeSnapshotManifest links policy bundle digest and source digests to gate inputs

View File

@@ -0,0 +1,43 @@
# Policy Simulation Engine (Shadow Runs / What-If Analysis)
## Module
Policy
## Status
IMPLEMENTED
## Description
Full policy simulation engine with risk simulation, what-if analysis, simulation analytics, and breakdown services. Multiple simulation endpoints exist (RiskSimulationEndpoints, PathScopeSimulationEndpoint, OverlaySimulationEndpoint, ConsoleSimulationEndpoint).
## Implementation Details
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs` (sealed class)
- `Simulate(items)` computes aggregate risk scores for a set of scored items
- `SimulateWithBreakdown(items)` adds distribution (10 buckets, percentiles p25/p50/p75/p90/p95/p99), severity breakdown (Critical/High/Medium/Low), top 10 movers
- `CompareProfilesWithBreakdown(profileA, profileB)` side-by-side profile comparison with delta analysis
- Signal scoring: Boolean (0/1), Numeric (direct), Categorical (mapped weight)
- Severity mapping: Critical>=90, High>=70, Medium>=40, Low>=10
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs` (sealed class)
- `SimulateAsync()` computes baseline vs simulated decisions with SBOM diffs
- Diff operations: add, remove, upgrade, downgrade with advisory/VEX/reachability
- Decision changes: status_changed, severity_changed, new, removed
- Impact summary: risk delta, blocked/warning deltas, recommendations
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs`
- Schema version: console-policy-23-001
- Deterministic before/after severity breakdowns, delta, rule impact, explain samples
- **Endpoints**:
- `RiskSimulationEndpoints.cs`: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskSimulationEndpoints.cs`
- `PathScopeSimulationEndpoint.cs`: `src/Policy/StellaOps.Policy.Engine/Endpoints/PathScopeSimulationEndpoint.cs`
- `OverlaySimulationEndpoint.cs`: `src/Policy/StellaOps.Policy.Engine/Endpoints/OverlaySimulationEndpoint.cs`
- `ConsoleSimulationEndpoint.cs`: `src/Policy/StellaOps.Policy.Engine/Endpoints/ConsoleSimulationEndpoint.cs`
## E2E Test Plan
- [ ] POST risk simulation with 10 scored items; verify response includes aggregate score, distribution (10 buckets), severity breakdown, top movers
- [ ] POST what-if simulation with add operation (add new component); verify new findings appear in delta
- [ ] POST what-if simulation with upgrade operation; verify severity_changed findings in delta
- [ ] POST path-scope simulation targeting specific artifact; verify results scoped to that artifact
- [ ] POST overlay simulation with policy rule change; verify delta reflects rule impact
- [ ] Compare two scoring profiles; verify CompareProfilesWithBreakdown returns per-profile breakdowns with deltas
- [ ] Verify console simulation diff produces deterministic output (same input -> same output)
- [ ] POST what-if simulation with remove operation; verify removed findings in delta
- [ ] Verify distribution percentiles: p25 <= p50 <= p75 <= p90 <= p95 <= p99
- [ ] Verify top movers are sorted by normalized score descending (top 10 limit)

View File

@@ -0,0 +1,39 @@
# ProhibitedPatternAnalyzer (Static Purity Analysis)
## Module
Policy
## Status
IMPLEMENTED
## Description
Static purity analysis detecting prohibited patterns (ambient IO, clock access, etc.) in evaluation code.
## Implementation Details
- **ProhibitedPatternAnalyzer**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/ProhibitedPatternAnalyzer.cs`
- Regex-based detection of non-deterministic patterns in source code
- Prohibited pattern categories:
- Wall-clock access: `DateTime.Now`, `DateTime.UtcNow`, `DateTimeOffset.Now`, `DateTimeOffset.UtcNow`
- Random number generation: `Random`, `RandomNumberGenerator`
- Network access: `HttpClient`, `WebRequest`, `TcpClient`, `UdpClient`
- Filesystem access: `File.`, `Directory.`, `Path.GetTempPath`
- Line-by-line scanning with comment line skipping (lines starting with `//` or `///`)
- Returns list of `ProhibitedPatternMatch` with line number, pattern name, matched text
- **DeterminismGuardService**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/DeterminismGuardService.cs`
- `AnalyzeSource(sourceCode)` invokes ProhibitedPatternAnalyzer to find violations
- `CreateScope()` creates a determinism guard scope for runtime monitoring
- `ValidateContext<T>()` validates evaluation context for determinism
- Combines ProhibitedPatternAnalyzer (static) and RuntimeDeterminismMonitor (runtime)
- **RuntimeDeterminismMonitor**: `src/Policy/StellaOps.Policy.Engine/DeterminismGuard/RuntimeDeterminismMonitor.cs` -- runtime monitoring companion
- **GuardedPolicyEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs` -- gate that uses determinism guards in evaluation pipeline
## E2E Test Plan
- [ ] Analyze source code containing `DateTime.Now`; verify prohibited pattern detected with correct line number
- [ ] Analyze source code containing `new Random()`; verify prohibited pattern detected
- [ ] Analyze source code containing `HttpClient`; verify network access pattern detected
- [ ] Analyze source code containing `File.ReadAllText`; verify filesystem pattern detected
- [ ] Analyze source code with prohibited pattern in a comment line (`// DateTime.Now`); verify NOT detected (comment skipped)
- [ ] Analyze clean source code with no prohibited patterns; verify empty results
- [ ] Analyze source code with multiple violations on different lines; verify all detected with correct line numbers
- [ ] Verify DeterminismGuardService.AnalyzeSource returns results from ProhibitedPatternAnalyzer
- [ ] Create determinism guard scope; use TimeProvider instead of DateTime.Now; verify no violations

View File

@@ -0,0 +1,42 @@
# Proof Replay / Deterministic Verdict Replay
## Module
Policy
## Status
IMPLEMENTED
## Description
Full replay service with a dedicated module, determinism verifier, run manifests, and extensive E2E tests that verify byte-identical verdict replay across runs.
## Implementation Details
- **ReplayEngine**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayEngine.cs` (sealed class implements `IReplayEngine`)
- `ReplayAsync(ReplayRequest)` replays policy evaluation with frozen snapshot inputs
- Pipeline: load snapshot -> resolve frozen inputs -> execute with frozen inputs -> compare with original -> generate delta report
- Uses `ISnapshotService` for snapshot loading, `IKnowledgeSourceResolver` for input resolution, `IVerdictComparer` for comparison
- Returns `ReplayResult` with MatchStatus, ReplayedVerdict, OriginalVerdict, DeltaReport, Duration
- **ReplayRequest**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayRequest.cs` (sealed record)
- ArtifactDigest, SnapshotId, OriginalVerdictId (optional, for comparison)
- ReplayOptions: CompareWithOriginal (default true), AllowNetworkFetch (default false), GenerateDetailedReport (default true), ScoreTolerance (default 0.001)
- **ReplayResult**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayResult.cs` (sealed record)
- ReplayMatchStatus: ExactMatch, MatchWithinTolerance, Mismatch, NoComparison, ReplayFailed
- ReplayedVerdict: VerdictId, ArtifactDigest, Decision (Pass/Fail/PassWithExceptions/Indeterminate), Score, FindingIds, KnowledgeSnapshotId
- ReplayDeltaReport: Summary, FieldDeltas (FieldName, OriginalValue, ReplayedValue), FindingDeltas (FindingId, DeltaType, Description), SuspectedCauses
- **VerdictComparer**: `src/Policy/__Libraries/StellaOps.Policy/Replay/VerdictComparer.cs` -- compares replayed vs original verdicts with tolerance
- **ReplayReport**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayReport.cs` -- detailed replay report generation
- **KnowledgeSourceResolver**: `src/Policy/__Libraries/StellaOps.Policy/Replay/KnowledgeSourceResolver.cs` -- resolves snapshot sources to frozen data
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs` -- content-addressed snapshot used as replay input
- **SnapshotAwarePolicyEvaluator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotAwarePolicyEvaluator.cs` -- evaluates using pinned snapshot inputs
## E2E Test Plan
- [ ] Replay verdict with same snapshot; verify MatchStatus=ExactMatch (deterministic evaluation)
- [ ] Replay verdict with OriginalVerdictId; verify OriginalVerdict is loaded and compared
- [ ] Replay with CompareWithOriginal=false; verify MatchStatus=NoComparison, no OriginalVerdict
- [ ] Replay with missing snapshot; verify MatchStatus=ReplayFailed, DeltaReport contains error
- [ ] Replay with incomplete snapshot (missing source); verify ReplayFailed with missing source names
- [ ] Replay with score difference within ScoreTolerance=0.001; verify MatchStatus=MatchWithinTolerance
- [ ] Replay with score difference exceeding tolerance; verify MatchStatus=Mismatch with FieldDeltas
- [ ] Replay with finding difference; verify DeltaReport.FindingDeltas contains Added/Removed/Modified entries
- [ ] Replay with GenerateDetailedReport=true; verify DeltaReport.SuspectedCauses is populated
- [ ] Verify AllowNetworkFetch=false prevents network access for missing sources
- [ ] Verify replay Duration is recorded in result

View File

@@ -0,0 +1,39 @@
# Property-Based Tests (FsCheck)
## Module
Policy
## Status
IMPLEMENTED
## Description
Property-based tests using FsCheck for canonical JSON determinism, SBOM/VEX ordering invariants, floating-point stability, digest computation determinism, smart-diff properties, and VEX lattice merge commutativity.
## Implementation Details
- **DecayPropertyTests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/PropertyTests/DecayPropertyTests.cs`
- FsCheck properties for DecayedConfidenceCalculator: monotonicity, bounds, floor enforcement, half-life correctness
- Verifies: decay factor always in [0, 1], result always >= floor, older observations have lower scores
- **DeterminismPropertyTests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/PropertyTests/DeterminismPropertyTests.cs`
- FsCheck properties for deterministic evaluation: same inputs produce same outputs
- Verifies: ObservationDecay CalculateDecay is deterministic, content-addressed ID generation is stable
- **ObservationDecayTests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/Models/ObservationDecayTests.cs`
- Unit tests for ObservationDecay model: Create, Fresh, WithSettings, CalculateDecay, CheckIsStale
- **DeterminizationResultTests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/Models/DeterminizationResultTests.cs`
- Unit tests for DeterminizationResult model
- **DecayedConfidenceCalculatorTests**: `src/Policy/__Tests/StellaOps.Policy.Determinization.Tests/DecayedConfidenceCalculatorTests.cs`
- Unit tests for DecayedConfidenceCalculator: boundary values, half-life verification, floor enforcement
- **DeterminizationGateTests**: `src/Policy/__Tests/StellaOps.Policy.Engine.Tests/Gates/Determinization/DeterminizationGateTests.cs`
- Integration tests for DeterminizationGate in gate pipeline
- **DeterminizationPolicyTests**: `src/Policy/__Tests/StellaOps.Policy.Engine.Tests/Policies/DeterminizationPolicyTests.cs`
- Policy-level tests for determinization enforcement
## E2E Test Plan
- [ ] Run DecayPropertyTests; verify all FsCheck properties pass (monotonicity, bounds, floor, half-life)
- [ ] Run DeterminismPropertyTests; verify deterministic evaluation property holds for 1000+ random inputs
- [ ] Verify DecayedConfidenceCalculator boundary: baseConfidence=0.0 always returns floor
- [ ] Verify DecayedConfidenceCalculator boundary: ageDays=0 always returns baseConfidence
- [ ] Verify ObservationDecay.Fresh(now).CheckIsStale(now) == false
- [ ] Verify decay monotonicity: older age always produces lower or equal score
- [ ] Verify content-addressed ID generation produces same ID for identical inputs (1000 iterations)
- [ ] Verify DeterminizationGate integration with DecayedConfidenceCalculator in gate pipeline
- [ ] Verify all test suites pass in CI with frozen test clock (no time-dependent flakiness)

View File

@@ -0,0 +1,39 @@
# Release Gate Levels (G0-G4)
## Module
Policy
## Status
IMPLEMENTED
## Description
Five gate levels (G0 through G4) with escalating requirements. GateSelector computes RRS, maps to gate level, and applies budget modifiers (Yellow/Red/Exhausted escalations). Each gate level has defined requirements matching the advisory specification.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Multi-gate evaluation with escalating strictness per gate level
- Gate levels mapped from Risk Readiness Score (RRS) and budget status
- 5 sequential gates with configurable thresholds per level
- Lattice states drive gate decisions: U, SR, SU, RO, RU, CR, CU, X
- Uncertainty tiers: T1 (High) -> strictest, T4 (Negligible) -> most permissive
- **PolicyGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateOptions.cs` -- per-level gate configuration
- **PolicyGateDecision**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateDecision.cs` -- decision model with per-gate results
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs`
- Signal-based RRS computation with severity mapping
- Severity: Critical>=90, High>=70, Medium>=40, Low>=10
- Distribution and percentile calculation for gate level determination
- **Budget integration**: Budget status (Yellow/Red/Exhausted) escalates gate level
- `BudgetEndpoints.cs`: `src/Policy/StellaOps.Policy.Engine/Endpoints/BudgetEndpoints.cs`
- `RiskBudgetEndpoints.cs`: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskBudgetEndpoints.cs`
- **Ledger**: `src/Policy/StellaOps.Policy.Engine/Ledger/` -- tracks gate decisions for compliance
## E2E Test Plan
- [ ] Evaluate artifact with low RRS (minimal risk); verify gate level maps to G0 (minimal requirements)
- [ ] Evaluate artifact with high RRS (many critical findings); verify gate level escalates to G3 or G4
- [ ] Evaluate with budget status Yellow; verify gate level escalates by one level
- [ ] Evaluate with budget status Exhausted; verify gate level escalates to maximum (G4)
- [ ] Evaluate at G0: verify only basic evidence completeness is checked
- [ ] Evaluate at G4: verify all gates apply strictest thresholds (lattice state, VEX trust, uncertainty, confidence)
- [ ] Verify each gate level (G0-G4) has progressively stricter thresholds
- [ ] Verify gate decision includes per-gate Pass/Warn/Block results for audit trail
- [ ] Verify ledger records gate level and decision for compliance

View File

@@ -0,0 +1,40 @@
# Replayable Verdict Evaluation
## Module
Policy
## Status
IMPLEMENTED
## Description
Full replay engine that re-evaluates verdicts using stored snapshot inputs, producing match/mismatch reports with delta explanations when results differ. Exposed via API endpoints.
## Implementation Details
- **ReplayEngine**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayEngine.cs` (sealed class implements `IReplayEngine`)
- `ReplayAsync(ReplayRequest)` -- full replay pipeline: load snapshot, resolve inputs, execute, compare, report
- Uses frozen inputs from KnowledgeSnapshotManifest to ensure deterministic re-evaluation
- Comparison with VerdictComparer produces ExactMatch, MatchWithinTolerance, or Mismatch
- Delta report with FieldDeltas, FindingDeltas, and SuspectedCauses
- **ReplayRequest**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayRequest.cs`
- ArtifactDigest, SnapshotId, OriginalVerdictId
- ReplayOptions: CompareWithOriginal, AllowNetworkFetch=false, GenerateDetailedReport, ScoreTolerance=0.001
- **ReplayResult**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayResult.cs`
- MatchStatus: ExactMatch, MatchWithinTolerance, Mismatch, NoComparison, ReplayFailed
- ReplayedVerdict with Decision (Pass/Fail/PassWithExceptions/Indeterminate), Score, FindingIds
- Duration tracking for performance monitoring
- **VerdictComparer**: `src/Policy/__Libraries/StellaOps.Policy/Replay/VerdictComparer.cs` -- deterministic comparison with configurable tolerance
- **KnowledgeSourceResolver**: `src/Policy/__Libraries/StellaOps.Policy/Replay/KnowledgeSourceResolver.cs` -- resolves snapshot source descriptors to data
- **SnapshotAwarePolicyEvaluator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotAwarePolicyEvaluator.cs` -- evaluation with pinned inputs
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs` -- content-addressed snapshot manifest
## E2E Test Plan
- [ ] Replay verdict with same snapshot and inputs; verify ExactMatch status
- [ ] Replay verdict after source data changed; verify Mismatch with SuspectedCauses listing changed source
- [ ] Replay with ScoreTolerance=0.01; introduce 0.005 score drift; verify MatchWithinTolerance
- [ ] Replay with ScoreTolerance=0.001; introduce 0.005 score drift; verify Mismatch with FieldDelta showing score difference
- [ ] Verify ReplayDeltaReport.FindingDeltas lists Added findings (present in replay, absent in original)
- [ ] Verify ReplayDeltaReport.FindingDeltas lists Removed findings (absent in replay, present in original)
- [ ] Replay with AllowNetworkFetch=false and missing bundled source; verify ReplayFailed
- [ ] Replay with CompareWithOriginal=false; verify NoComparison status, no DeltaReport
- [ ] Verify replay Duration is non-zero and reasonable
- [ ] POST replay endpoint; verify JSON response includes all ReplayResult fields

View File

@@ -0,0 +1,34 @@
# Risk Budget API Endpoints
## Module
Policy
## Status
IMPLEMENTED
## Description
API endpoints for risk budget management and enforcement with integration-level testing of budget enforcement.
## Implementation Details
- **BudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BudgetEndpoints.cs` -- CRUD endpoints for budget management
- **RiskBudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskBudgetEndpoints.cs` -- risk budget evaluation and status endpoints
- **RiskProfileEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskProfileEndpoints.cs` -- risk profile configuration endpoints
- **RiskProfileSchemaEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskProfileSchemaEndpoints.cs` -- schema validation for risk profiles
- **RiskProfileAirGapEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskProfileAirGapEndpoints.cs` -- air-gap compatible risk profile endpoints
- **LedgerExportService**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportService.cs` -- budget ledger export for compliance
- **LedgerModels**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerModels.cs` -- ledger data models
- **LedgerExportStore**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportStore.cs` -- persistence for ledger exports
- **UnknownBudgetService** / **UnknownsBudgetEnforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/` -- budget enforcement for unknowns
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- budget status affects gate level selection
## E2E Test Plan
- [ ] GET budget status endpoint; verify response includes current consumption, limits, and status (Green/Yellow/Red/Exhausted)
- [ ] POST create budget with critical/high/medium limits; verify budget created with correct thresholds
- [ ] POST evaluate risk budget for artifact; verify consumption is calculated and compared against limits
- [ ] Consume budget beyond Yellow threshold; verify status changes to Yellow
- [ ] Consume budget beyond Red threshold; verify status changes to Red
- [ ] Consume budget beyond limit; verify status changes to Exhausted and gate level escalates
- [ ] GET risk profile endpoint; verify profile includes budget configuration and scoring weights
- [ ] POST risk profile schema validation; verify invalid profile returns validation errors
- [ ] GET ledger export; verify budget transactions are exported with timestamps and actor IDs
- [ ] GET air-gap risk profile endpoint; verify offline-compatible response without external dependencies

View File

@@ -0,0 +1,33 @@
# Risk Budget Management
## Module
Policy
## Status
IMPLEMENTED
## Description
Per-service risk budget management with budget ledger (RP consumed per release, remaining, trendline), constraint enforcement, threshold notifications, and earned capacity replenishment.
## Implementation Details
- **BudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BudgetEndpoints.cs` -- CRUD API for budget definitions and status queries
- **RiskBudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskBudgetEndpoints.cs` -- risk budget evaluation, consumption tracking, and status
- **LedgerExportService**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportService.cs` -- budget ledger tracking RP consumed per release, remaining capacity, trendline
- **LedgerModels**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerModels.cs` -- data models for ledger entries (release ID, RP consumed, timestamp, actor)
- **LedgerExportStore**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportStore.cs` -- persistence for ledger export
- **UnknownBudgetService**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownBudgetService.cs` -- budget management for unknowns
- **UnknownsBudgetEnforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownsBudgetEnforcer.cs` -- constraint enforcement (Green/Yellow/Red/Exhausted thresholds)
- **PolicyGateEvaluator budget integration**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- budget status (Yellow/Red/Exhausted) escalates gate levels
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs` -- simulates budget impact of policy changes
## E2E Test Plan
- [ ] Create budget with critical=10, high=20, medium=50 limits; verify budget status is Green
- [ ] Consume 15 critical RP; verify budget status transitions to Yellow for critical
- [ ] Consume 8 more critical RP (total 23 > limit 10); verify budget status transitions to Red/Exhausted
- [ ] Verify ledger records each consumption with release ID, RP amount, timestamp, and actor
- [ ] Query budget trendline; verify declining remaining capacity across releases
- [ ] Trigger threshold notification at Yellow; verify notification includes budget name, threshold, and current consumption
- [ ] Verify earned capacity replenishment: resolve findings to restore budget capacity
- [ ] Export ledger; verify all entries are included with compliance-ready format
- [ ] Verify budget constraint enforcement blocks release when Exhausted
- [ ] Verify gate level escalation when budget is in Red status

View File

@@ -0,0 +1,41 @@
# Risk Budget Model (Service Tiers + Risk Points)
## Module
Policy
## Status
IMPLEMENTED
## Description
Complete risk budget system with service tier-based scoring, risk point computation, budget ledger tracking, constraint enforcement, threshold notifications, capacity replenishment, and persistence. Includes API endpoints and property-based tests for monotonicity.
## Implementation Details
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs`
- Signal-based risk point computation: Boolean (0/1), Numeric (direct), Categorical (mapped weight)
- Severity mapping: Critical>=90, High>=70, Medium>=40, Low>=10
- Distribution calculation with 10 buckets, 6 percentiles (p25/p50/p75/p90/p95/p99)
- Aggregate metrics: total, mean, median, stddev, severity breakdown
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Two-factor risk score: Score = (Uncertainty * 50) + (ExploitPressure * 50)
- Band assignment: Hot >= 75, Warm >= 50, Cold >= 25, Negligible < 25
- Containment reduction capped at 40% (Seccomp 10%, FsRO 10%, Isolated 15%, etc.)
- Decay buckets for time-based scoring adjustments
- **UnknownBudgetService** / **UnknownsBudgetEnforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/`
- Per-service budget constraints with Green/Yellow/Red/Exhausted thresholds
- Budget enforcement blocks releases when Exhausted
- **LedgerExportService**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportService.cs` -- budget ledger persistence
- **BudgetEndpoints** / **RiskBudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/` -- API for budget CRUD and evaluation
- **Scoring engines**: `src/Policy/StellaOps.Policy.Engine/Scoring/Engines/` -- SimpleScoringEngine, AdvancedScoringEngine, ProofAwareScoringEngine
- **ScoringProfileService**: `src/Policy/StellaOps.Policy.Engine/Scoring/ScoringProfileService.cs` -- configurable scoring profiles with weighted signals
## E2E Test Plan
- [ ] Compute risk points for finding with Critical severity (CVSS>=9.0, EPSS>=0.90); verify score >= 90
- [ ] Compute risk points for finding with Low severity (CVSS=3.0); verify score maps to Low range (10-39)
- [ ] Compute risk points with containment reduction (Seccomp + FsRO); verify 20% reduction applied
- [ ] Verify score monotonicity: higher CVSS/EPSS always produces higher or equal score
- [ ] Compute aggregate risk for 10 findings; verify distribution has 10 buckets, valid percentiles
- [ ] Verify severity breakdown: Critical count + High count + Medium count + Low count = total findings
- [ ] Create budget with tier-based limits; consume RP; verify threshold transitions (Green -> Yellow -> Red -> Exhausted)
- [ ] Verify budget capacity replenishment: resolve 5 findings; verify remaining capacity increases
- [ ] Verify ProofAwareScoringEngine includes proof references in scored output
- [ ] Verify scoring profile weights CVSS, EPSS, reachability contributions correctly

View File

@@ -0,0 +1,42 @@
# Risk Point Scoring
## Module
Policy
## Status
IMPLEMENTED
## Description
Risk Point (RP) scoring model computing Release Risk Score from base criticality, diff risk, operational context, and mitigations with monotonicity guarantees.
## Implementation Details
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs`
- `Simulate(items)` computes aggregate risk scores
- `SimulateWithBreakdown(items)` returns full distribution, severity breakdown, top movers
- Signal-based scoring: Boolean (0/1), Numeric (direct value), Categorical (mapped weight)
- Severity mapping: Critical>=90, High>=70, Medium>=40, Low>=10
- Normalization ensures scores in valid range
- **Scoring engines**: `src/Policy/StellaOps.Policy.Engine/Scoring/Engines/`
- `SimpleScoringEngine.cs` -- basic risk point computation
- `AdvancedScoringEngine.cs` -- multi-factor scoring with mitigations
- `ProofAwareScoringEngine.cs` -- proof-linked scoring with attestation references
- **IScoringEngine interface**: `src/Policy/StellaOps.Policy.Engine/Scoring/IScoringEngine.cs`
- **ScoringProfileService**: `src/Policy/StellaOps.Policy.Engine/Scoring/ScoringProfileService.cs` -- profile-based scoring with configurable weights
- **ScorePolicyService**: `src/Policy/StellaOps.Policy.Engine/Scoring/ScorePolicyService.cs` -- policy-aware scoring
- **EvidenceWeightedScore**: `src/Policy/StellaOps.Policy.Engine/Scoring/EvidenceWeightedScore/` -- evidence-weighted scoring enricher
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Two-factor formula: Score = (Uncertainty * 50) + (ExploitPressure * 50)
- Uncertainty: Missing VEX +0.40, Missing reachability +0.30, Conflicting +0.20, Stale +0.10
- Exploit pressure: KEV +0.50, EPSS>=0.90 +0.30, EPSS>=0.50 +0.15, CVSS>=9.0 +0.05
## E2E Test Plan
- [ ] Score finding with base criticality=Critical (CVSS 9.5); verify RP score >= 90
- [ ] Score finding with diff risk (new finding in delta); verify RP includes diff risk component
- [ ] Score finding with operational context (production, internet-facing); verify RP adjusted upward
- [ ] Score finding with mitigation (compensating control verified); verify RP reduced
- [ ] Verify monotonicity: increasing CVSS from 7.0 to 9.0 always increases RP score
- [ ] Verify monotonicity: adding KEV flag always increases RP score
- [ ] Score with SimpleScoringEngine; verify basic RP computation
- [ ] Score with AdvancedScoringEngine; verify multi-factor computation includes mitigations
- [ ] Score with ProofAwareScoringEngine; verify attestation references included
- [ ] Verify EvidenceWeightedScore enricher adjusts score based on evidence freshness/completeness

View File

@@ -0,0 +1,41 @@
# Risk Verdict Attestation (RVA) Contract
## Module
Policy
## Status
IMPLEMENTED
## Description
Structured Risk Verdict Attestation with PASS/FAIL/PASS_WITH_EXCEPTIONS/INDETERMINATE verdicts, policy references, knowledge snapshot bindings, evidence references, and reason codes as a first-class product artifact.
## Implementation Details
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs`
- Generates DSSE-signed attestations for policy verdicts
- Verdict types: PASS, FAIL, PASS_WITH_EXCEPTIONS, INDETERMINATE
- Policy reference binding: PolicyBundleDigest links attestation to specific policy version
- Knowledge snapshot binding: SnapshotId links to frozen evaluation inputs
- Evidence references: content-addressed digests for all evidence used
- Reason codes for verdict justification
- **PolicyDecisionAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/PolicyDecisionAttestationService.cs`
- Creates attestations for individual policy decisions within a verdict
- **RvaService**: `src/Policy/StellaOps.Policy.Engine/Attestation/RvaService.cs` -- Risk Verdict Attestation service
- **ScoringDeterminismVerifier**: `src/Policy/StellaOps.Policy.Engine/Attestation/ScoringDeterminismVerifier.cs` -- verifies scoring determinism before attestation
- **ReplayedVerdict model**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayResult.cs`
- ReplayDecision enum: Unknown, Pass, Fail, PassWithExceptions, Indeterminate
- Verdict includes Score, FindingIds, KnowledgeSnapshotId
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs`
- Content-addressed snapshot binding: SnapshotId (ksm:sha256:{hash})
- **Attestation directory**: `src/Policy/StellaOps.Policy.Engine/Attestation/` -- 28 files for attestation generation, verification, and management
## E2E Test Plan
- [ ] Generate RVA for artifact with all gates passing; verify verdict=PASS with reason codes
- [ ] Generate RVA for artifact with blocked gate; verify verdict=FAIL with blocking gate in reason
- [ ] Generate RVA for artifact with exception applied; verify verdict=PASS_WITH_EXCEPTIONS
- [ ] Generate RVA with indeterminate state (missing evidence); verify verdict=INDETERMINATE
- [ ] Verify RVA includes PolicyBundleDigest matching the policy used for evaluation
- [ ] Verify RVA includes SnapshotId matching the KnowledgeSnapshotManifest
- [ ] Verify RVA includes evidence references (content-addressed digests)
- [ ] Verify DSSE signature on RVA is valid and covers all verdict fields
- [ ] Verify ScoringDeterminismVerifier passes before attestation generation
- [ ] Parse RVA JSON; verify all required fields are present (verdict, policy_ref, snapshot_id, evidence_refs, reason_codes, generated_at)

View File

@@ -0,0 +1,36 @@
# Runtime Containment Signals for Unknowns Scoring
## Module
Policy
## Status
IMPLEMENTED
## Description
Incorporates runtime isolation posture (Seccomp enforcement, read-only filesystem, network isolation) as risk reduction factors in unknowns scoring. Enforced Seccomp gives 10% reduction, read-only FS gives 10%, network isolation gives 5%. Total containment reduction capped at 40%.
## Implementation Details
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Containment reduction applied after raw score computation
- Signal flags: Isolated (15%), NotNetFacing (5%), NonRoot (5%), Seccomp (10%), FsRO (10%), NetworkIsolated (5%)
- Total containment reduction capped at 40%
- Computation: `containmentBps = min(Sum(signal_bps), 4000)`, then `score *= (10000 - containmentBps) / 10000`
- Containment signals come from `UnknownRankInput.ContainmentSignals`
- **BlastRadius model**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/BlastRadius.cs`
- Dependents (int) -- number of dependent services
- NetFacing (bool) -- whether the service is internet-facing
- Privilege (string?) -- privilege level of the service process
- **UnknownRankerOptions**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRankerOptions.cs` -- configurable containment signal weights
- **Band assignment**: After containment reduction, score maps to bands: Hot >= 75, Warm >= 50, Cold >= 25, Negligible < 25
## E2E Test Plan
- [ ] Score unknown with no containment signals; verify full score (no reduction)
- [ ] Score unknown with Seccomp=true; verify 10% reduction from raw score
- [ ] Score unknown with FsRO=true; verify 10% reduction from raw score
- [ ] Score unknown with Isolated=true; verify 15% reduction from raw score
- [ ] Score unknown with all containment signals (Isolated+NotNetFacing+NonRoot+Seccomp+FsRO+NetworkIsolated); verify reduction capped at 40%
- [ ] Score unknown with Seccomp+FsRO (20% reduction); verify score reduced by exactly 20%
- [ ] Score unknown with containment reducing score from Hot (76) to Warm range; verify band changes from Hot to Warm
- [ ] Verify containment does not reduce score below 0
- [ ] Verify containment signals from BlastRadius.NetFacing=false maps to NotNetFacing signal
- [ ] Verify configurable weights in UnknownRankerOptions are applied correctly

View File

@@ -0,0 +1,36 @@
# SBOM Presence Policy Gate (SbomPresenceGate)
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy gate that blocks releases lacking a valid SBOM document, with configurable format requirements (CycloneDX/SPDX), minimum component count thresholds, and freshness checks.
## Implementation Details
- **PolicyGateEvaluator Evidence Completeness gate**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Evidence Completeness gate (first in 5-gate pipeline) checks for SBOM presence
- Missing SBOM triggers Block or Warn based on gate configuration
- Evaluates SBOM format, component count, and freshness as part of evidence checks
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs`
- Evaluates SBOM drift between baseline and target
- SBOM format validation (CycloneDX/SPDX) as part of drift analysis
- **DriftGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateOptions.cs` -- configurable SBOM requirements
- **EvidenceTtlEnforcer**: `src/Policy/__Libraries/StellaOps.Policy/Freshness/EvidenceTtlEnforcer.cs`
- SBOM/Provenance freshness: checks BuildTime against TTL
- Freshness statuses: Fresh, Warning, Stale
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs`
- SBOM diff operations verify SBOM presence before simulation
## E2E Test Plan
- [ ] Evaluate artifact without SBOM; verify Evidence Completeness gate blocks
- [ ] Evaluate artifact with valid CycloneDX SBOM; verify gate passes
- [ ] Evaluate artifact with valid SPDX SBOM; verify gate passes
- [ ] Configure minimum component count threshold=10; provide SBOM with 5 components; verify gate warns/blocks
- [ ] Configure minimum component count threshold=10; provide SBOM with 15 components; verify gate passes
- [ ] Evaluate artifact with stale SBOM (BuildTime exceeds TTL); verify freshness check warns
- [ ] Evaluate artifact with fresh SBOM (BuildTime within TTL); verify freshness check passes
- [ ] Verify gate result message indicates SBOM format and component count when present
- [ ] Verify DriftGateEvaluator detects missing SBOM in drift analysis

View File

@@ -0,0 +1,41 @@
# Score Attestation and Proof Ledger
## Module
Policy
## Status
IMPLEMENTED
## Description
Score attestation statements linked to proof nodes in a proof ledger for auditable scoring decisions.
## Implementation Details
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs`
- DSSE-signed attestations for scoring decisions
- Links score to evidence references and policy bundle digest
- Content-addressed attestation IDs for proof chain linking
- **PolicyDecisionAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/PolicyDecisionAttestationService.cs`
- Per-decision attestations within a verdict
- **ScoringDeterminismVerifier**: `src/Policy/StellaOps.Policy.Engine/Attestation/ScoringDeterminismVerifier.cs`
- Verifies scoring is deterministic before creating attestation
- Prevents non-deterministic scores from entering proof ledger
- **LedgerExportService**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportService.cs`
- Proof ledger: records score attestations with timestamps, actors, and references
- Export for compliance and audit review
- **LedgerModels**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerModels.cs` -- data models for ledger entries
- **LedgerExportStore**: `src/Policy/StellaOps.Policy.Engine/Ledger/LedgerExportStore.cs` -- persistence layer
- **ProofAwareScoringEngine**: `src/Policy/StellaOps.Policy.Engine/Scoring/Engines/ProofAwareScoringEngine.cs`
- Scoring engine that embeds proof references in scored output
- Links each score to the evidence and policy rules that produced it
- **EvidenceWeightedScore**: `src/Policy/StellaOps.Policy.Engine/Scoring/EvidenceWeightedScore/` -- evidence-weighted scoring with attestation links
## E2E Test Plan
- [ ] Score finding with ProofAwareScoringEngine; verify score includes proof references
- [ ] Generate score attestation; verify DSSE signature covers score, evidence refs, and policy bundle
- [ ] Verify ScoringDeterminismVerifier passes for deterministic scoring inputs
- [ ] Record score attestation in proof ledger; verify ledger entry includes attestation ID, score, and timestamp
- [ ] Export proof ledger; verify all score attestations are included in chronological order
- [ ] Score same finding twice with same inputs; verify attestation IDs match (content-addressed)
- [ ] Score finding with different evidence; verify attestation IDs differ
- [ ] Verify proof ledger links score attestation to parent verdict attestation
- [ ] Query ledger by time range; verify filtered results include only entries in range

View File

@@ -0,0 +1,40 @@
# Score.v1 Policy Format
## Status
IMPLEMENTED
## Description
No Score.v1 policy format was found in the codebase. Scoring is embedded in the TrustVerdict and SmartDiff modules without a standalone schema.
## Why Marked as Dropped (Correction)
**FINDING: The Score.v1 policy format IS implemented.** The following exist:
- `src/Policy/__Libraries/StellaOps.Policy/Schemas/score-policy.v1.schema.json` -- the v1 JSON schema itself
- `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScorePolicyValidator.cs` -- validates policies against the v1 schema
- `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScorePolicyModels.cs` -- data models for score policies
- `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScorePolicyLoader.cs` -- loads score policy definitions
- `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScoreAttestationStatement.cs` -- score attestation statements
- `src/Policy/StellaOps.Policy.Engine/Scoring/ScorePolicyService.cs` -- runtime score policy evaluation service
- `src/Policy/StellaOps.Policy.Engine/Scoring/ScoringProfileService.cs` -- scoring profile management
- Policy interop: `src/Policy/__Libraries/StellaOps.Policy.Interop/Import/JsonPolicyImporter.cs`, `FormatDetector.cs`
- Tests: `src/Policy/__Tests/StellaOps.Policy.Engine.Tests/Scoring/ScorePolicyServiceCachingTests.cs`, `ScorePolicyDigestReplayIntegrationTests.cs`, `ScoreBasedRuleTests.cs`
## Implementation Details
- Schema: `src/Policy/__Libraries/StellaOps.Policy/Schemas/score-policy.v1.schema.json`
- Validator: `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScorePolicyValidator.cs`
- Models: `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScorePolicyModels.cs`
- Loader: `src/Policy/__Libraries/StellaOps.Policy/Scoring/ScorePolicyLoader.cs`
- Engine service: `src/Policy/StellaOps.Policy.Engine/Scoring/ScorePolicyService.cs`
## E2E Test Plan
- Validate score policy schema validation against valid/invalid policies
- Test score policy loading and evaluation
- Verify score-based rules produce deterministic decisions
- Test digest replay for score policies
## Source
- Feature matrix scan
## Notes
- Module: Policy
- Modules referenced: `src/Policy/__Libraries/StellaOps.Policy/Scoring/`, `src/Policy/StellaOps.Policy.Engine/Scoring/`
- **Status should be reclassified from NOT_FOUND to IMPLEMENTED**

View File

@@ -0,0 +1,41 @@
# Security State Delta (Diff Engine)
## Module
Policy
## Status
IMPLEMENTED
## Description
A diff engine that takes baseline and target snapshot digests and produces structured delta objects with baseline selection methods (previous build, last approved, last deployed).
## Implementation Details
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs`
- `SimulateAsync()` computes baseline vs target deltas
- Baseline selection: current artifact state as baseline, simulated changes as target
- Delta objects: decision changes (status_changed, severity_changed, new, removed)
- Impact summary: risk delta (increased/decreased/unchanged), blocked/warning deltas
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs`
- Schema version: console-policy-23-001
- Structured before/after delta with severity breakdowns
- Rule impact analysis: which policy rules drove the delta
- Deterministic output for same inputs
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs`
- SBOM drift detection between baseline and target snapshots
- Produces structured drift delta with component additions/removals/upgrades
- **DriftGateContext**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateContext.cs` -- context for drift evaluation with baseline/target digests
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs`
- Content-addressed snapshots enable diff between any two evaluation states
- Baseline selection via SnapshotId comparison
## E2E Test Plan
- [ ] Compute delta between baseline and target with 2 new critical findings; verify delta shows 2 new findings with severity=Critical
- [ ] Compute delta between baseline and target with 1 resolved finding; verify delta shows 1 removed finding
- [ ] Compute delta with severity change (High->Critical); verify delta shows severity_changed
- [ ] Compute delta with status change (Warn->Block); verify delta shows status_changed
- [ ] Select baseline as "previous build"; verify correct baseline snapshot used
- [ ] Select baseline as "last approved"; verify correct baseline snapshot used
- [ ] Verify delta includes risk delta (increased/decreased/unchanged) summary
- [ ] Verify ConsoleSimulationDiffService produces deterministic delta for same inputs
- [ ] Verify DriftGateEvaluator detects component additions in SBOM drift
- [ ] Verify delta is empty when baseline and target are identical

View File

@@ -0,0 +1,41 @@
# Signature Required Policy Gate (SignatureRequiredGate)
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy gate requiring valid cryptographic signatures on release artifacts before promotion, with configurable signing key allowlists, certificate chain validation, and Rekor inclusion proof requirements.
## Implementation Details
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Evidence Completeness gate (first in pipeline) verifies signature presence
- Signature requirements configurable per environment
- Gate result types: Pass (valid signature), Block (missing/invalid signature)
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs`
- `RequireIssuerVerified` per-environment: production=true, staging=true, development=false
- Issuer signature verification as part of VEX trust evaluation
- **VexTrustGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateOptions.cs`
- Per-environment signing requirements (RequireIssuerVerified flag)
- FailureAction: Warn or Block when signature verification fails
- **EvidenceRequirementValidator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs`
- DSSE signature verification for evidence attestations
- Validates signed evidence meets trust requirements
- **VerdictAttestationService**: `src/Policy/StellaOps.Policy.Engine/Attestation/VerdictAttestationService.cs`
- DSSE-signed verdict attestations with certificate chain
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs`
- TrustBundleRef (BundleId, Digest, Uri) for trust anchor set
- Signature field on manifest for optional DSSE signing
## E2E Test Plan
- [ ] Evaluate artifact with valid signature from allowed key; verify gate passes
- [ ] Evaluate artifact without signature; verify gate blocks with "missing signature" message
- [ ] Evaluate artifact with signature from key not in allowlist; verify gate blocks
- [ ] Configure environment requiring issuer verification; provide unverified issuer; verify gate blocks
- [ ] Configure environment not requiring issuer verification (development); provide unsigned VEX; verify gate passes
- [ ] Evaluate artifact with expired certificate; verify gate blocks with certificate validation error
- [ ] Verify DSSE envelope structure on verdict attestation includes valid signature
- [ ] Verify TrustBundleRef in KnowledgeSnapshotManifest references correct trust anchor set
- [ ] Verify EvidenceRequirementValidator validates DSSE signature on evidence attestation

View File

@@ -0,0 +1,43 @@
# Signed VEX Override Enforcement in Policy Engine
## Module
Policy
## Status
IMPLEMENTED
## Description
Policy engine requires signed VEX override attestations with DSSE/Rekor validation, exposes override_signed and override_rekor_verified signals to DSL, and supports key trust levels and validity period enforcement.
## Implementation Details
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` (implements `IVexTrustGate`)
- Evaluates VEX trust including signature verification status
- VexTrustStatus with TrustScore and TrustBreakdown (issuer verification, accuracy, freshness)
- Per-environment thresholds for signature requirements
- **VexTrustGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateOptions.cs`
- Production: RequireIssuerVerified=true, MinCompositeScore=0.80, FailureAction=Block
- Staging: RequireIssuerVerified=true, FailureAction=Warn
- MissingTrustBehavior: Allow/Warn/Block when VEX trust data absent
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- VEX normalization pipeline supports DSSE-signed VEX documents
- Three normalizers: CycloneDX, OpenVEX, CSAF
- Signed VEX claims receive higher trust scores in ClaimScoreMerger
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs`
- Signed claims scored higher via specificity and score adjustments
- Conflict penalization (0.25) applies to conflicting signed/unsigned claims
- **EvidenceRequirementValidator**: `src/Policy/__Libraries/StellaOps.Policy.Exceptions/Services/EvidenceRequirementValidator.cs`
- DSSE signature verification on VEX override evidence
- Trust score threshold validation for signed evidence
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- VEX Trust gate evaluates signed override status as part of multi-gate pipeline
## E2E Test Plan
- [ ] Submit DSSE-signed VEX override; verify VexTrustGate passes with high TrustScore
- [ ] Submit unsigned VEX override in production; verify VexTrustGate blocks (RequireIssuerVerified=true)
- [ ] Submit unsigned VEX override in development; verify VexTrustGate passes (RequireIssuerVerified=false)
- [ ] Submit signed VEX with expired signing key; verify trust score reduced or gate blocks
- [ ] Submit signed VEX with Rekor inclusion proof; verify higher trust score than without proof
- [ ] Submit conflicting signed and unsigned VEX claims; verify ClaimScoreMerger applies conflict penalty, signed claim wins
- [ ] Verify VexTrustStatus includes TrustBreakdown with issuer verification status
- [ ] Submit VEX override with trust score below MinCompositeScore; verify gate blocks in production
- [ ] Configure MissingTrustBehavior=Block; submit VEX without trust data; verify gate blocks

View File

@@ -0,0 +1,44 @@
# Smart-Diff Semantic Risk Delta (Moat Score 4)
## Module
Policy
## Status
IMPLEMENTED
## Description
Material risk change detection with delta verdict computation, security state delta analysis, and delta computing.
## Implementation Details
- **WhatIfSimulationService**: `src/Policy/StellaOps.Policy.Engine/WhatIfSimulation/WhatIfSimulationService.cs`
- `SimulateAsync()` computes semantic risk delta between baseline and target
- SBOM diff operations: add, remove, upgrade, downgrade with advisory/VEX/reachability context
- Decision change types: status_changed, severity_changed, new, removed
- Impact summary: risk delta (increased/decreased/unchanged), material risk indicators
- Recommendations based on delta analysis
- **ConsoleSimulationDiffService**: `src/Policy/StellaOps.Policy.Engine/Console/ConsoleSimulationDiffService.cs`
- Schema version: console-policy-23-001
- Deterministic before/after severity breakdowns
- Rule impact analysis: identifies which policy rules drive the risk delta
- Explain samples for delta reasoning
- **DriftGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/DriftGateEvaluator.cs`
- SBOM drift detection as a semantic risk signal
- Component addition/removal/version change tracking
- **CounterfactualEngine**: `src/Policy/__Libraries/StellaOps.Policy/Counterfactuals/CounterfactualEngine.cs`
- Computes "what would fix this" paths: VEX, Exception, Reachability, VersionUpgrade, CompensatingControl
- Effort ratings per path: Critical=5, High=4, Medium=3, Low=2
- **RiskSimulationService**: `src/Policy/StellaOps.Policy.Engine/Simulation/RiskSimulationService.cs`
- Signal-based risk scoring with distribution and top movers
- `CompareProfilesWithBreakdown()` for before/after profile delta
## E2E Test Plan
- [ ] Simulate adding component with known critical CVE; verify risk delta shows "increased" with new critical finding
- [ ] Simulate upgrading component that fixes CVE; verify risk delta shows "decreased" with removed finding
- [ ] Simulate no changes; verify risk delta shows "unchanged"
- [ ] Verify severity_changed detection: finding changes from High to Critical
- [ ] Verify new detection: component addition introduces new findings
- [ ] Verify removed detection: component removal clears associated findings
- [ ] Verify CounterfactualEngine computes fix paths for blocked findings in delta
- [ ] Verify console diff output includes rule impact analysis
- [ ] Verify deterministic output: same baseline + target always produces same delta
- [ ] Verify DriftGateEvaluator integrates semantic drift into gate evaluation

View File

@@ -0,0 +1,43 @@
# Time-Travel Replay Engine
## Module
Policy
## Status
IMPLEMENTED
## Description
Re-evaluation of any historical decision using only snapshot content and recorded execution contract, producing match/mismatch reports with deterministic comparison.
## Implementation Details
- **ReplayEngine**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayEngine.cs` (sealed class implements `IReplayEngine`)
- `ReplayAsync(ReplayRequest)` replays historical decisions using frozen snapshot inputs
- Pipeline: load snapshot -> verify snapshot integrity -> resolve frozen inputs -> execute evaluation -> compare with original -> generate report
- Frozen inputs prevent time-dependent drift (no network fetch, no live data)
- Duration tracking for performance analysis
- **ReplayRequest**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayRequest.cs`
- ArtifactDigest, SnapshotId (content-addressed), OriginalVerdictId
- ReplayOptions: CompareWithOriginal=true, AllowNetworkFetch=false, GenerateDetailedReport=true, ScoreTolerance=0.001
- **ReplayResult**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayResult.cs`
- MatchStatus: ExactMatch, MatchWithinTolerance, Mismatch, NoComparison, ReplayFailed
- DeltaReport: Summary, FieldDeltas, FindingDeltas, SuspectedCauses
- **VerdictComparer**: `src/Policy/__Libraries/StellaOps.Policy/Replay/VerdictComparer.cs` -- deterministic verdict comparison
- **ReplayReport**: `src/Policy/__Libraries/StellaOps.Policy/Replay/ReplayReport.cs` -- detailed report generation
- **KnowledgeSourceResolver**: `src/Policy/__Libraries/StellaOps.Policy/Replay/KnowledgeSourceResolver.cs` -- resolves snapshot sources to frozen data
- **KnowledgeSnapshotManifest**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/KnowledgeSnapshotManifest.cs`
- Content-addressed snapshots enable time-travel to any historical state
- Sources with Epoch and Digest for point-in-time data resolution
- **SnapshotAwarePolicyEvaluator**: `src/Policy/__Libraries/StellaOps.Policy/Snapshots/SnapshotAwarePolicyEvaluator.cs`
- Evaluates policy using only pinned snapshot inputs (no live data)
## E2E Test Plan
- [ ] Replay decision from 30 days ago using its snapshot; verify ExactMatch (deterministic)
- [ ] Replay decision with modified snapshot source; verify Mismatch with SuspectedCauses
- [ ] Replay with AllowNetworkFetch=false; verify no external calls made during replay
- [ ] Verify ReplayResult.Duration tracks execution time
- [ ] Replay with missing snapshot; verify ReplayFailed with descriptive error
- [ ] Replay with ScoreTolerance=0.01; introduce minor floating-point drift; verify MatchWithinTolerance
- [ ] Verify DeltaReport.FieldDeltas shows exact field-level differences for Mismatch
- [ ] Verify DeltaReport.FindingDeltas shows finding-level changes (Added/Removed/Modified)
- [ ] Replay multiple historical decisions; verify each produces correct MatchStatus
- [ ] Verify snapshot integrity check runs before replay execution

View File

@@ -0,0 +1,40 @@
# Unknown Budget Policy Enforcement
## Module
Policy
## Status
IMPLEMENTED
## Description
Unknown budget enforcement with environment-aware thresholds, supporting policy evaluation that can fail/warn based on unknown counts by type.
## Implementation Details
- **UnknownsBudgetEnforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownsBudgetEnforcer.cs`
- Enforces budget constraints based on unknown counts by type
- Threshold levels: Green (within limits), Yellow (warning), Red (over budget), Exhausted (blocked)
- Environment-aware: different thresholds for production vs staging vs development
- **UnknownBudgetService**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownBudgetService.cs`
- Budget management: create, query, consume, replenish
- Per-type budget tracking (reachability unknowns, identity unknowns, VEX gaps, etc.)
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Ranks unknowns by two-factor score: (Uncertainty * 50) + (ExploitPressure * 50)
- Reason codes: AnalyzerLimit, Reachability, Identity, Provenance, VexConflict, FeedGap, ConfigUnknown
- Band assignment: Hot >= 75, Warm >= 50, Cold >= 25, Negligible < 25
- **PolicyGateEvaluator Uncertainty Tier gate**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- Uncertainty Tier gate (4th in pipeline) evaluates unknown counts against thresholds
- Tiers: T1 (High uncertainty -> strictest enforcement), T4 (Negligible -> most permissive)
- **BudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BudgetEndpoints.cs` -- API for budget management
- **RiskBudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/RiskBudgetEndpoints.cs` -- API for budget evaluation
## E2E Test Plan
- [ ] Set budget limit for reachability unknowns=10; report 5 unknowns; verify status Green
- [ ] Set budget limit for reachability unknowns=10; report 8 unknowns; verify status Yellow (warning)
- [ ] Set budget limit for reachability unknowns=10; report 12 unknowns; verify status Red/Exhausted
- [ ] Verify environment-aware thresholds: production has stricter limits than development
- [ ] Evaluate through PolicyGateEvaluator with T1 uncertainty tier; verify Uncertainty gate blocks
- [ ] Evaluate through PolicyGateEvaluator with T4 uncertainty tier; verify Uncertainty gate passes
- [ ] Consume unknowns budget; resolve some unknowns; verify budget capacity restored
- [ ] Query budget status via API; verify response includes per-type counts and thresholds
- [ ] Verify Hot-band unknowns consume more budget than Cold-band unknowns
- [ ] Verify Exhausted budget escalates gate level in PolicyGateEvaluator

View File

@@ -0,0 +1,39 @@
# Unknowns budget dashboard (budgeted unknowns with policy thresholds)
## Module
Policy
## Status
IMPLEMENTED
## Description
Grey queue, SLA monitoring, unknown budget service, and budget constraint enforcer implement first-class unknowns management with policy thresholds.
## Implementation Details
- **UnknownBudgetService**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownBudgetService.cs`
- Budget CRUD operations: create, query, consume, replenish, status check
- Per-type budget tracking across multiple unknown categories
- **UnknownsBudgetEnforcer**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownsBudgetEnforcer.cs`
- Constraint enforcement with Green/Yellow/Red/Exhausted thresholds
- SLA monitoring: tracks unknown resolution against SLA targets
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Prioritizes unknowns by HOT/WARM/COLD/Negligible bands
- Score = (Uncertainty * 50) + (ExploitPressure * 50)
- Reason codes for triage: AnalyzerLimit, Reachability, Identity, Provenance, VexConflict, FeedGap, ConfigUnknown
- **Grey queue models**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/`
- UnknownItem with reason code, band assignment, score, and SLA tracking
- BlastRadius (Dependents, NetFacing, Privilege)
- **BudgetEndpoints**: `src/Policy/StellaOps.Policy.Engine/Endpoints/BudgetEndpoints.cs` -- budget dashboard API
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs` -- uncertainty tier gate enforces budget thresholds
## E2E Test Plan
- [ ] Query budget dashboard; verify response includes per-type unknown counts, thresholds, and status
- [ ] Verify HOT band unknowns appear first in priority queue
- [ ] Verify SLA tracking: unknown exceeding SLA target flagged as overdue
- [ ] Consume budget; verify dashboard updates with new consumption levels
- [ ] Resolve unknowns; verify budget capacity replenished and dashboard reflects change
- [ ] Verify reason codes in dashboard: AnalyzerLimit, Reachability, Identity, etc.
- [ ] Query budget history; verify trendline shows consumption over time
- [ ] Verify budget threshold transitions are logged for audit
- [ ] Create budget with per-type limits (reachability=10, identity=5); verify independent tracking
- [ ] Verify Exhausted status prevents new releases via PolicyGateEvaluator

View File

@@ -0,0 +1,44 @@
# Unknowns Grey Queue with Conflict Detection and Reanalysis Fingerprints
## Module
Policy
## Status
IMPLEMENTED
## Description
Deterministic reanalysis fingerprints, conflict detection routing (VEX/reachability contradiction, static/runtime contradiction, VEX status conflict), grey queue with Disputed state and manual adjudication gates, versioned signal event handling.
## Implementation Details
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs`
- Reason codes for conflict detection: VexConflict (conflicting VEX claims), Reachability (unknown reachability), Identity (unknown identity), Provenance (unknown provenance)
- Uncertainty factor: Conflicting signals +0.20 to uncertainty score
- Stale evidence +0.10 to uncertainty score
- **K4Lattice conflict detection**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/K4Lattice.cs`
- K4Value.Conflict (value=3) when True join False occurs
- Conflict detection in lattice evaluation routes to grey queue
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- Pipeline detects conflicts during VEX normalization and claim ingestion
- Conflicting claims flagged for manual adjudication
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs`
- ConflictPenalizer applies 0.25 penalty to conflicting claims
- RequiresReplayProof flag set when conflicts detected
- Deterministic merge ordering ensures reproducible conflict resolution
- **DeterminizationGate**: `src/Policy/StellaOps.Policy.Engine/Gates/Determinization/DeterminizationGate.cs`
- Gates using DecayedConfidenceCalculator for stale signal detection
- Reanalysis triggering based on confidence decay below threshold
- **ObservationDecay**: `src/Policy/__Libraries/StellaOps.Policy.Determinization/Models/ObservationDecay.cs`
- Reanalysis fingerprint: ObservedAt + RefreshedAt + HalfLifeDays + DecayedMultiplier
- CheckIsStale(now) triggers reanalysis when decay below StalenessThreshold
## E2E Test Plan
- [ ] Ingest conflicting VEX claims (True + False for same subject); verify K4 Conflict state detected
- [ ] Verify conflicting claims route to grey queue with Disputed state
- [ ] Verify ConflictPenalizer applies 0.25 penalty to conflicting claims
- [ ] Verify RequiresReplayProof=true when conflicts detected
- [ ] Verify UnknownRanker adds +0.20 uncertainty for VexConflict reason code
- [ ] Detect stale reachability evidence; verify reanalysis triggered (ObservationDecay.CheckIsStale)
- [ ] Verify reanalysis fingerprint is deterministic: same inputs produce same fingerprint
- [ ] Verify versioned signal events: newer signal supersedes older signal
- [ ] Verify manual adjudication gate prevents automated resolution of Disputed unknowns
- [ ] Verify stale evidence adds +0.10 to uncertainty in UnknownRanker

View File

@@ -0,0 +1,45 @@
# Unknowns Ranking Algorithm (HOT/WARM/COLD bands)
## Module
Policy
## Status
IMPLEMENTED
## Description
Unknown ranker with weighted scoring (popularity, exploit potential, uncertainty density, centrality, staleness), HOT/WARM/COLD band assignment, and BlastRadius model. Database migration for blast radius/containment exists.
## Implementation Details
- **UnknownRanker**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRanker.cs` (sealed class)
- Two-factor scoring: Score = (Uncertainty * 50) + (ExploitPressure * 50)
- **Uncertainty factors** (sum capped at 1.0):
- Missing VEX: +0.40
- Missing reachability: +0.30
- Conflicting signals: +0.20
- Stale evidence: +0.10
- **Exploit pressure factors** (sum capped at 1.0):
- KEV flagged: +0.50
- EPSS >= 0.90: +0.30
- EPSS >= 0.50: +0.15
- CVSS >= 9.0: +0.05
- **Containment reduction** (capped at 40%):
- Isolated: 15%, NotNetFacing: 5%, NonRoot: 5%, Seccomp: 10%, FsRO: 10%, NetworkIsolated: 5%
- **Time decay**: 7d=100%, 30d=90%, 90d=75%, 180d=60%, 365d=40%, >365d=20%
- **Band assignment**: Hot >= 75, Warm >= 50, Cold >= 25, Negligible < 25
- **Reason codes**: AnalyzerLimit, Reachability, Identity, Provenance, VexConflict, FeedGap, ConfigUnknown
- **BlastRadius model**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Models/BlastRadius.cs`
- Dependents (int), NetFacing (bool), Privilege (string?)
- **UnknownRankerOptions**: `src/Policy/__Libraries/StellaOps.Policy.Unknowns/Services/UnknownRankerOptions.cs` -- configurable weights and thresholds
- **UnknownRankInput**: includes EpssScore, CvssScore, IsKev, ContainmentSignals, LastEvaluatedAt, ReasonCodes
## E2E Test Plan
- [ ] Rank unknown with missing VEX + KEV flagged; verify score = (0.40*50) + (0.50*50) = 45; band=Warm
- [ ] Rank unknown with missing VEX + missing reachability + KEV + EPSS=0.95; verify score = (0.70*50) + (0.80*50) = 75; band=Hot
- [ ] Rank unknown with no uncertainty + no exploit pressure; verify score=0; band=Negligible
- [ ] Rank unknown with Isolated containment; verify 15% reduction from raw score
- [ ] Rank unknown with all containment signals; verify exactly 40% reduction (cap)
- [ ] Rank unknown last evaluated 90 days ago; verify decay factor=0.75 applied
- [ ] Rank unknown last evaluated 365 days ago; verify decay factor=0.40 applied
- [ ] Verify band assignment: score 80 -> Hot, score 55 -> Warm, score 30 -> Cold, score 10 -> Negligible
- [ ] Verify reason codes: unknown with VexConflict produces reason=VexConflict
- [ ] Verify deterministic ranking: same inputs always produce same score and band

View File

@@ -0,0 +1,42 @@
# Verdict Explainability / Rationale Renderer
## Module
Policy
## Status
IMPLEMENTED
## Description
Verdict rationale renderer and rationale model in Policy Explainability library. Testing infrastructure includes explainability assertions, IExplainableDecision interface, and explainability models.
## Implementation Details
- **VerdictRationaleRenderer**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/VerdictRationaleRenderer.cs` (sealed class implements `IVerdictRationaleRenderer`)
- `Render(VerdictRationaleInput)` produces structured 4-line rationale
- `RenderPlainText(rationale)` produces 4-line plain text output
- `RenderMarkdown(rationale)` produces Markdown with ## headers (Evidence, Policy Clause, Attestations, Decision)
- `RenderJson(rationale)` produces canonical JSON (RFC 8785) via `CanonJson.Serialize`
- Content-addressed RationaleId: `rat:sha256:{hash}` computed from SHA256 of canonical JSON
- Evidence rendering: CVE ID, component PURL/name/version, reachability (vulnerable function, entry point, path summary)
- Policy clause rendering: ClauseId, RuleDescription, Conditions
- Attestation rendering: path witness, VEX statements, provenance references
- Decision rendering: verdict, score, recommendation, mitigation (action, details)
- **VerdictRationale model**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/VerdictRationale.cs`
- SchemaVersion: "1.0"
- 4-line template: RationaleEvidence, RationalePolicyClause, RationaleAttestations, RationaleDecision
- RationaleInputDigests: VerdictDigest, PolicyDigest, EvidenceDigest for reproducibility
- Supporting records: ComponentIdentity, ReachabilityDetail, AttestationReference, MitigationGuidance
- **IVerdictRationaleRenderer**: `src/Policy/__Libraries/StellaOps.Policy.Explainability/IVerdictRationaleRenderer.cs`
- Interface with Render, RenderPlainText, RenderMarkdown, RenderJson methods
- VerdictRationaleInput record with full input specification
## E2E Test Plan
- [ ] Render rationale for CVE-2024-1234 in lodash@4.17.21 with reachability; verify Evidence.FormattedText contains CVE, component, vulnerable function
- [ ] Render rationale with policy clause "require-vex-for-critical"; verify PolicyClause.FormattedText includes clause ID and conditions
- [ ] Render rationale with 2 VEX attestation references; verify Attestations.FormattedText includes both
- [ ] Render rationale without attestations; verify FormattedText says "No attestations available."
- [ ] Render same input twice; verify RationaleId is identical (content-addressed determinism)
- [ ] Render with score=0.85 and mitigation; verify Decision.FormattedText includes "score 0.85" and mitigation action
- [ ] RenderPlainText produces 4-line output (evidence, clause, attestations, decision)
- [ ] RenderMarkdown produces valid Markdown with ## headers
- [ ] RenderJson produces valid JSON parseable by standard parser
- [ ] Verify RationaleId matches format `rat:sha256:{64 hex chars}`

View File

@@ -0,0 +1,45 @@
# VEX Decisioning Engine (Not Just Ingestion) (Moat Score 4)
## Module
Policy
## Status
IMPLEMENTED
## Description
Full VEX decisioning with consensus engine, trust scoring, OpenVEX and CSAF normalization, and trust lattice conflict resolution.
## Implementation Details
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- Full VEX decisioning pipeline: VEX normalization -> claim ingestion -> K4 evaluation -> disposition selection -> proof bundle
- Three VEX format normalizers: CycloneDX, OpenVEX, CSAF
- Fluent ClaimBuilder: Assert, Present, Applies, Reachable, Mitigated, Fixed, Misattributed
- `Evaluate()` with optional SubjectFilter and proof bundle generation
- Disposition selection from K4 lattice values: True -> not_affected, False -> affected, Conflict -> disputed, Unknown -> under_investigation
- **K4Lattice**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/K4Lattice.cs`
- Belnap four-valued logic: Unknown=0, True=1, False=2, Conflict=3
- Join (consensus): T join F = Conflict; commutative, idempotent
- Meet (agreement): T meet F = Unknown
- FromSupport(): maps evidence support to K4 value
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs`
- Deterministic claim merging with conflict penalization (0.25 penalty)
- Merge ordering: adjusted score -> specificity -> original score -> source ID -> index
- MergePolicy: ConflictPenalty, PreferSpecificity, RequireReplayProofOnConflict
- Returns MergeResult: winning claim, conflicts, RequiresReplayProof flag
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs`
- Gates policy decisions based on VEX trust scores
- Per-environment thresholds with FailureAction (Warn/Block)
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- VEX Trust gate (3rd in 5-gate pipeline) evaluates trust lattice results
## E2E Test Plan
- [ ] Ingest CycloneDX VEX with not_affected status; verify K4 value=True after normalization
- [ ] Ingest OpenVEX with affected status; verify K4 value=False after normalization
- [ ] Ingest CSAF VEX with fixed status; verify K4 value=True after normalization
- [ ] Ingest conflicting claims (CycloneDX not_affected + OpenVEX affected); verify K4 Conflict, disposition=disputed
- [ ] Verify ClaimScoreMerger: signed claim (score 0.9) wins over unsigned claim (score 0.95) when PreferSpecificity enabled
- [ ] Verify conflict penalization: conflicting claims receive 0.25 penalty
- [ ] Evaluate with VexTrustGate in production (threshold 0.80); provide trust score 0.85; verify gate passes
- [ ] Evaluate with VexTrustGate; provide trust score 0.60 in production; verify gate blocks
- [ ] Build claim via fluent API: Assert("CVE-2024-1234").Present("pkg:npm/lodash@4.17.21").Mitigated(); verify claim correctly formed
- [ ] Verify proof bundle includes all claims, scores, and K4 evaluations for audit

View File

@@ -0,0 +1,40 @@
# VEX Format Normalization (CycloneDX, OpenVEX, CSAF)
## Module
Policy
## Status
IMPLEMENTED
## Description
Normalizers for CSAF and OpenVEX formats to convert heterogeneous VEX statements into the unified trust lattice representation.
## Implementation Details
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- Three VEX format normalizers integrated into evaluation pipeline:
- CycloneDX normalizer: converts CycloneDX VEX analysis states to K4 claims
- OpenVEX normalizer: converts OpenVEX status to K4 claims
- CSAF normalizer: converts CSAF product status to K4 claims
- All normalizers produce unified claim objects for K4 lattice evaluation
- Format-specific metadata preserved in claim provenance
- **K4Lattice**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/K4Lattice.cs`
- Unified representation: Unknown=0, True=1, False=2, Conflict=3
- `FromSupport()` maps normalized evidence to K4 values
- **ClaimBuilder**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- Fluent API for building claims from any format:
- Assert(cve).Present(component).Mitigated() -> K4 True
- Assert(cve).Present(component).Applies() -> K4 False (affected)
- Assert(cve).Present(component).Fixed() -> K4 True (fixed version)
- Assert(cve).Present(component).Misattributed() -> K4 True (not applicable)
- **Trust lattice directory**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/` (15 files total)
## E2E Test Plan
- [ ] Normalize CycloneDX VEX with status "not_affected" and justification "code_not_reachable"; verify K4 True claim with correct provenance
- [ ] Normalize OpenVEX with status "affected"; verify K4 False claim
- [ ] Normalize CSAF with status "known_affected" and remediation "vendor_fix"; verify K4 claim reflects affected + fix available
- [ ] Normalize CycloneDX VEX with status "fixed"; verify K4 True claim (vulnerability fixed)
- [ ] Normalize all 3 formats for same CVE; merge via ClaimScoreMerger; verify deterministic result
- [ ] Normalize VEX with invalid format; verify error handling (parse failure does not crash pipeline)
- [ ] Verify format-specific metadata preserved: CycloneDX justification, OpenVEX statement, CSAF product_status
- [ ] Normalize VEX from unknown format; verify treated as Unknown K4 value
- [ ] Verify all normalizers produce claims compatible with K4Lattice.Join() and Meet()

View File

@@ -0,0 +1,40 @@
# VEX Status Promotion Gate
## Module
Policy
## Status
IMPLEMENTED
## Description
Promotion gate that blocks environment promotions based on VEX status thresholds, ensuring only properly triaged artifacts can advance.
## Implementation Details
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` (implements `IVexTrustGate`)
- `EvaluateAsync(VexTrustGateRequest)` evaluates VEX trust for status transitions
- VexTrustGateRequest: RequestedStatus, Environment, VexTrustStatus, TenantId
- VexTrustStatus: TrustScore (0.0-1.0), PolicyTrustThreshold, MeetsPolicyThreshold, TrustBreakdown
- Per-environment evaluation: production requires highest trust, development most permissive
- **VexTrustGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateOptions.cs`
- ApplyToStatuses: ["not_affected", "fixed"] -- statuses requiring trust verification
- Per-environment thresholds:
- Production: MinCompositeScore=0.80, RequireIssuerVerified=true, MinAccuracyRate=0.85, AcceptableFreshness=["fresh"], FailureAction=Block
- Staging: MinCompositeScore=0.60, RequireIssuerVerified=true, AcceptableFreshness=["fresh","stale"], FailureAction=Warn
- Development: MinCompositeScore=0.40, RequireIssuerVerified=false, AcceptableFreshness=["fresh","stale","superseded"], FailureAction=Warn
- MissingTrustBehavior: Allow, Warn, Block
- TenantOverrides for tenant-specific thresholds
- **PolicyGateEvaluator**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- VEX Trust gate (3rd in pipeline) blocks promotion when trust insufficient
- VEX trust evaluation integrated with lattice state and uncertainty tier gates
## E2E Test Plan
- [ ] Request promotion to production with trust score 0.85; verify gate passes
- [ ] Request promotion to production with trust score 0.70; verify gate blocks (threshold 0.80)
- [ ] Request promotion to staging with trust score 0.65; verify gate passes (threshold 0.60)
- [ ] Request promotion with stale VEX in production; verify gate blocks (only "fresh" acceptable)
- [ ] Request promotion with stale VEX in staging; verify gate passes (stale acceptable)
- [ ] Request promotion with unverified issuer in production; verify gate blocks
- [ ] Request promotion with unverified issuer in development; verify gate passes
- [ ] Request promotion with MissingTrustBehavior=Block and no VEX data; verify gate blocks
- [ ] Verify tenant-specific overrides apply when TenantId matches
- [ ] Verify gate returns descriptive message identifying which threshold was not met

View File

@@ -0,0 +1,47 @@
# VEX Trust Lattice with Provenance/Coverage/Replayability Scoring
## Module
Policy
## Status
IMPLEMENTED
## Description
Full trust lattice engine with claim score merging, conflict penalization, trust labels, and configurable trust source weights per the advisory's P/C/R model.
## Implementation Details
- **TrustLatticeEngine**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/TrustLatticeEngine.cs`
- P/C/R scoring model: Provenance, Coverage, Replayability
- Pipeline: VEX normalization -> claim ingestion -> K4 evaluation -> disposition selection -> proof bundle
- Trust labels derived from K4 lattice values and claim scores
- Configurable trust source weights per claim source
- **K4Lattice**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/K4Lattice.cs`
- Four-valued trust algebra: Unknown=0, True=1, False=2, Conflict=3
- Join: T join F = Conflict (contradictory evidence produces conflict)
- Meet: T meet F = Unknown (no agreement reduces to unknown)
- LessOrEqual: lattice ordering for trust comparisons
- **ClaimScoreMerger**: `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/ClaimScoreMerger.cs`
- Deterministic merge with configurable MergePolicy
- ConflictPenalizer: applies 0.25 penalty to conflicting claims
- PreferSpecificity: more specific claims (exact PURL vs wildcard) preferred
- RequireReplayProofOnConflict: flags conflicts requiring replay verification
- Merge ordering: adjusted score -> specificity -> original score -> source ID -> index
- Returns MergeResult: winning claim, conflicts list, RequiresReplayProof flag
- **VexTrustGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateOptions.cs`
- Per-environment trust thresholds with P/C/R scoring integration
- Production: MinCompositeScore=0.80 (requires high P/C/R)
- Development: MinCompositeScore=0.40 (accepts lower P/C/R)
- **Trust lattice files** (15 files in `src/Policy/__Libraries/StellaOps.Policy/TrustLattice/`):
- Normalizers, claim builders, score mergers, lattice algebra
## E2E Test Plan
- [ ] Evaluate claim with high Provenance (signed, verified issuer) + high Coverage (exact CVE+PURL match) + high Replayability (deterministic); verify high composite trust score
- [ ] Evaluate claim with low Provenance (unsigned) + low Coverage (wildcard match); verify low composite score
- [ ] Merge 2 claims: one with high P/C/R, one with low P/C/R; verify high-scoring claim wins
- [ ] Merge conflicting claims; verify ConflictPenalizer reduces both scores by 0.25
- [ ] Verify PreferSpecificity: exact PURL claim beats wildcard PURL claim even with lower raw score
- [ ] Verify RequiresReplayProof flag is set when conflicting claims are merged
- [ ] Verify deterministic merge: same inputs always produce same MergeResult
- [ ] Evaluate trust lattice with Join(True, False); verify K4 Conflict
- [ ] Evaluate trust lattice with Meet(True, False); verify K4 Unknown
- [ ] Verify trust labels derived from K4 values: True -> "trusted", False -> "untrusted", Conflict -> "disputed", Unknown -> "unverified"

View File

@@ -0,0 +1,43 @@
# VexTrustGate Policy Integration
## Module
Policy
## Status
IMPLEMENTED
## Description
Integrates VEX trust evaluation as a named policy gate in the policy evaluation chain. VexTrustGate validates VEX statement trust levels against configurable thresholds before accepting VEX-based risk reductions. Registered in the GateSelector alongside existing gates. Distinct from known "VEX Trust Scoring" (which computes scores) -- this gates policy decisions based on those scores.
## Implementation Details
- **VexTrustGate**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGate.cs` (implements `IVexTrustGate`)
- `EvaluateAsync(VexTrustGateRequest)` evaluates trust score against thresholds
- Returns VexTrustGateResult with decision (Pass/Warn/Block), details, and recommendations
- Checks: composite score >= threshold, issuer verified, accuracy rate, freshness
- **VexTrustGateOptions**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateOptions.cs`
- Section key: `"Policy:Gates:VexTrust"`
- Enabled flag (default true)
- ApplyToStatuses: ["not_affected", "fixed"]
- Per-environment thresholds (production/staging/development/default)
- MissingTrustBehavior: Allow, Warn, Block
- EmitMetrics: true (OpenTelemetry)
- TenantOverrides for multi-tenant deployments
- **PolicyGateEvaluator integration**: `src/Policy/StellaOps.Policy.Engine/Gates/PolicyGateEvaluator.cs`
- VEX Trust gate is 3rd in the 5-gate sequential pipeline
- Evaluates after Evidence Completeness and Lattice State gates
- Per-environment thresholds with MissingTrustBehavior fallback
- **VexTrustGateMetrics**: `src/Policy/StellaOps.Policy.Engine/Gates/VexTrustGateMetrics.cs`
- OpenTelemetry metrics: gate decisions, trust scores, evaluation duration
- Tags: environment, decision, trust_score_bucket
## E2E Test Plan
- [ ] Evaluate VEX trust in production with score 0.85 (above 0.80 threshold); verify gate passes
- [ ] Evaluate VEX trust in production with score 0.75 (below 0.80 threshold); verify gate blocks
- [ ] Evaluate VEX trust in staging with score 0.55 (below 0.60 threshold); verify gate warns (FailureAction=Warn)
- [ ] Evaluate VEX trust in development with score 0.35 (below 0.40 threshold); verify gate warns
- [ ] Evaluate without VEX trust data, MissingTrustBehavior=Warn; verify gate warns with descriptive message
- [ ] Evaluate without VEX trust data, MissingTrustBehavior=Block; verify gate blocks
- [ ] Evaluate without VEX trust data, MissingTrustBehavior=Allow; verify gate passes
- [ ] Configure TenantOverrides for tenant-A with custom staging threshold 0.70; evaluate in staging for tenant-A; verify custom threshold used
- [ ] Verify VexTrustGateMetrics emits gate decision metric with environment and decision tags
- [ ] Disable VexTrustGate (Enabled=false); evaluate; verify gate is skipped in pipeline