-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

{- | The policy engine denies by default and decides in boot order. One advisory read per package
serves every advisory rule an evaluator reaches, so a request's decisions read one generation.
-}
module Ecluse.Core.Rules (
    -- * The boot-bound rule capabilities
    RuleDeps (..),
    AdvisoryDatabase (..),
    AdvisoryGeneration (..),
    withCveLookup,

    -- * The built-in rule dispatch
    VerdictSource (..),
    AdvisoryAlignment (..),
    verdictSource,
    AdvisoryRows,
    readAdvisories,

    -- * The engine's prepared rule
    PreparedRule (..),
    RuleEval (..),
    PackageRead (..),
    Resilience (..),
    prepare,
    prepResilience,

    -- * Boot-time ordering
    bootOrder,
    renderBootOrder,

    -- * Evaluation
    newEvaluator,
    evalRules,
    pushInability,

    -- * Observing the advisory source
    SourceHealth (..),
    SourceReporter (..),
    noSourceReporter,
) where

import Data.Fixed (Fixed (MkFixed))
import Data.Text qualified as T
import Data.Text.Short qualified as TS
import Data.Time (NominalDiffTime, UTCTime (UTCTime), diffDays, diffTimeToPicoseconds, getCurrentTime, secondsToNominalDiffTime)
import Data.Time.Clock.POSIX (posixDayLength)
import UnliftIO (evaluate, tryAny)
import UnliftIO.MVar (withMVar)

import Ecluse.Core.Breaker (BreakerReporter (..))
import Ecluse.Core.Cve (AdvisoryRange (..), CveLookup (..), MissingScorePolicy (..), PackageAdvisories, advisoryIdsOf, affecting, hasAdvisories, keepAdvisories, packageAdvisories, scoreAtLeast)
import Ecluse.Core.Cve.Types (DbEtag)
import Ecluse.Core.Package
import Ecluse.Core.Rules.Effectful (
    ReadFault (..),
    Resilience (..),
    defaultEffectfulConfig,
    newBreaker,
    runResilient,
 )
import Ecluse.Core.Rules.Freshness (AdvisoryFreshness (AdvisoryAging, AdvisoryFresh, AdvisoryStale, AdvisoryUndated))
import Ecluse.Core.Rules.Outage (SourceHealth (..), SourceReporter (..), noSourceReporter)
import Ecluse.Core.Rules.Remediation (remediationVerdict)
import Ecluse.Core.Rules.Types
import Ecluse.Core.Text (displayExceptionT)
import Ecluse.Core.Version (renderVersion)

-- | One ecosystem's boot-bound rule capabilities: its advisory database and the rules' observers.
data RuleDeps = RuleDeps
    { RuleDeps -> AdvisoryDatabase
rdAdvisoryDatabase :: AdvisoryDatabase
    , RuleDeps -> IO (Maybe DbEtag)
rdCurrentAdvisoryEtag :: IO (Maybe DbEtag)
    -- ^ Read the active ETag without pinning or delaying a swap.
    , RuleDeps -> BreakerReporter
rdBreakerReporter :: BreakerReporter
    -- ^ Where advisory rules report breaker transitions, as @ecluse.rule.breaker.state@.
    , RuleDeps -> SourceReporter
rdSourceReporter :: SourceReporter
    -- ^ Report source availability as outage transitions for each reached advisory rule.
    , RuleDeps -> IO AdvisoryFreshness
rdAdvisoryFreshness :: IO AdvisoryFreshness
    -- ^ The live slot age for the Dredger's final deletion check. Advisory reads use their borrowed age.
    }

-- | An ecosystem's advisory database, as configuration fixes it at boot.
data AdvisoryDatabase
    = NoAdvisoryDatabase
    | -- | Hold one generation's age reading and lookup access together through the caller's action.
      AdvisoryDatabase (forall a. (AdvisoryGeneration -> IO a) -> IO a)

-- | The age and lookup capabilities borrowed from one advisory generation.
data AdvisoryGeneration = AdvisoryGeneration
    { AdvisoryGeneration -> IO AdvisoryFreshness
agFreshness :: IO AdvisoryFreshness
    -- ^ Assess the borrowed publication timestamp against the existing clock and maximum age.
    , AdvisoryGeneration
-> forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
agLookup :: forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
    -- ^ Access the borrowed lookup. Query failures belong to the caller's resilience policy.
    }

-- | Borrow the loaded generation, or 'Nothing' when none is configured or none has loaded yet.
withCveLookup :: RuleDeps -> (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
withCveLookup :: forall a. RuleDeps -> (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
withCveLookup RuleDeps
deps Maybe (DbEtag, CveLookup) -> IO a
use = case RuleDeps -> AdvisoryDatabase
rdAdvisoryDatabase RuleDeps
deps of
    AdvisoryDatabase
NoAdvisoryDatabase -> Maybe (DbEtag, CveLookup) -> IO a
use Maybe (DbEtag, CveLookup)
forall a. Maybe a
Nothing
    AdvisoryDatabase forall a. (AdvisoryGeneration -> IO a) -> IO a
borrow -> (AdvisoryGeneration -> IO a) -> IO a
forall a. (AdvisoryGeneration -> IO a) -> IO a
borrow (\AdvisoryGeneration{forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
agLookup :: AdvisoryGeneration
-> forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
agLookup :: forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
agLookup} -> (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
agLookup Maybe (DbEtag, CveLookup) -> IO a
use)

-- | One package's advisory rows and the generation that served them, or 'Nothing' while none is loaded.
type AdvisoryRows = Maybe (DbEtag, PackageAdvisories)

-- | Parse one borrowed generation's package rows once for all versions. Query faults escape.
readAdvisories :: PackageName -> Maybe (DbEtag, CveLookup) -> IO AdvisoryRows
readAdvisories :: PackageName -> Maybe (DbEtag, CveLookup) -> IO AdvisoryRows
readAdvisories PackageName
name =
    ((DbEtag, CveLookup) -> IO (DbEtag, PackageAdvisories))
-> Maybe (DbEtag, CveLookup) -> IO AdvisoryRows
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Maybe a -> f (Maybe b)
traverse (\(DbEtag
etag, CveLookup
cve) -> (DbEtag
etag,) (PackageAdvisories -> (DbEtag, PackageAdvisories))
-> ([AdvisoryRange] -> PackageAdvisories)
-> [AdvisoryRange]
-> (DbEtag, PackageAdvisories)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Ecosystem -> [AdvisoryRange] -> PackageAdvisories
packageAdvisories (PackageName -> Ecosystem
pkgEcosystem PackageName
name) ([AdvisoryRange] -> (DbEtag, PackageAdvisories))
-> IO [AdvisoryRange] -> IO (DbEtag, PackageAdvisories)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CveLookup -> Text -> IO [AdvisoryRange]
cveAdvisoriesFor CveLookup
cve (ShortText -> Text
TS.toText (PackageName -> ShortText
pkgCanonical PackageName
name)))

-- | Where a built-in rule's verdict comes from.
data VerdictSource
    = -- | One version's evidence and the request context.
      FromEvidence (EvalContext -> RuleEvidence -> RuleVerdict)
    | -- | The package's advisory rows, with how the rule resolves when it cannot read them.
      FromAdvisories AdvisoryAlignment (AdvisoryRows -> RuleEvidence -> RuleVerdict)

-- | How an advisory rule resolves when it cannot read: on an expired push, and on a faulted read.
data AdvisoryAlignment = AdvisoryAlignment
    { AdvisoryAlignment -> FailureAlignment
onExpiredPush :: FailureAlignment
    -- ^ A deny refuses an expired push under any configuration. The remediation allow takes its one choice here too.
    , AdvisoryAlignment -> FailureAlignment
onFaultedRead :: FailureAlignment
    -- ^ The rule's configured alignment for a timeout, a spent retry budget, or an open breaker.
    }

-- | Dispatch the closed rule vocabulary. An unread required fact refuses instead of abstaining.
verdictSource :: Rule -> VerdictSource
verdictSource :: Rule -> VerdictSource
verdictSource = \case
    AllowScope Scope
scope -> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
_ RuleEvidence
ev -> case PackageName -> Maybe Scope
pkgNamespace (RuleEvidence -> PackageName
evName RuleEvidence
ev) of
        Just Scope
s | Scope
s Scope -> Scope -> Bool
forall a. Eq a => a -> a -> Bool
== Scope
scope -> Reason -> RuleVerdict
Allow (Scope -> Reason
ScopeAllowListed Scope
scope)
        Maybe Scope
_ -> Reason -> RuleVerdict
NoDecision (Scope -> Reason
ScopeNotAllowListed Scope
scope)
    AllowIfOlderThan NominalDiffTime
minAge -> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
ctx RuleEvidence
ev -> case RuleEvidence -> Fact (Maybe UTCTime)
evPublishedAt RuleEvidence
ev of
        Fact (Maybe UTCTime)
Unread -> FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
FailDeny Inability
PublishTimeUnread
        Known Maybe UTCTime
Nothing -> Reason -> RuleVerdict
NoDecision Reason
PublishTimeUnknown
        Known (Just UTCTime
publishedAt) -> NominalDiffTime -> NominalDiffTime -> RuleVerdict
ageVerdict NominalDiffTime
minAge (UTCTime -> UTCTime -> NominalDiffTime
ageSince (EvalContext -> UTCTime
ctxNow EvalContext
ctx) UTCTime
publishedAt)
    Rule
DenyInstallTimeExecution -> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
_ RuleEvidence
ev -> case RuleEvidence -> Fact CodeExecSignal
evInstallCode RuleEvidence
ev of
        Fact CodeExecSignal
Unread -> FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
FailDeny Inability
InstallSignalUnread
        Known (RunsCodeOnInstall Text
how) -> Maybe DbEtag -> Reason -> RuleVerdict
Deny Maybe DbEtag
forall a. Maybe a
Nothing (Text -> Reason
RunsOnInstall Text
how)
        Known CodeExecSignal
NoCodeOnInstall -> Reason -> RuleVerdict
NoDecision Reason
NothingRunsOnInstall
        Known CodeExecSignal
CodeExecUnknown -> Reason -> RuleVerdict
NoDecision Reason
InstallCodeUndetermined
    Rule
DenyExternalDependencies -> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
_ RuleEvidence
ev -> case RuleEvidence -> Fact DependencySources
evDependencySources RuleEvidence
ev of
        Fact DependencySources
Unread -> FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
FailDeny Inability
DependencySourcesUnread
        Known (FetchesOutsideRegistry Text
which) -> Maybe DbEtag -> Reason -> RuleVerdict
Deny Maybe DbEtag
forall a. Maybe a
Nothing (Text -> Reason
FetchesOutside Text
which)
        Known DependencySources
RegistryDependencies -> Reason -> RuleVerdict
NoDecision Reason
DependenciesThroughRegistry
        Known DependencySources
DependencySourcesUnknown -> Reason -> RuleVerdict
NoDecision Reason
DependencySourcesUndetermined
    Rule
DenyIfYanked -> Availability -> Reason -> Reason -> VerdictSource
availabilityVerdict Availability
Yanked Reason
VersionYanked Reason
VersionNotYanked
    Rule
DenyIfDeprecated -> Availability -> Reason -> Reason -> VerdictSource
availabilityVerdict Availability
Deprecated Reason
VersionDeprecated Reason
VersionNotDeprecated
    DenyByIdentity Text
ident -> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
_ RuleEvidence
ev ->
        if Text -> RuleEvidence -> Bool
matchesIdentity Text
ident RuleEvidence
ev
            then Maybe DbEtag -> Reason -> RuleVerdict
Deny Maybe DbEtag
forall a. Maybe a
Nothing (Text -> Reason
IdentityRevoked Text
ident)
            else Reason -> RuleVerdict
NoDecision (Text -> Reason
IdentityNotRevoked Text
ident)
    AllowByIdentity Text
ident -> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
_ RuleEvidence
ev ->
        if Text -> RuleEvidence -> Bool
matchesIdentity Text
ident RuleEvidence
ev
            then Reason -> RuleVerdict
Allow (Text -> Reason
IdentityAllowListed Text
ident)
            else Reason -> RuleVerdict
NoDecision (Text -> Reason
IdentityNotAllowListed Text
ident)
    -- The remediation allow's one choice governs every unavailability, an expired push included.
    AllowIfRemediatesCve AllowIfRemediatesCveParams
params ->
        let alignment :: FailureAlignment
alignment = AllowIfRemediatesCveParams -> FailureAlignment
aircOnUnavailable AllowIfRemediatesCveParams
params
            decide :: PackageAdvisories -> RuleEvidence -> RuleVerdict
decide = RemainingAdvisories
-> PackageAdvisories -> RuleEvidence -> RuleVerdict
remediationVerdict (AllowIfRemediatesCveParams -> RemainingAdvisories
aircRemaining AllowIfRemediatesCveParams
params)
         in AdvisoryAlignment
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromAdvisories (FailureAlignment -> FailureAlignment -> AdvisoryAlignment
AdvisoryAlignment FailureAlignment
alignment FailureAlignment
alignment) ((AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \case
                AdvisoryRows
Nothing -> RuleVerdict -> RuleEvidence -> RuleVerdict
forall a b. a -> b -> a
const (FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
alignment Inability
NoDatabaseLoaded)
                Just (DbEtag
_, PackageAdvisories
advisories) -> PackageAdvisories -> RuleEvidence -> RuleVerdict
decide PackageAdvisories
advisories
    -- No in-process retry could load a database, so its absence is a verdict and never a fault.
    DenyIfCve DenyIfCveParams
params -> AdvisoryAlignment
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromAdvisories (FailureAlignment -> FailureAlignment -> AdvisoryAlignment
AdvisoryAlignment FailureAlignment
FailDeny (DenyIfCveParams -> FailureAlignment
dicOnUnavailable DenyIfCveParams
params)) ((AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \case
        AdvisoryRows
Nothing -> RuleVerdict -> RuleEvidence -> RuleVerdict
forall a b. a -> b -> a
const (FailureAlignment -> Inability -> RuleVerdict
CannotVet (DenyIfCveParams -> FailureAlignment
dicOnUnavailable DenyIfCveParams
params) Inability
NoDatabaseLoaded)
        Just (DbEtag
etag, PackageAdvisories
advisories) -> DbEtag
-> MissingScorePolicy
-> AdvisoryScore
-> Double
-> (AdvisoryRange -> Maybe Double)
-> PackageAdvisories
-> RuleEvidence
-> RuleVerdict
advisoryDenyVerdict DbEtag
etag MissingScorePolicy
DenyMissingScore AdvisoryScore
Cvss (DenyIfCveParams -> Double
dicMinCvss DenyIfCveParams
params) AdvisoryRange -> Maybe Double
arSeverity PackageAdvisories
advisories
    DenyIfKnownMalicious FailureAlignment
alignment -> AdvisoryAlignment
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromAdvisories (FailureAlignment -> FailureAlignment -> AdvisoryAlignment
AdvisoryAlignment FailureAlignment
FailDeny FailureAlignment
alignment) ((AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \case
        AdvisoryRows
Nothing -> RuleVerdict -> RuleEvidence -> RuleVerdict
forall a b. a -> b -> a
const (FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
alignment Inability
NoDatabaseLoaded)
        Just (DbEtag
etag, PackageAdvisories
advisories) ->
            DbEtag
-> (AdvisoryIds -> Reason)
-> Reason
-> PackageAdvisories
-> RuleEvidence
-> RuleVerdict
affectedVerdict DbEtag
etag AdvisoryIds -> Reason
KnownMalicious Reason
NoKnownMaliciousAdvisory ((AdvisoryRange -> Bool) -> PackageAdvisories -> PackageAdvisories
keepAdvisories AdvisoryRange -> Bool
isMalicious PackageAdvisories
advisories)
    DenyIfEpss DenyIfEpssParams
params -> AdvisoryAlignment
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromAdvisories (FailureAlignment -> FailureAlignment -> AdvisoryAlignment
AdvisoryAlignment FailureAlignment
FailDeny (DenyIfEpssParams -> FailureAlignment
dieOnUnavailable DenyIfEpssParams
params)) ((AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \case
        AdvisoryRows
Nothing -> RuleVerdict -> RuleEvidence -> RuleVerdict
forall a b. a -> b -> a
const (FailureAlignment -> Inability -> RuleVerdict
CannotVet (DenyIfEpssParams -> FailureAlignment
dieOnUnavailable DenyIfEpssParams
params) Inability
NoDatabaseLoaded)
        Just (DbEtag
etag, PackageAdvisories
advisories) -> DbEtag
-> MissingScorePolicy
-> AdvisoryScore
-> Double
-> (AdvisoryRange -> Maybe Double)
-> PackageAdvisories
-> RuleEvidence
-> RuleVerdict
advisoryDenyVerdict DbEtag
etag MissingScorePolicy
AbstainMissingScore AdvisoryScore
Epss (DenyIfEpssParams -> Double
dieMinEpss DenyIfEpssParams
params) AdvisoryRange -> Maybe Double
arEpss PackageAdvisories
advisories

availabilityVerdict :: Availability -> Reason -> Reason -> VerdictSource
availabilityVerdict :: Availability -> Reason -> Reason -> VerdictSource
availabilityVerdict Availability
flag Reason
denied Reason
absent = (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
FromEvidence ((EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource)
-> (EvalContext -> RuleEvidence -> RuleVerdict) -> VerdictSource
forall a b. (a -> b) -> a -> b
$ \EvalContext
_ RuleEvidence
ev -> case RuleEvidence -> Fact Availability
evAvailability RuleEvidence
ev of
    Fact Availability
Unread -> FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
FailDeny Inability
AvailabilityUnread
    Known Availability
actual
        | Availability
actual Availability -> Availability -> Bool
forall a. Eq a => a -> a -> Bool
== Availability
flag -> Maybe DbEtag -> Reason -> RuleVerdict
Deny Maybe DbEtag
forall a. Maybe a
Nothing Reason
denied
        | Bool
otherwise -> Reason -> RuleVerdict
NoDecision Reason
absent

-- The quarantine gives the registry time to yank a malicious publish.
ageVerdict :: NominalDiffTime -> NominalDiffTime -> RuleVerdict
ageVerdict :: NominalDiffTime -> NominalDiffTime -> RuleVerdict
ageVerdict NominalDiffTime
minAge NominalDiffTime
age
    | NominalDiffTime
age NominalDiffTime -> NominalDiffTime -> Bool
forall a. Ord a => a -> a -> Bool
>= NominalDiffTime
minAge = Reason -> RuleVerdict
Allow (NominalDiffTime -> NominalDiffTime -> Reason
PublishedLongEnough NominalDiffTime
age NominalDiffTime
minAge)
    | Bool
otherwise = Reason -> RuleVerdict
NoDecision (NominalDiffTime -> NominalDiffTime -> Reason
PublishedTooRecently NominalDiffTime
age NominalDiffTime
minAge)

-- Equal to 'diffUTCTime' in exact Pico arithmetic, without its two POSIX conversions through
-- picosecond products past 2^64. The time of day clamps at 'posixDayLength' as it does there.
ageSince :: UTCTime -> UTCTime -> NominalDiffTime
ageSince :: UTCTime -> UTCTime -> NominalDiffTime
ageSince (UTCTime Day
nowDay DiffTime
nowTime) (UTCTime Day
day DiffTime
time) =
    Pico -> NominalDiffTime
secondsToNominalDiffTime (Integer -> Pico
forall k (a :: k). Integer -> Fixed a
MkFixed (Day -> Day -> Integer
diffDays Day
nowDay Day
day Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
dayPicos Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ DiffTime -> Integer
clamped DiffTime
nowTime Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- DiffTime -> Integer
clamped DiffTime
time))
  where
    clamped :: DiffTime -> Integer
clamped DiffTime
t = Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min Integer
dayPicos (DiffTime -> Integer
diffTimeToPicoseconds DiffTime
t)

dayPicos :: Integer
dayPicos :: Integer
dayPicos = DiffTime -> Integer
diffTimeToPicoseconds (NominalDiffTime -> DiffTime
forall a b. (Real a, Fractional b) => a -> b
realToFrac NominalDiffTime
posixDayLength)

-- The score filter and the abstention no version changes are built once per read.
advisoryDenyVerdict :: DbEtag -> MissingScorePolicy -> AdvisoryScore -> Double -> (AdvisoryRange -> Maybe Double) -> PackageAdvisories -> RuleEvidence -> RuleVerdict
advisoryDenyVerdict :: DbEtag
-> MissingScorePolicy
-> AdvisoryScore
-> Double
-> (AdvisoryRange -> Maybe Double)
-> PackageAdvisories
-> RuleEvidence
-> RuleVerdict
advisoryDenyVerdict DbEtag
etag MissingScorePolicy
missing AdvisoryScore
score Double
threshold AdvisoryRange -> Maybe Double
scoreOf PackageAdvisories
advisories =
    DbEtag
-> (AdvisoryIds -> Reason)
-> Reason
-> PackageAdvisories
-> RuleEvidence
-> RuleVerdict
affectedVerdict DbEtag
etag (AdvisoryScore -> Double -> AdvisoryIds -> Reason
AffectedBy AdvisoryScore
score Double
threshold) (AdvisoryScore -> Reason
NotAffectedAtThreshold AdvisoryScore
score) PackageAdvisories
scored
  where
    scored :: PackageAdvisories
scored = (AdvisoryRange -> Bool) -> PackageAdvisories -> PackageAdvisories
keepAdvisories (MissingScorePolicy -> Double -> Maybe Double -> Bool
scoreAtLeast MissingScorePolicy
missing Double
threshold (Maybe Double -> Bool)
-> (AdvisoryRange -> Maybe Double) -> AdvisoryRange -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AdvisoryRange -> Maybe Double
scoreOf) PackageAdvisories
advisories

isMalicious :: AdvisoryRange -> Bool
isMalicious :: AdvisoryRange -> Bool
isMalicious = Bool -> (Text -> Bool) -> Maybe Text -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) (Maybe Text -> Bool)
-> (AdvisoryRange -> Maybe Text) -> AdvisoryRange -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text -> Maybe Text
T.stripPrefix Text
"MAL-" (Text -> Maybe Text)
-> (AdvisoryRange -> Text) -> AdvisoryRange -> Maybe Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AdvisoryRange -> Text
arCveId

-- Filtering happens once per package. With no segment left, every version shares one abstention.
affectedVerdict :: DbEtag -> (AdvisoryIds -> Reason) -> Reason -> PackageAdvisories -> RuleEvidence -> RuleVerdict
affectedVerdict :: DbEtag
-> (AdvisoryIds -> Reason)
-> Reason
-> PackageAdvisories
-> RuleEvidence
-> RuleVerdict
affectedVerdict DbEtag
etag AdvisoryIds -> Reason
affectedReason Reason
absentReason PackageAdvisories
advisories
    | PackageAdvisories -> Bool
hasAdvisories PackageAdvisories
advisories = \RuleEvidence
ev -> case [AdvisoryRange] -> [Text]
advisoryIdsOf (PackageAdvisories -> Version -> [AdvisoryRange]
affecting PackageAdvisories
advisories (RuleEvidence -> Version
evVersion RuleEvidence
ev)) of
        [] -> RuleVerdict
absent
        Text
affected : [Text]
more -> Maybe DbEtag -> Reason -> RuleVerdict
Deny (DbEtag -> Maybe DbEtag
forall a. a -> Maybe a
Just DbEtag
etag) (AdvisoryIds -> Reason
affectedReason (NonEmpty Text -> AdvisoryIds
mkAdvisoryIds (Text
affected Text -> [Text] -> NonEmpty Text
forall a. a -> [a] -> NonEmpty a
:| [Text]
more)))
    | Bool
otherwise = RuleVerdict -> RuleEvidence -> RuleVerdict
forall a b. a -> b -> a
const RuleVerdict
absent
  where
    absent :: RuleVerdict
absent = Reason -> RuleVerdict
NoDecision Reason
absentReason

-- The one identity test the by-identity twins share: the exact rendered package
-- name, or the exact package@version.
matchesIdentity :: Text -> RuleEvidence -> Bool
matchesIdentity :: Text -> RuleEvidence -> Bool
matchesIdentity Text
ident RuleEvidence
ev =
    let pkgStr :: Text
pkgStr = PackageName -> Text
renderPackageName (RuleEvidence -> PackageName
evName RuleEvidence
ev)
        pkgAtVer :: Text
pkgAtVer = Text
pkgStr Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"@" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Version -> Text
renderVersion (RuleEvidence -> Version
evVersion RuleEvidence
ev)
     in Text
ident Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
pkgStr Bool -> Bool -> Bool
|| Text
ident Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
pkgAtVer

-- | Config obtains evaluators only through 'prepare', never from arbitrary code.
data PreparedRule = PreparedRule
    { PreparedRule -> Text
prepName :: Text
    -- ^ The stable, human-facing name: the boot-order tiebreak and the credited identity.
    , PreparedRule -> Int
prepPrecedence :: Int
    -- ^ The precedence at which this rule competes. Higher wins in the boot order.
    , PreparedRule -> RuleEval
prepEval :: RuleEval
    -- ^ How the rule reaches the versions an evaluator decides.
    }

-- | How a prepared rule reaches the versions an evaluator decides.
data RuleEval
    = -- | Each version's verdict. It can run more than once for a version and must answer alike. A throw refuses admission.
      PerVersion (EvalContext -> RuleEvidence -> IO RuleVerdict)
    | -- | A verdict for each version from the evaluator's one advisory read of the package.
      PerPackage PackageRead

-- | A rule's bracketed advisory read and its verdict over the shared result.
data PackageRead = PackageRead
    { PackageRead
-> forall a.
   PackageName
   -> (AdvisoryFreshness -> IO AdvisoryRows -> IO a) -> IO a
prRead :: forall a. PackageName -> (AdvisoryFreshness -> IO AdvisoryRows -> IO a) -> IO a
    -- ^ Hold the assessed generation open while the caller gates its age and reads its rows.
    , PackageRead -> Maybe Resilience
prResilience :: Maybe Resilience
    -- ^ The policy around the read, or 'Nothing' where no database is configured and the read does no IO.
    , PackageRead -> AdvisoryAlignment
prAlignment :: AdvisoryAlignment
    -- ^ How this rule resolves an ineligible push and a faulted read.
    , PackageRead -> AdvisoryRows -> RuleEvidence -> RuleVerdict
prVerdict :: AdvisoryRows -> RuleEvidence -> RuleVerdict
    -- ^ This rule's verdict for each version, from the rows.
    , PackageRead -> SourceReporter
prReporter :: SourceReporter
    -- ^ Where this rule reports whether the read let it consult the source.
    }

-- | The resilience policy a prepared rule's package read runs under, if any.
prepResilience :: PreparedRule -> Maybe Resilience
prepResilience :: PreparedRule -> Maybe Resilience
prepResilience PreparedRule
rule = case PreparedRule -> RuleEval
prepEval PreparedRule
rule of
    PerVersion EvalContext -> RuleEvidence -> IO RuleVerdict
_ -> Maybe Resilience
forall a. Maybe a
Nothing
    PerPackage PackageRead
packageRead -> PackageRead -> Maybe Resilience
prResilience PackageRead
packageRead

-- | Allocate each advisory rule's breaker once. Unconfigured databases need no resilience.
prepare :: RuleDeps -> [PrecededRule] -> IO [PreparedRule]
prepare :: RuleDeps -> [PrecededRule] -> IO [PreparedRule]
prepare RuleDeps
deps = (PrecededRule -> IO PreparedRule)
-> [PrecededRule] -> IO [PreparedRule]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (RuleDeps -> PrecededRule -> IO PreparedRule
prepareRule RuleDeps
deps)

prepareRule :: RuleDeps -> PrecededRule -> IO PreparedRule
prepareRule :: RuleDeps -> PrecededRule -> IO PreparedRule
prepareRule RuleDeps
deps (PrecededRule Int
prec RuleReach
_ Rule
rule) = do
    eval <- case Rule -> VerdictSource
verdictSource Rule
rule of
        FromEvidence EvalContext -> RuleEvidence -> RuleVerdict
verdict -> RuleEval -> IO RuleEval
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((EvalContext -> RuleEvidence -> IO RuleVerdict) -> RuleEval
PerVersion (\EvalContext
ctx -> RuleVerdict -> IO RuleVerdict
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RuleVerdict -> IO RuleVerdict)
-> (RuleEvidence -> RuleVerdict) -> RuleEvidence -> IO RuleVerdict
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EvalContext -> RuleEvidence -> RuleVerdict
verdict EvalContext
ctx))
        FromAdvisories AdvisoryAlignment
alignment AdvisoryRows -> RuleEvidence -> RuleVerdict
verdict -> PackageRead -> RuleEval
PerPackage (PackageRead -> RuleEval) -> IO PackageRead -> IO RuleEval
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RuleDeps
-> AdvisoryAlignment
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict)
-> IO PackageRead
advisoryRead RuleDeps
deps AdvisoryAlignment
alignment AdvisoryRows -> RuleEvidence -> RuleVerdict
verdict
    pure PreparedRule{prepName = ruleName rule, prepPrecedence = prec, prepEval = eval}

advisoryRead :: RuleDeps -> AdvisoryAlignment -> (AdvisoryRows -> RuleEvidence -> RuleVerdict) -> IO PackageRead
advisoryRead :: RuleDeps
-> AdvisoryAlignment
-> (AdvisoryRows -> RuleEvidence -> RuleVerdict)
-> IO PackageRead
advisoryRead RuleDeps
deps AdvisoryAlignment
alignment AdvisoryRows -> RuleEvidence -> RuleVerdict
verdict = do
    resilience <- case RuleDeps -> AdvisoryDatabase
rdAdvisoryDatabase RuleDeps
deps of
        AdvisoryDatabase
NoAdvisoryDatabase -> Maybe Resilience -> IO (Maybe Resilience)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Resilience
forall a. Maybe a
Nothing
        AdvisoryDatabase forall a. (AdvisoryGeneration -> IO a) -> IO a
_ -> Resilience -> Maybe Resilience
forall a. a -> Maybe a
Just (Resilience -> Maybe Resilience)
-> IO Resilience -> IO (Maybe Resilience)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RuleDeps -> IO Resilience
newResilience RuleDeps
deps
    pure
        PackageRead
            { prRead = withAdvisoryRead deps
            , prResilience = resilience
            , prAlignment = alignment
            , prVerdict = verdict
            , prReporter = rdSourceReporter deps
            }

withAdvisoryRead :: RuleDeps -> PackageName -> (AdvisoryFreshness -> IO AdvisoryRows -> IO a) -> IO a
withAdvisoryRead :: forall a.
RuleDeps
-> PackageName
-> (AdvisoryFreshness -> IO AdvisoryRows -> IO a)
-> IO a
withAdvisoryRead RuleDeps
deps PackageName
package AdvisoryFreshness -> IO AdvisoryRows -> IO a
use = case RuleDeps -> AdvisoryDatabase
rdAdvisoryDatabase RuleDeps
deps of
    AdvisoryDatabase forall a. (AdvisoryGeneration -> IO a) -> IO a
borrow ->
        (AdvisoryGeneration -> IO a) -> IO a
forall a. (AdvisoryGeneration -> IO a) -> IO a
borrow (\AdvisoryGeneration
generation -> AdvisoryGeneration -> IO AdvisoryFreshness
agFreshness AdvisoryGeneration
generation IO AdvisoryFreshness -> (AdvisoryFreshness -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \AdvisoryFreshness
freshness -> AdvisoryFreshness -> IO AdvisoryRows -> IO a
use AdvisoryFreshness
freshness (AdvisoryGeneration
-> forall a. (Maybe (DbEtag, CveLookup) -> IO a) -> IO a
agLookup AdvisoryGeneration
generation (PackageName -> Maybe (DbEtag, CveLookup) -> IO AdvisoryRows
readAdvisories PackageName
package)))
    AdvisoryDatabase
NoAdvisoryDatabase -> RuleDeps -> IO AdvisoryFreshness
rdAdvisoryFreshness RuleDeps
deps IO AdvisoryFreshness -> (AdvisoryFreshness -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \AdvisoryFreshness
freshness -> AdvisoryFreshness -> IO AdvisoryRows -> IO a
use AdvisoryFreshness
freshness (AdvisoryRows -> IO AdvisoryRows
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure AdvisoryRows
forall a. Maybe a
Nothing)

newResilience :: RuleDeps -> IO Resilience
newResilience :: RuleDeps -> IO Resilience
newResilience RuleDeps
deps = do
    breaker <- IO (TVar Breaker)
newBreaker
    pure
        Resilience
            { resConfig = defaultEffectfulConfig
            , resBreaker = breaker
            , resBreakerReporter = rdBreakerReporter deps
            , resClock = getCurrentTime
            }

-- | Sort by descending precedence, then ascending rule name, independently of configuration order.
bootOrder :: [PreparedRule] -> [PreparedRule]
bootOrder :: [PreparedRule] -> [PreparedRule]
bootOrder = (PreparedRule -> (Down Int, Text))
-> [PreparedRule] -> [PreparedRule]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\PreparedRule
r -> Int -> Text -> (Down Int, Text)
bootKey (PreparedRule -> Int
prepPrecedence PreparedRule
r) (PreparedRule -> Text
prepName PreparedRule
r))

-- 'bootOrder' and 'renderBootOrder' order through this one key, so the logged order is the
-- evaluated one.
bootKey :: Int -> Text -> (Down Int, Text)
bootKey :: Int -> Text -> (Down Int, Text)
bootKey Int
prec Text
name = (Int -> Down Int
forall a. a -> Down a
Down Int
prec, Text
name)

-- | Render each rule and its phases in the order 'bootOrder' evaluates them.
renderBootOrder :: [PrecededRule] -> [Text]
renderBootOrder :: [PrecededRule] -> [Text]
renderBootOrder [PrecededRule]
rules = (Int -> PrecededRule -> Text) -> [Int] -> [PrecededRule] -> [Text]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> PrecededRule -> Text
forall {a}. Show a => a -> PrecededRule -> Text
line [Int
1 :: Int ..] ((PrecededRule -> (Down Int, Text))
-> [PrecededRule] -> [PrecededRule]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\PrecededRule
r -> Int -> Text -> (Down Int, Text)
bootKey (PrecededRule -> Int
rulePrecedence PrecededRule
r) (Rule -> Text
ruleName (PrecededRule -> Rule
prRule PrecededRule
r))) [PrecededRule]
rules)
  where
    line :: a -> PrecededRule -> Text
line a
i PrecededRule
r =
        Text
"rule "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> a -> Text
forall b a. (Show a, IsString b) => a -> b
show a
i
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Rule -> Text
ruleName (PrecededRule -> Rule
prRule PrecededRule
r)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (precedence "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show (PrecededRule -> Int
rulePrecedence PrecededRule
r)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> RuleReach -> Text
renderReach (PrecededRule -> RuleReach
ruleReach PrecededRule
r)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"

renderReach :: RuleReach -> Text
renderReach :: RuleReach -> Text
renderReach = \case
    RuleReach
AdmissionAndRevocation -> Text
"applies at admission and revocation"
    RuleReach
AdmissionOnly -> Text
"applies at admission only"

-- | Decide a request's versions in boot order, catching throws. Advisory rules sharing one 'prepare' read one generation.
newEvaluator :: EvalContext -> [PreparedRule] -> IO (RuleEvidence -> IO Decision)
newEvaluator :: EvalContext -> [PreparedRule] -> IO (RuleEvidence -> IO Decision)
newEvaluator EvalContext
ctx [PreparedRule]
rules = do
    shared <- IO (PackageCell (Either Text AdvisoryRead))
forall a. IO (PackageCell a)
newPackageCell
    bound <- traverse (\PreparedRule
rule -> (PreparedRule
rule,) (VersionEval -> (PreparedRule, VersionEval))
-> IO VersionEval -> IO (PreparedRule, VersionEval)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> EvalContext
-> PackageCell (Either Text AdvisoryRead)
-> PreparedRule
-> IO VersionEval
bindRule EvalContext
ctx PackageCell (Either Text AdvisoryRead)
shared PreparedRule
rule) (bootOrder rules)
    -- One handler per version. A throw decides the version again with a handler per rule. The fast pass
    -- forces the evidence first, so evidence that throws leaves no held result for the second pass to meet.
    pure (\RuleEvidence
ev -> IO Decision -> IO (Either SomeException Decision)
forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> m (Either SomeException a)
tryAny (RuleEvidence -> IO RuleEvidence
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate RuleEvidence
ev IO RuleEvidence -> IO Decision -> IO Decision
forall a b. IO a -> IO b -> IO b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> RunEvaluation
-> RuleEvidence
-> [(PreparedRule, VersionEval)]
-> [Passed]
-> IO Decision
stepRules RunEvaluation
forceEvaluation RuleEvidence
ev [(PreparedRule, VersionEval)]
bound []) IO (Either SomeException Decision)
-> (Either SomeException Decision -> IO Decision) -> IO Decision
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (SomeException -> IO Decision)
-> (Decision -> IO Decision)
-> Either SomeException Decision
-> IO Decision
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (IO Decision -> SomeException -> IO Decision
forall a b. a -> b -> a
const (RunEvaluation
-> RuleEvidence
-> [(PreparedRule, VersionEval)]
-> [Passed]
-> IO Decision
stepRules RunEvaluation
caughtEvaluation RuleEvidence
ev [(PreparedRule, VersionEval)]
bound [])) Decision -> IO Decision
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure)

-- | Decide one version through a fresh 'newEvaluator'.
evalRules :: EvalContext -> [PreparedRule] -> RuleEvidence -> IO Decision
evalRules :: EvalContext -> [PreparedRule] -> RuleEvidence -> IO Decision
evalRules EvalContext
ctx [PreparedRule]
rules RuleEvidence
ev = EvalContext -> [PreparedRule] -> IO (RuleEvidence -> IO Decision)
newEvaluator EvalContext
ctx [PreparedRule]
rules IO (RuleEvidence -> IO Decision)
-> ((RuleEvidence -> IO Decision) -> IO Decision) -> IO Decision
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ((RuleEvidence -> IO Decision) -> RuleEvidence -> IO Decision
forall a b. (a -> b) -> a -> b
$ RuleEvidence
ev)

-- How the fold runs one rule's evaluation. Each way forces it with 'forceEvaluation'.
type RunEvaluation = IO RuleEvaluation -> IO RuleEvaluation

-- One rule's evaluation of a version, as the action the fold runs.
type VersionEval = RuleEvidence -> IO (IO RuleEvaluation)

-- A rule's closures are built once here, not per version. 'eval ctx' is bound outside the version
-- lambda because a prepared rule builds its verdict function for each context it is given.
bindRule :: EvalContext -> PackageCell (Either Text AdvisoryRead) -> PreparedRule -> IO VersionEval
bindRule :: EvalContext
-> PackageCell (Either Text AdvisoryRead)
-> PreparedRule
-> IO VersionEval
bindRule EvalContext
ctx PackageCell (Either Text AdvisoryRead)
shared PreparedRule
rule = case PreparedRule -> RuleEval
prepEval PreparedRule
rule of
    PerVersion EvalContext -> RuleEvidence -> IO RuleVerdict
eval -> do
        let decide :: RuleEvidence -> IO RuleVerdict
decide = EvalContext -> RuleEvidence -> IO RuleVerdict
eval EvalContext
ctx
        VersionEval -> IO VersionEval
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (\RuleEvidence
ev -> IO RuleEvaluation -> IO (IO RuleEvaluation)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RuleVerdict -> RuleEvaluation
Decided (RuleVerdict -> RuleEvaluation)
-> IO RuleVerdict -> IO RuleEvaluation
forall (m :: * -> *) a b. Monad m => (a -> b) -> m a -> m b
<$!> RuleEvidence -> IO RuleVerdict
decide RuleEvidence
ev))
    PerPackage PackageRead
packageRead -> do
        own <- IO (PackageCell (Either Text (RuleEvidence -> RuleEvaluation)))
forall a. IO (PackageCell a)
newPackageCell
        let resolve = PackageCell (Either Text (RuleEvidence -> RuleEvaluation))
-> (RuleEvidence
    -> IO (Either Text (RuleEvidence -> RuleEvaluation)))
-> RuleEvidence
-> IO (Either Text (RuleEvidence -> RuleEvaluation))
forall a.
PackageCell a -> (RuleEvidence -> IO a) -> RuleEvidence -> IO a
heldFor PackageCell (Either Text (RuleEvidence -> RuleEvaluation))
own (Text
-> PackageRead
-> PackageCell (Either Text AdvisoryRead)
-> RuleEvidence
-> IO (Either Text (RuleEvidence -> RuleEvaluation))
decideFromRead (PreparedRule -> Text
prepName PreparedRule
rule) PackageRead
packageRead PackageCell (Either Text AdvisoryRead)
shared)
        pure $ \RuleEvidence
ev ->
            RuleEvidence -> IO (Either Text (RuleEvidence -> RuleEvaluation))
resolve RuleEvidence
ev IO (Either Text (RuleEvidence -> RuleEvaluation))
-> (Either Text (RuleEvidence -> RuleEvaluation)
    -> IO RuleEvaluation)
-> IO (IO RuleEvaluation)
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \case
                Left Text
escape -> RuleEvaluation -> IO RuleEvaluation
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> RuleEvaluation
threw Text
escape)
                Right RuleEvidence -> RuleEvaluation
decideVersion -> RuleEvaluation -> IO RuleEvaluation
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RuleEvidence -> RuleEvaluation
decideVersion RuleEvidence
ev)

-- Strict fields evaluate the verdict payloads. Optional payloads need their own evaluation.
forceEvaluation :: IO RuleEvaluation -> IO RuleEvaluation
forceEvaluation :: RunEvaluation
forceEvaluation IO RuleEvaluation
action = do
    result <- IO RuleEvaluation
action IO RuleEvaluation
-> (RuleEvaluation -> IO RuleEvaluation) -> IO RuleEvaluation
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= RuleEvaluation -> IO RuleEvaluation
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate
    case result of
        Decided (Deny Maybe DbEtag
etag Reason
_) -> (DbEtag -> IO DbEtag) -> Maybe DbEtag -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ DbEtag -> IO DbEtag
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate Maybe DbEtag
etag
        Unavailable (WillResolve Maybe RetryAfter
retry) FailureAlignment
_ Inability
_ -> (RetryAfter -> IO RetryAfter) -> Maybe RetryAfter -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ RetryAfter -> IO RetryAfter
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate Maybe RetryAfter
retry
        RuleEvaluation
_ -> IO ()
forall (f :: * -> *). Applicative f => f ()
pass
    pure result

-- The rule's own handler around 'forceEvaluation'. Both passes force alike, so the fast pass never forces less.
caughtEvaluation :: RunEvaluation
caughtEvaluation :: RunEvaluation
caughtEvaluation = (Either Text RuleEvaluation -> RuleEvaluation)
-> IO (Either Text RuleEvaluation) -> IO RuleEvaluation
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Text -> RuleEvaluation)
-> (RuleEvaluation -> RuleEvaluation)
-> Either Text RuleEvaluation
-> RuleEvaluation
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either Text -> RuleEvaluation
threw RuleEvaluation -> RuleEvaluation
forall a. a -> a
id) (IO (Either Text RuleEvaluation) -> IO RuleEvaluation)
-> (IO RuleEvaluation -> IO (Either Text RuleEvaluation))
-> RunEvaluation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO RuleEvaluation -> IO (Either Text RuleEvaluation)
forall a. IO a -> IO (Either Text a)
caught (IO RuleEvaluation -> IO (Either Text RuleEvaluation))
-> RunEvaluation
-> IO RuleEvaluation
-> IO (Either Text RuleEvaluation)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RunEvaluation
forceEvaluation

-- An evaluation that throws breaks its contract, so it refuses admission as a fail-closed inability.
threw :: Text -> RuleEvaluation
threw :: Text -> RuleEvaluation
threw = RuleVerdict -> RuleEvaluation
Decided (RuleVerdict -> RuleEvaluation)
-> (Text -> RuleVerdict) -> Text -> RuleEvaluation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FailureAlignment -> Inability -> RuleVerdict
CannotVet FailureAlignment
FailDeny (Inability -> RuleVerdict)
-> (Text -> Inability) -> Text -> RuleVerdict
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Inability
RuleThrew

caught :: IO a -> IO (Either Text a)
caught :: forall a. IO a -> IO (Either Text a)
caught = (Either SomeException a -> Either Text a)
-> IO (Either SomeException a) -> IO (Either Text a)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((SomeException -> Text) -> Either SomeException a -> Either Text a
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first SomeException -> Text
forall e. Exception e => e -> Text
displayExceptionT) (IO (Either SomeException a) -> IO (Either Text a))
-> (IO a -> IO (Either SomeException a))
-> IO a
-> IO (Either Text a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO a -> IO (Either SomeException a)
forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> m (Either SomeException a)
tryAny

-- A result held for the last package decided. Another package computes its own, never borrowing it.
-- The lock serialises computing. A hit reads the latest result without it.
data PackageCell a = PackageCell (MVar ()) (IORef (Maybe (PackageName, a)))

newPackageCell :: IO (PackageCell a)
newPackageCell :: forall a. IO (PackageCell a)
newPackageCell = MVar () -> IORef (Maybe (PackageName, a)) -> PackageCell a
forall a.
MVar () -> IORef (Maybe (PackageName, a)) -> PackageCell a
PackageCell (MVar () -> IORef (Maybe (PackageName, a)) -> PackageCell a)
-> IO (MVar ())
-> IO (IORef (Maybe (PackageName, a)) -> PackageCell a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> () -> IO (MVar ())
forall (m :: * -> *) a. MonadIO m => a -> m (MVar a)
newMVar () IO (IORef (Maybe (PackageName, a)) -> PackageCell a)
-> IO (IORef (Maybe (PackageName, a))) -> IO (PackageCell a)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Maybe (PackageName, a) -> IO (IORef (Maybe (PackageName, a)))
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef Maybe (PackageName, a)
forall a. Maybe a
Nothing

-- A miss looks again under the lock, so concurrent callers for one package compute it once.
heldFor :: PackageCell a -> (RuleEvidence -> IO a) -> RuleEvidence -> IO a
heldFor :: forall a.
PackageCell a -> (RuleEvidence -> IO a) -> RuleEvidence -> IO a
heldFor (PackageCell MVar ()
lock IORef (Maybe (PackageName, a))
latest) RuleEvidence -> IO a
compute RuleEvidence
ev =
    IORef (Maybe (PackageName, a)) -> IO (Maybe (PackageName, a))
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef (Maybe (PackageName, a))
latest IO (Maybe (PackageName, a))
-> (Maybe (PackageName, a) -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Just (PackageName
known, a
value) | PackageName
known PackageName -> PackageName -> Bool
forall a. Eq a => a -> a -> Bool
== RuleEvidence -> PackageName
evName RuleEvidence
ev -> a -> IO a
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
value
        Maybe (PackageName, a)
_ -> MVar () -> (() -> IO a) -> IO a
forall (m :: * -> *) a b.
MonadUnliftIO m =>
MVar a -> (a -> m b) -> m b
withMVar MVar ()
lock ((() -> IO a) -> IO a) -> (() -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \() ->
            IORef (Maybe (PackageName, a)) -> IO (Maybe (PackageName, a))
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef (Maybe (PackageName, a))
latest IO (Maybe (PackageName, a))
-> (Maybe (PackageName, a) -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                Just (PackageName
known, a
value) | PackageName
known PackageName -> PackageName -> Bool
forall a. Eq a => a -> a -> Bool
== RuleEvidence -> PackageName
evName RuleEvidence
ev -> a -> IO a
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
value
                Maybe (PackageName, a)
_ -> RuleEvidence -> IO a
compute RuleEvidence
ev IO a -> (a -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \a
value -> a
value a -> IO () -> IO a
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ IORef (Maybe (PackageName, a)) -> Maybe (PackageName, a) -> IO ()
forall (m :: * -> *) a. MonadIO m => IORef a -> a -> m ()
atomicWriteIORef IORef (Maybe (PackageName, a))
latest ((PackageName, a) -> Maybe (PackageName, a)
forall a. a -> Maybe a
Just (RuleEvidence -> PackageName
evName RuleEvidence
ev, a
value))

-- The evaluator's one advisory read of a package: its rows, or why it has none.
data AdvisoryRead
    = RowsRead AdvisoryRows
    | PushIneligible Inability
    | ReadGivenUp ReadFault

-- One rule's evaluation of every version from the shared read, made by this rule if it is the first
-- reached. The rule reports once per package whether the read let it consult the source.
decideFromRead :: Text -> PackageRead -> PackageCell (Either Text AdvisoryRead) -> RuleEvidence -> IO (Either Text (RuleEvidence -> RuleEvaluation))
decideFromRead :: Text
-> PackageRead
-> PackageCell (Either Text AdvisoryRead)
-> RuleEvidence
-> IO (Either Text (RuleEvidence -> RuleEvaluation))
decideFromRead Text
name PackageRead
packageRead PackageCell (Either Text AdvisoryRead)
shared RuleEvidence
reaching =
    PackageCell (Either Text AdvisoryRead)
-> (RuleEvidence -> IO (Either Text AdvisoryRead))
-> RuleEvidence
-> IO (Either Text AdvisoryRead)
forall a.
PackageCell a -> (RuleEvidence -> IO a) -> RuleEvidence -> IO a
heldFor PackageCell (Either Text AdvisoryRead)
shared (IO AdvisoryRead -> IO (Either Text AdvisoryRead)
forall a. IO a -> IO (Either Text a)
caught (IO AdvisoryRead -> IO (Either Text AdvisoryRead))
-> (RuleEvidence -> IO AdvisoryRead)
-> RuleEvidence
-> IO (Either Text AdvisoryRead)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PackageRead -> PackageName -> IO AdvisoryRead
readShared PackageRead
packageRead (PackageName -> IO AdvisoryRead)
-> (RuleEvidence -> PackageName) -> RuleEvidence -> IO AdvisoryRead
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RuleEvidence -> PackageName
evName) RuleEvidence
reaching IO (Either Text AdvisoryRead)
-> (Either Text AdvisoryRead
    -> IO (Either Text (RuleEvidence -> RuleEvaluation)))
-> IO (Either Text (RuleEvidence -> RuleEvaluation))
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Left Text
escape -> Either Text (RuleEvidence -> RuleEvaluation)
-> IO (Either Text (RuleEvidence -> RuleEvaluation))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Either Text (RuleEvidence -> RuleEvaluation)
forall a b. a -> Either a b
Left Text
escape)
        Right AdvisoryRead
advisory -> do
            let resolved :: RuleEvidence -> RuleEvaluation
resolved = PackageRead -> AdvisoryRead -> RuleEvidence -> RuleEvaluation
resolveRead PackageRead
packageRead AdvisoryRead
advisory
            health <- IO SourceHealth -> IO (Either Text SourceHealth)
forall a. IO a -> IO (Either Text a)
caught (SourceHealth -> IO SourceHealth
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate (Text -> AdvisoryRead -> RuleEvaluation -> SourceHealth
readHealth Text
name AdvisoryRead
advisory (RuleEvidence -> RuleEvaluation
resolved RuleEvidence
reaching)))
            caught (resolved <$ reportSource (prReporter packageRead) (either (SourceUnavailable name . RuleThrew) id health))

-- The push-age gate, then the rows under the reading rule's resilience. The gate runs ahead of
-- breaker admission, which an open breaker would otherwise skip past.
readShared :: PackageRead -> PackageName -> IO AdvisoryRead
readShared :: PackageRead -> PackageName -> IO AdvisoryRead
readShared PackageRead
packageRead PackageName
package =
    PackageRead
-> forall a.
   PackageName
   -> (AdvisoryFreshness -> IO AdvisoryRows -> IO a) -> IO a
prRead PackageRead
packageRead PackageName
package ((AdvisoryFreshness -> IO AdvisoryRows -> IO AdvisoryRead)
 -> IO AdvisoryRead)
-> (AdvisoryFreshness -> IO AdvisoryRows -> IO AdvisoryRead)
-> IO AdvisoryRead
forall a b. (a -> b) -> a -> b
$ \AdvisoryFreshness
freshness IO AdvisoryRows
rows -> case AdvisoryFreshness -> Maybe Inability
pushInability AdvisoryFreshness
freshness of
        Just Inability
why -> AdvisoryRead -> IO AdvisoryRead
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Inability -> AdvisoryRead
PushIneligible Inability
why)
        Maybe Inability
Nothing -> case PackageRead -> Maybe Resilience
prResilience PackageRead
packageRead of
            Maybe Resilience
Nothing -> AdvisoryRows -> AdvisoryRead
RowsRead (AdvisoryRows -> AdvisoryRead)
-> IO AdvisoryRows -> IO AdvisoryRead
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO AdvisoryRows
rows
            Just Resilience
res -> (ReadFault -> AdvisoryRead)
-> (AdvisoryRows -> AdvisoryRead)
-> Either ReadFault AdvisoryRows
-> AdvisoryRead
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ReadFault -> AdvisoryRead
ReadGivenUp AdvisoryRows -> AdvisoryRead
RowsRead (Either ReadFault AdvisoryRows -> AdvisoryRead)
-> IO (Either ReadFault AdvisoryRows) -> IO AdvisoryRead
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Resilience -> IO AdvisoryRows -> IO (Either ReadFault AdvisoryRows)
forall a. Resilience -> IO a -> IO (Either ReadFault a)
runResilient Resilience
res IO AdvisoryRows
rows

-- One rule's evaluation of each version, under its own alignments. A fault resolves all alike.
resolveRead :: PackageRead -> AdvisoryRead -> RuleEvidence -> RuleEvaluation
resolveRead :: PackageRead -> AdvisoryRead -> RuleEvidence -> RuleEvaluation
resolveRead PackageRead
packageRead = \case
    RowsRead AdvisoryRows
rows -> RuleVerdict -> RuleEvaluation
Decided (RuleVerdict -> RuleEvaluation)
-> (RuleEvidence -> RuleVerdict) -> RuleEvidence -> RuleEvaluation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PackageRead -> AdvisoryRows -> RuleEvidence -> RuleVerdict
prVerdict PackageRead
packageRead AdvisoryRows
rows
    PushIneligible Inability
why -> RuleEvaluation -> RuleEvidence -> RuleEvaluation
forall a b. a -> b -> a
const (RuleVerdict -> RuleEvaluation
Decided (FailureAlignment -> Inability -> RuleVerdict
CannotVet (AdvisoryAlignment -> FailureAlignment
onExpiredPush AdvisoryAlignment
alignment) Inability
why))
    ReadGivenUp ReadFault
fault -> RuleEvaluation -> RuleEvidence -> RuleEvaluation
forall a b. a -> b -> a
const (Transience -> FailureAlignment -> Inability -> RuleEvaluation
Unavailable (ReadFault -> Transience
rfTransience ReadFault
fault) (AdvisoryAlignment -> FailureAlignment
onFaultedRead AdvisoryAlignment
alignment) (ReadFault -> Inability
rfReason ReadFault
fault))
  where
    alignment :: AdvisoryAlignment
alignment = PackageRead -> AdvisoryAlignment
prAlignment PackageRead
packageRead

-- Whether the read let one rule consult the source: only a rule that could not vet says it did not.
readHealth :: Text -> AdvisoryRead -> RuleEvaluation -> SourceHealth
readHealth :: Text -> AdvisoryRead -> RuleEvaluation -> SourceHealth
readHealth Text
name AdvisoryRead
advisory RuleEvaluation
resolved = case AdvisoryRead
advisory of
    ReadGivenUp ReadFault
fault -> Text -> Inability -> SourceHealth
SourceUnavailable Text
name (ReadFault -> Inability
rfDetail ReadFault
fault)
    AdvisoryRead
_ -> case RuleEvaluation
resolved of
        Decided (CannotVet FailureAlignment
_ Inability
why) -> Text -> Inability -> SourceHealth
SourceUnavailable Text
name Inability
why
        Unavailable Transience
_ FailureAlignment
_ Inability
why -> Text -> Inability -> SourceHealth
SourceUnavailable Text
name Inability
why
        Decided RuleVerdict
_ -> Text -> SourceHealth
SourceAnswered Text
name

-- 'passed' holds each non-decisive evaluation in reverse boot order. The deny-by-default trail
-- and an admission's skipped-check evidence both read it back.
stepRules :: RunEvaluation -> RuleEvidence -> [(PreparedRule, VersionEval)] -> [Passed] -> IO Decision
stepRules :: RunEvaluation
-> RuleEvidence
-> [(PreparedRule, VersionEval)]
-> [Passed]
-> IO Decision
stepRules RunEvaluation
_ RuleEvidence
_ [] [Passed]
passed = Decision -> IO Decision
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Reason] -> Decision
BlockedByDefault ((Passed -> Reason) -> [Passed] -> [Reason]
forall a b. (a -> b) -> [a] -> [b]
map Passed -> Reason
passedReason ([Passed] -> [Passed]
forall a. [a] -> [a]
reverse [Passed]
passed)))
stepRules RunEvaluation
run RuleEvidence
ev ((PreparedRule
rule, VersionEval
eval) : [(PreparedRule, VersionEval)]
rest) [Passed]
passed =
    VersionEval
eval RuleEvidence
ev IO (IO RuleEvaluation) -> RunEvaluation -> IO RuleEvaluation
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= RunEvaluation
run IO RuleEvaluation -> (RuleEvaluation -> IO Decision) -> IO Decision
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \RuleEvaluation
res -> case Text -> RuleEvaluation -> Maybe Decision
decisive (PreparedRule -> Text
prepName PreparedRule
rule) RuleEvaluation
res of
        Just Decision
d -> Decision -> IO Decision
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Passed] -> [PreparedRule] -> Decision -> Decision
withEvidence [Passed]
passed (((PreparedRule, VersionEval) -> PreparedRule)
-> [(PreparedRule, VersionEval)] -> [PreparedRule]
forall a b. (a -> b) -> [a] -> [b]
map (PreparedRule, VersionEval) -> PreparedRule
forall a b. (a, b) -> a
fst [(PreparedRule, VersionEval)]
rest) Decision
d)
        Maybe Decision
Nothing -> RunEvaluation
-> RuleEvidence
-> [(PreparedRule, VersionEval)]
-> [Passed]
-> IO Decision
stepRules RunEvaluation
run RuleEvidence
ev [(PreparedRule, VersionEval)]
rest (Text -> RuleEvaluation -> Passed
Passed (PreparedRule -> Text
prepName PreparedRule
rule) RuleEvaluation
res Passed -> [Passed] -> [Passed]
forall a. a -> [a] -> [a]
: [Passed]
passed)

-- One non-decisive evaluation as the fold keeps it, so the trail and the evidence read one record.
data Passed = Passed Text RuleEvaluation

-- The audit reason one passed evaluation leaves in the deny-by-default trail, its rule named
-- where the rule could not vet.
passedReason :: Passed -> Reason
passedReason :: Passed -> Reason
passedReason (Passed Text
name RuleEvaluation
res) = case RuleEvaluation
res of
    Unavailable Transience
_ FailureAlignment
_ Inability
why -> Text -> Inability -> Reason
RuleUnable Text
name Inability
why
    Decided (CannotVet FailureAlignment
_ Inability
why) -> Text -> Inability -> Reason
RuleUnable Text
name Inability
why
    Decided (Allow Reason
reason) -> Reason
reason
    Decided (Deny Maybe DbEtag
_ Reason
reason) -> Reason
reason
    Decided (NoDecision Reason
reason) -> Reason
reason

-- The evidence a fail-open inability leaves. A fail-closed one is decisive, so it never passes.
skippedOf :: Passed -> Maybe SkippedCheck
skippedOf :: Passed -> Maybe SkippedCheck
skippedOf (Passed Text
name RuleEvaluation
res) = case RuleEvaluation
res of
    Decided (CannotVet FailureAlignment
alignment Inability
why) -> FailureAlignment -> Inability -> Maybe SkippedCheck
skipped FailureAlignment
alignment Inability
why
    Unavailable Transience
_ FailureAlignment
alignment Inability
why -> FailureAlignment -> Inability -> Maybe SkippedCheck
skipped FailureAlignment
alignment Inability
why
    Decided RuleVerdict
_ -> Maybe SkippedCheck
forall a. Maybe a
Nothing
  where
    skipped :: FailureAlignment -> Inability -> Maybe SkippedCheck
skipped FailureAlignment
FailNoDecision Inability
why = SkippedCheck -> Maybe SkippedCheck
forall a. a -> Maybe a
Just (Text -> Inability -> SkippedCheck
SkippedUnavailable Text
name Inability
why)
    skipped FailureAlignment
FailDeny Inability
_ = Maybe SkippedCheck
forall a. Maybe a
Nothing

-- Only an admission carries evidence: the checks that could not vet ahead of it, in boot order,
-- then the ones it pre-empted. 'decisive' builds it with none, so it stands when none is found.
withEvidence :: [Passed] -> [PreparedRule] -> Decision -> Decision
withEvidence :: [Passed] -> [PreparedRule] -> Decision -> Decision
withEvidence [Passed]
passed [PreparedRule]
unreached Decision
decided = case Decision
decided of
    Admitted Text
name Reason
reason [SkippedCheck]
_ | Bool -> Bool
not ([SkippedCheck] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [SkippedCheck]
evidence) -> Text -> Reason -> [SkippedCheck] -> Decision
Admitted Text
name Reason
reason [SkippedCheck]
evidence
    Decision
_ -> Decision
decided
  where
    evidence :: [SkippedCheck]
evidence = [SkippedCheck] -> [SkippedCheck]
forall a. [a] -> [a]
reverse ((Passed -> Maybe SkippedCheck) -> [Passed] -> [SkippedCheck]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Passed -> Maybe SkippedCheck
skippedOf [Passed]
passed) [SkippedCheck] -> [SkippedCheck] -> [SkippedCheck]
forall a. Semigroup a => a -> a -> a
<> (PreparedRule -> SkippedCheck) -> [PreparedRule] -> [SkippedCheck]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> SkippedCheck
Unreached (Text -> SkippedCheck)
-> (PreparedRule -> Text) -> PreparedRule -> SkippedCheck
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PreparedRule -> Text
prepName) [PreparedRule]
unreached

-- 'CannotVet' has no transience evidence, so it produces a plain retryable refusal. An admission's
-- evidence is attached by the fold, which alone knows what it passed and pre-empted.
decisive :: Text -> RuleEvaluation -> Maybe Decision
decisive :: Text -> RuleEvaluation -> Maybe Decision
decisive Text
name = \case
    Decided (Allow Reason
reason) -> Decision -> Maybe Decision
forall a. a -> Maybe a
Just (Text -> Reason -> [SkippedCheck] -> Decision
Admitted Text
name Reason
reason [])
    Decided (Deny Maybe DbEtag
etag Reason
reason) -> Decision -> Maybe Decision
forall a. a -> Maybe a
Just (Text -> Maybe DbEtag -> Reason -> Decision
Blocked Text
name Maybe DbEtag
etag Reason
reason)
    Decided (NoDecision Reason
_) -> Maybe Decision
forall a. Maybe a
Nothing
    Decided (CannotVet FailureAlignment
FailDeny Inability
why) -> Decision -> Maybe Decision
forall a. a -> Maybe a
Just (Transience -> Reason -> Decision
Undecidable (Maybe RetryAfter -> Transience
WillResolve Maybe RetryAfter
forall a. Maybe a
Nothing) (Text -> Inability -> Reason
RuleUnable Text
name Inability
why))
    Decided (CannotVet FailureAlignment
FailNoDecision Inability
_) -> Maybe Decision
forall a. Maybe a
Nothing
    Unavailable Transience
transience FailureAlignment
FailDeny Inability
why -> Decision -> Maybe Decision
forall a. a -> Maybe a
Just (Transience -> Reason -> Decision
Undecidable Transience
transience (Text -> Inability -> Reason
RuleUnable Text
name Inability
why))
    Unavailable Transience
_ FailureAlignment
FailNoDecision Inability
_ -> Maybe Decision
forall a. Maybe a
Nothing

-- | Return why expired or undated evidence is unavailable, or 'Nothing' while it is eligible.
pushInability :: AdvisoryFreshness -> Maybe Inability
pushInability :: AdvisoryFreshness -> Maybe Inability
pushInability = \case
    AdvisoryFreshness
AdvisoryFresh -> Maybe Inability
forall a. Maybe a
Nothing
    AdvisoryAging{} -> Maybe Inability
forall a. Maybe a
Nothing
    AdvisoryStale AdvisoryAge
observed -> Inability -> Maybe Inability
forall a. a -> Maybe a
Just (AdvisoryAge -> Inability
PushPastMaximum AdvisoryAge
observed)
    AdvisoryFreshness
AdvisoryUndated -> Inability -> Maybe Inability
forall a. a -> Maybe a
Just Inability
PushUndated