-- hokey.hs: hOpenPGP key tool
-- Copyright © 2013-2026  Clint Adams
--
-- vim: softtabstop=4:shiftwidth=4:expandtab
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as
-- published by the Free Software Foundation, either version 3 of the
-- License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeApplications #-}

import Codec.Encryption.OpenPGP.Expirations (getKeyExpirationTimesFromSignature)
import Codec.Encryption.OpenPGP.Fingerprint (eightOctetKeyID, fingerprint)
import Codec.Encryption.OpenPGP.KeyInfo (pkalgoAbbrev, pubkeySize)
import Codec.Encryption.OpenPGP.KeySelection (parseFingerprint)
import Codec.Encryption.OpenPGP.Ontology
  ( isCT
  , isCertRevocationSig
  , isKUF
  , isPHA
  , isPKBindingSig
  , isSKBindingSig
  )
import Codec.Encryption.OpenPGP.Serialize ()
import Codec.Encryption.OpenPGP.Types
import Control.Applicative (optional)
import Control.Arrow ((***))
import Control.Error.Util (hush)
import Control.Exception (bracket)
import Control.Lens ((&), (^.), _1, _2, mapped, over)
import Control.Monad.Trans.Except (ExceptT(..), runExceptT)
import Control.Monad.Trans.Writer.Lazy (execWriter, tell)
import qualified Crypto.Hash as CH
import qualified Crypto.Hash.Algorithms as CHA
import qualified Crypto.PubKey.RSA as RSA
import qualified Data.Aeson as A
import Data.Binary (get, put)
import Data.Binary.Get (getWord32be, runGet)
import Data.Binary.Put (Put, putByteString, putLazyByteString, putWord32be, putWord8, runPut)
import Data.Bits ((.&.), shiftR, testBit)
import qualified Data.ByteArray as BA
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Char8 as BC8
import qualified Data.ByteString.Lazy as BL
import Data.Conduit ((.|), runConduitRes)
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Conduit.OpenPGP.Keyring (AuthSecretSubkeyAtTime, authSecretSubkeyPrimaryUID, authSecretSubkeyValue, conduitToAuthSecretSubkeysAt, conduitToSecretTKs, conduitToTKsDropping)
import Data.Conduit.Serialization.Binary (conduitGet, conduitPut)
import Data.Foldable (find)
import Data.List (elemIndex, findIndex, intercalate, nub, sort, sortOn)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)
import Data.Ord (Down(..))
import Data.Semigroup (Semigroup, (<>))
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (POSIXTime, getPOSIXTime, posixSecondsToUTCTime)
import Data.Time.Format (formatTime)
import qualified Data.Word as Word
import qualified Data.Yaml as Y
import GHC.Generics
import HOpenPGP.Tools.Common (banner, versioner, warranty)
import HOpenPGP.Tools.HKP (FetchValidationMethod(..), rearmorKeys)
import qualified HOpenPGP.Tools.HKP as HKP
import HOpenPGP.Tools.TKUtils (processTK)
import Network.Socket (Family(AF_UNIX), SockAddr(..), Socket, SocketType(Stream), close, connect, defaultProtocol, socket)
import qualified Network.Socket.ByteString as NSB
import System.Environment (lookupEnv)
import System.Exit (exitFailure)
import qualified HOpenPGP.Tools.WKD as WKD

import Options.Applicative.Builder
  ( argument
  , auto
  , command
  , footerDoc
  , headerDoc
  , help
  , helpDoc
  , info
  , long
  , metavar
  , option
  , prefs
  , progDesc
  , showDefault
  , showHelpOnError
  , str
  , value
  )
import Options.Applicative.Extra (customExecParser, helper, hsubparser)
import Options.Applicative.Types (Parser)

import Data.Time.Locale.Compat (defaultTimeLocale)
import System.IO
  ( BufferMode(..)
  , Handle
  , hFlush
  , hPutStrLn
  , hSetBuffering
  , stderr
  , stdin
  , stdout
  )

import Prettyprinter
  ( Doc
  , (<+>)
  , annotate
  , colon
  , defaultLayoutOptions
  , flatAlt
  , hardline
  , indent
  , layoutPretty
  , line
  , list
  , pretty
  )
import qualified Prettyprinter.Render.Terminal as PPA

linebreak = flatAlt line mempty

green = annotate (PPA.color PPA.Green)

yellow = annotate (PPA.color PPA.Yellow)

red = annotate (PPA.color PPA.Red)

data KAS =
  KAS
    { pubkeyalgo :: Colored PubKeyAlgorithm
    , pubkeysize :: Colored (Maybe Int)
    , stringrep :: String
    }
  deriving (Generic)

data Color
  = Green
  | Yellow
  | Red
  deriving (Eq, Generic, Ord)

data Colored a =
  Colored
    { color :: Maybe Color
    , explanation :: Maybe String
    , val :: a
    }
  deriving (Functor, Generic)

newtype FakeMap a b =
  FakeMap
    { unFakeMap :: [(a, b)]
    }

data KeyReport =
  KeyReport
    { keyStatus :: String
    , keyFingerprint :: Fingerprint
    , keyVer :: Colored KeyVersion
    , keyCreationTime :: ThirtyTwoBitTimeStamp
    , keyAlgorithmAndSize :: KAS
    , keyUIDsAndUAts :: FakeMap Text (Colored UIDReport)
    , keyBestOf :: Maybe UIDReport
    , keySubkeys :: [SubkeyReport]
    , keyHasEncryptionCapableSubkey :: Colored Bool
    }
  deriving (Generic)

data UIDReport =
  UIDReport
    { uidSelfSigHashAlgorithms :: [Colored HashAlgorithm]
    , uidPreferredHashAlgorithms :: [Colored [HashAlgorithm]]
    , uidKeyExpirationTimes :: [Colored [ThirtyTwoBitDuration]]
    , uidKeyUsageFlags :: [Colored (Set.Set KeyFlag)]
    , uidRevocationStatus :: [RevocationStatus]
    }
  deriving (Generic)

data SubkeyReport =
  SubkeyReport
    { skFingerprint :: Colored Fingerprint
    , skVer :: Colored KeyVersion
    , skCreationTime :: ThirtyTwoBitTimeStamp
    , skAlgorithmAndSize :: KAS
    , skBindingSigHashAlgorithms :: [Colored HashAlgorithm]
    , skRevocationSigWeakDigests :: [SubkeyRevocationDigestWarning]
    , skUsageFlags :: [Colored (Set.Set KeyFlag)]
    , skCrossCerts :: CrossCertReport
    }
  deriving (Generic)

data SubkeyRevocationDigestWarning =
  SubkeyRevocationDigestWarning
    { srwHashAlgorithm :: HashAlgorithm
    , srwSubkeyFingerprint :: String
    , srwSubkeyKeyID :: Maybe String
    , srwMessage :: String
    }
  deriving (Generic)

data CrossCertReport =
  CrossCertReport
    { ccPresent :: Colored Bool
    , ccHashAlgorithms :: [Colored HashAlgorithm]
    }
  deriving (Generic)

data RevocationStatus =
  RevocationStatus
    { isRevoked :: Bool
    , revocationCode :: String
    , revocationReason :: Text
    }
  deriving (Generic)

instance A.ToJSON KAS

instance A.ToJSON Color

instance (A.ToJSON a) => A.ToJSON (Colored a)

instance A.ToJSON KeyReport

instance A.ToJSON UIDReport

instance A.ToJSON SubkeyReport

instance A.ToJSON SubkeyRevocationDigestWarning

instance A.ToJSON CrossCertReport

instance A.ToJSON b => A.ToJSON (FakeMap Text b) where
  toJSON = A.toJSON . Map.fromList . unFakeMap

instance A.ToJSON RevocationStatus

instance Semigroup UIDReport where
  (<>) (UIDReport a b c d e) (UIDReport a' b' c' d' e') =
    UIDReport (a <> a') (b <> b') (c <> c') (d <> d') (e <> e')

instance Monoid UIDReport where
  mempty = UIDReport [] [] [] [] []
  mappend = (<>)

checkKey :: Maybe POSIXTime -> TKUnknown -> KeyReport
checkKey mpt key =
  (\x ->
     x
       { keyBestOf = populateBestOf x
       , keyHasEncryptionCapableSubkey =
           hasEncryptionCapableSubkey (concatMap skUsageFlags (keySubkeys x))
       })
    KeyReport
      { keyStatus = either id (const "good") processedTK
      , keyFingerprint = key ^. tkuKey . _1 & fingerprint
      , keyVer = key ^. tkuKey . _1 & _keyVersion & colorizeKV
      , keyCreationTime = key ^. tkuKey . _1 & _timestamp
      , keyAlgorithmAndSize = kasIt (key ^. tkuKey . _1)
      , keyUIDsAndUAts =
          FakeMap
            (map (\(x, y) -> (x, uidr (Just x) y)) (processedOrOrig ^. tkuUIDs) ++
             map (uatspsToText *** uidr Nothing) (processedOrOrig ^. tkuUAts))
      , keyBestOf = Nothing
      , keySubkeys =
          map (checkSK (key ^. tkuKey . _1 & fingerprint)) (key ^. tkuSubs)
      , keyHasEncryptionCapableSubkey = Colored Nothing Nothing False
      }
  where
    processedOrOrig = either (const key) id processedTK
    processedTK = processTK mpt key
    kasIt :: SomePKPayload -> KAS
    kasIt pkp = kasIt' (_pkalgo pkp) (_pubkey pkp & pubkeySize)
    kasIt' :: PubKeyAlgorithm -> Either String Int -> KAS
    kasIt' pka epks =
      KAS
        { pubkeyalgo = colorizePKA pka
        , pubkeysize = colorizePKS pka epks
        , stringrep = (either (const "unknown") show epks) ++ (pkalgoAbbrev pka)
        }
    colorizeKV kv =
      uncurry
        Colored
        (if kv == V4
           then (Just Green, Nothing)
           else (Just Red, Just "not a V4 key"))
        kv
    colorizePKA pka
      | pka `elem` [RSA, EdDSA, ECDH] = Colored (Just Green) Nothing pka
      | otherwise =
        Colored
          (Just Yellow)
          (Just "public key algorithm neither RSA nor EdDSA")
          pka
    colorizePKS pka epks = uncurry Colored (colorizePKS' pka epks) (hush epks)
    colorizePKS' pka (Right pks)
      | pka `elem` [EdDSA, ECDH] && pks >= 256 = (Just Green, Nothing)
      | pka `elem` [EdDSA, ECDH] =
        (Just Yellow, Just "Public key size under 256 bits")
      | pka == RSA && pks >= 3072 = (Just Green, Nothing)
      | pka == RSA && pks >= 2048 =
        (Just Yellow, Just "Public key size between 2048 and 3072 bits")
      | pka == RSA = (Just Red, Just "Public key size under 2048 bits")
      | otherwise = (Nothing, Nothing)
    colorizePKS' _ (Left _) =
      (Just Red, Just "public key algorithm not understood")
    colorizePHAs x =
      uncurry
        Colored
        (if preferredWeakHash x
           then (Just Red, Just "weak hash with higher preference")
           else (Just Green, Nothing))
        x
    fSHA2Family = fi (`elem` [SHA512, SHA384, SHA256, SHA224])
    firstStrongSHA2 xs = fSHA2Family xs
    preferredWeakHash xs =
      any
        (\ha -> fromMaybe maxBound (elemIndex ha xs) < firstStrongSHA2 xs)
        knownWeakHashAlgorithms
    fi x y = fromMaybe maxBound (findIndex x y)
    colorizeKETs ct ts kes
      | null kes = Colored (Just Red) (Just "no expiration set") kes
      | any (\ke -> realToFrac ts + realToFrac ke < ct) kes =
        Colored (Just Red) (Just "expiration passed") kes
      | any (\ke -> realToFrac ts + realToFrac ke > ct + (5 * 31557600)) kes =
        Colored (Just Yellow) (Just "expiration too far in future") kes
      | otherwise = Colored (Just Green) Nothing kes
    eoki pkp
      | _keyVersion pkp == V4 = hush . eightOctetKeyID $ pkp
      | _keyVersion pkp == DeprecatedV3 &&
          elem (_pkalgo pkp) [RSA, DeprecatedRSASignOnly] =
        hush . eightOctetKeyID $ pkp
      | otherwise = Nothing
    phas (SigV4 _ _ _ xs _ _ _) =
      colorizePHAs .
      concatMap (\(SigSubPacket _ (PreferredHashAlgorithms x)) -> x) $
      filter isPHA xs
    phas _ = Colored Nothing Nothing []
    has = map (colorizeHA . hashAlgo) . alleged
    colorizeHA ha =
      uncurry
        Colored
        (if isKnownWeakHashAlgorithm ha
           then (Just Red, Just "weak hash algorithm")
           else (Nothing, Nothing))
        ha
    sigcts (SigV4 _ _ _ xs _ _ _) =
      map (\(SigSubPacket _ (SigCreationTime x)) -> x) $ filter isCT xs
    alleged =
      filter
        (\x -> ((==) <$> sigissuer x <*> eoki (key ^. tkuKey . _1)) == Just True)
    uatspsToText = T.pack . uatspsToString
    uatspsToString us =
      "<uat:[" ++ intercalate "," (map uaspToString us) ++ "]>"
    uaspToString (ImageAttribute hdr d) =
      hdrToString hdr ++ ':' : show (BL.length d) ++ ':' :
      BC8.unpack (Base16.encode (BA.convert (CH.hashlazy @CHA.SHA3_512 d)))
    uaspToString (OtherUASub t d) =
      "other-" ++ show t ++ ':' : show (BL.length d) ++ ':' :
      BC8.unpack (Base16.encode (BA.convert (CH.hashlazy @CHA.SHA3_512 d)))
    hdrToString (ImageHV1 JPEG) = "jpeg"
    hdrToString (ImageHV1 fmt) = "image-" ++ show (fromFVal fmt)
    uidr Nothing sps =
      Colored
        Nothing
        Nothing
        (UIDReport
           (has sps)
           (map phas sps)
           (map
              (colorizeKETs
                 (fromMaybe 0 mpt)
                 (unThirtyTwoBitTimeStamp (_timestamp (key ^. tkuKey . _1))) .
               getKeyExpirationTimesFromSignature)
              sps -- should that be 0?
            )
           (kufs False sps)
           (findRevocationReason sps))
    uidr (Just u) sps =
      colorizeUID
        u
        (UIDReport
           (has sps)
           (map phas sps)
           (map
              (colorizeKETs
                 (fromMaybe 0 mpt)
                 (unThirtyTwoBitTimeStamp (_timestamp (key ^. tkuKey . _1))) .
               getKeyExpirationTimesFromSignature)
              sps -- should that be 0?
            )
           (kufs False sps)
           (findRevocationReason sps))
    populateBestOf krep =
      Just
        (UIDReport <$> best . uidSelfSigHashAlgorithms <*> best .
         uidPreferredHashAlgorithms <*>
         best .
         uidKeyExpirationTimes <*>
         best .
         uidKeyUsageFlags <*>
         pure [] $
         mconcat (justTheUIDRs krep))
    justTheUIDRs = map (decolorize . snd) . unFakeMap . keyUIDsAndUAts
    best = take 1 . sortOn color
    decolorize (Colored _ _ x) = x
    colorizeUID u
      | '(' `elem` T.unpack u =
        Colored (Just Yellow) (Just "parenthesis in uid") -- FIXME: be more discerning
      | '<' `notElem` T.unpack u =
        Colored (Just Yellow) (Just "no left angle bracket in uid") -- FIXME: be more discerning
      | otherwise = Colored Nothing Nothing
    findRevocationReason = concatMap grabReasons . filter isCertRevocationSig
    grabReasons (SigV4 CertRevocationSig _ _ has _ _ _) =
      mapMaybe (grabReasons' . _sspPayload) has
    grabReasons _ = []
    grabReasons' (ReasonForRevocation a b) =
      Just (RevocationStatus True (show a) b)
    grabReasons' _ = Nothing
    kufs s =
      map
        (colorizeKUFs s . (\(SigSubPacket _ (KeyFlags x)) -> x) .
         fromMaybe undefined .
         find isKUF .
         hasheds) .
      newestWith (any isKUF . hasheds)
    colorizeKUFs False x =
      uncurry
        Colored
        (if (Set.member EncryptStorageKey x ||
             Set.member EncryptCommunicationsKey x) &&
            (Set.member SignDataKey x || Set.member CertifyKeysKey x)
           then (Just Yellow, Just "both signing & encryption")
           else (Just Green, Nothing))
        x
    colorizeKUFs True x =
      uncurry
        Colored
        (if Set.member CertifyKeysKey x
           then (Just Red, Just "certification-capable subkey")
           else (if (Set.member EncryptStorageKey x ||
                     Set.member EncryptCommunicationsKey x) &&
                    Set.member SignDataKey x
                   then (Just Yellow, Just "both signing & encryption")
                   else (Just Green, Nothing)))
        x
    newestWith p = take 1 . sortOn (Down . take 1 . sigcts) . filter p -- FIXME: this is terrible
    hasheds (SigV4 _ _ _ xs _ _ _) = xs
    hasheds _ = []
    checkSK ::
         Fingerprint -> (Pkt, [SignaturePayload]) -> SubkeyReport
    checkSK pf (PublicSubkeyPkt pkp, sigs) = checkSK' pf pkp sigs
    checkSK pf (SecretSubkeyPkt pkp _, sigs) = checkSK' pf pkp sigs
    checkSK' pf pkp sigs =
      (\x -> x {skCrossCerts = ccr (map decolorize (skUsageFlags x)) sigs})
        SubkeyReport
          { skFingerprint = colorizeF pf (fingerprint pkp)
          , skVer = colorizeKV (_keyVersion pkp)
          , skCreationTime = _timestamp pkp
          , skAlgorithmAndSize = kasIt pkp
          , skBindingSigHashAlgorithms = has (filter isSKBindingSig sigs)
          , skRevocationSigWeakDigests =
              subkeyRevocationSigWeakDigests pkp sigs
          , skUsageFlags = kufs True (filter isSKBindingSig sigs)
          , skCrossCerts = CrossCertReport (Colored Nothing Nothing False) []
          }
    hasEncryptionCapableSubkey skrs =
      if any
           ((\x ->
               Set.member EncryptStorageKey x ||
               Set.member EncryptCommunicationsKey x) .
            decolorize)
           skrs
        then Colored (Just Green) Nothing True
        else Colored
               (Just Red)
               (Just "no encryption-capable subkey present")
               False
    embeddedSigs =
      filter isPKBindingSig . concatMap getEmbeds . filter isSKBindingSig
    getEmbeds (SigV4 _ _ _ xs ys _ _) = concatMap getEmbed (xs ++ ys)
    getEmbeds _ = []
    getEmbed (SigSubPacket _ (EmbeddedSignature sp)) = [sp]
    getEmbed _ = []
    ccr kufs sigs =
      CrossCertReport (colorES kufs sigs) (map (colorizeHA . hashAlgo) sigs)
    colorES kufs sigs =
      case ( null (embeddedSigs sigs)
           , any (Set.member SignDataKey) kufs
           , any (Set.member AuthKey) kufs) of
        (True, True, True) ->
          Colored
            (Just Red)
            (Just "signing- and auth-capable subkey without cross-cert")
            False
        (True, True, False) ->
          Colored
            (Just Red)
            (Just "signing-capable subkey without cross-cert")
            False
        (True, False, True) ->
          Colored
            (Just Yellow)
            (Just "auth-capable subkey without cross-cert")
            False
        (False, True, True) -> Colored (Just Green) Nothing True
        (False, True, False) -> Colored (Just Green) Nothing True
        (False, False, True) -> Colored (Just Green) Nothing True
        (False, False, False) -> Colored Nothing Nothing True
        (True, _, _) -> Colored Nothing Nothing False
    colorizeF pf fp =
      uncurry
        Colored
        (if pf == fp
           then (Just Red, Just "subkey has same fingerprint as primary key")
           else (Just Green, Nothing))
        fp
    subkeyRevocationSigWeakDigests pkp =
      mapMaybe (mkSubkeyRevocationSigWeakDigestWarning pkp) .
      filter isSubkeyRevocationSignature
    mkSubkeyRevocationSigWeakDigestWarning pkp sig =
      let ha = hashAlgo sig
       in if isKnownWeakHashAlgorithm ha
            then
              Just
                SubkeyRevocationDigestWarning
                  { srwHashAlgorithm = ha
                  , srwSubkeyFingerprint = renderFingerprint (fingerprint pkp)
                  , srwSubkeyKeyID = fmap renderKeyID (hush (eightOctetKeyID pkp))
                  , srwMessage =
                      "subkey revocation signature uses known-weak digest algorithm"
                  }
            else Nothing

prettyKeyReport :: POSIXTime -> TKUnknown -> Doc PPA.AnsiStyle
prettyKeyReport cpt key = do
  let keyReport = checkKey (Just cpt) key
  execWriter $
    tell
      (linebreak <> pretty "Key has potential validity" <> colon <+>
       pretty (keyStatus keyReport) <>
       linebreak <>
       pretty "Key has fingerprint" <>
       colon <+>
       pretty (SpacedFingerprint (keyFingerprint keyReport)) <>
       linebreak <>
       pretty "Checking to see if key is OpenPGPv4" <>
       colon <+>
       coloredToColor (pretty . show) (keyVer keyReport) <>
       linebreak <>
       (\kas ->
          pretty "Checking the strength of your primary asymmetric key" <> colon <+>
          coloredToColor pretty (pubkeyalgo kas) <+>
          coloredToColor (maybe (pretty "unknown") pretty) (pubkeysize kas))
         (keyAlgorithmAndSize keyReport) <>
       linebreak <>
       pretty "Checking user-ID- and user-attribute-related items" <>
       colon <>
       mconcat
         (map
            (uidtrip (keyCreationTime keyReport) . gottabeabetterway)
            (unFakeMap (keyUIDsAndUAts keyReport))) <>
       linebreak <>
       pretty "Checking subkeys" <>
       colon <>
       linebreak <>
       indent
         2
         (pretty "one of the subkeys is encryption-capable" <> colon <+>
          coloredToColor pretty (keyHasEncryptionCapableSubkey keyReport)) <>
       mconcat (map subkeyrep (keySubkeys keyReport)) <>
       linebreak)
  where
    coloredToColor f (Colored (Just Green) _ x) = green (f x)
    coloredToColor f (Colored (Just Yellow) _ x) = yellow (f x)
    coloredToColor f (Colored (Just Red) _ x) = red (f x)
    coloredToColor f (Colored Nothing _ x) = f x
    uidtrip ts (u, ur)
      | null (uidRevocationStatus ur) =
        linebreak <> indent 2 (coloredToColor pretty (fmap T.unpack u)) <> colon <>
        linebreak <>
        indent
          4
          (pretty "Self-sig hash algorithms" <> colon <+>
           (list . map (coloredToColor pretty) . uidSelfSigHashAlgorithms) ur) <>
        linebreak <>
        indent
          4
          (pretty "Preferred hash algorithms" <> colon <+>
           mconcat (map (coloredToColor pretty) (uidPreferredHashAlgorithms ur))) <>
        linebreak <>
        indent
          4
          (pretty "Key expiration times" <> colon <+>
           mconcat
             (map
                (coloredToColor list . fmap (map (pretty . keyExp ts)))
                (uidKeyExpirationTimes ur))) <>
        linebreak <>
        indent
          4
          (pretty "Key usage flags" <> colon <+>
           (list . map (coloredToColor (pretty . Set.toList)))
             (uidKeyUsageFlags ur))
      | otherwise =
        linebreak <> indent 2 (coloredToColor pretty (fmap T.unpack u)) <> colon <+>
        pretty "[revoked]" <>
        linebreak <>
        indent
          4
          (pretty "Revocation code" <> colon <+>
           list (map (pretty . revocationCode) (uidRevocationStatus ur))) <>
        linebreak <>
        indent
          4
          (pretty "Revocation reason" <> colon <+>
           list
             (map
                (pretty . T.unpack . revocationReason)
                (uidRevocationStatus ur)))
    keyExp ts ke =
      (show . pretty) ke ++ " = " ++
      formatTime
        defaultTimeLocale
        "%c"
        (posixSecondsToUTCTime (realToFrac ts + realToFrac ke))
    gottabeabetterway (a, Colored x y z) = (Colored x y a, z)
    subkeyrep skr =
      linebreak <>
      indent
        2
        (pretty "fpr" <> colon <+>
         coloredToColor pretty (fmap SpacedFingerprint (skFingerprint skr))) <>
      linebreak <>
      indent 4 (pretty "version" <> colon <+> coloredToColor pretty (skVer skr)) <>
      linebreak <>
      indent 4 (pretty "timestamp" <> colon <+> pretty (skCreationTime skr)) <>
      linebreak <>
      indent
        4
        ((\kas ->
            pretty "algo/size" <> colon <+>
            coloredToColor pretty (pubkeyalgo kas) <+>
            coloredToColor (maybe (pretty "unknown") pretty) (pubkeysize kas))
           (skAlgorithmAndSize skr)) <>
      linebreak <>
      indent
        4
        (pretty "binding sig hash algorithms" <> colon <+>
         (list . map (coloredToColor pretty) . skBindingSigHashAlgorithms) skr) <>
      linebreak <>
      indent
        4
        (pretty "weak subkey revocation digests" <> colon <+>
         if null (skRevocationSigWeakDigests skr)
           then pretty "[]"
           else
             list
               (map
                  (\w ->
                     red
                       (pretty (srwHashAlgorithm w) <> colon <+>
                        pretty (srwSubkeyFingerprint w) <> colon <+>
                        maybe (pretty "<no-key-id>") pretty (srwSubkeyKeyID w)))
                  (skRevocationSigWeakDigests skr))) <>
      linebreak <>
      indent
        4
        (pretty "usage flags" <> colon <+>
         (list . map (coloredToColor (pretty . Set.toList))) (skUsageFlags skr)) <>
      linebreak <>
      indent
        4
        (pretty "embedded cross-cert" <> colon <+>
         (coloredToColor pretty . ccPresent . skCrossCerts) skr) <>
      linebreak <>
      indent
        4
        (pretty "cross-cert hash algorithms" <> colon <+>
         (list . map (coloredToColor pretty) . ccHashAlgorithms . skCrossCerts)
           skr)

jsonReport :: POSIXTime -> TKUnknown -> BL.ByteString
jsonReport ps = A.encode . checkKey (Just ps)

yamlReport :: POSIXTime -> TKUnknown -> B.ByteString
yamlReport ps = Y.encode . (: []) . checkKey (Just ps)

data LintOutputFormat
  = Pretty
  | JSON
  | YAML
  deriving (Bounded, Enum, Eq, Read, Show)

data LintOptions =
  LintOptions
    { lintOutputFormat :: LintOutputFormat
    }

data FetchOptions =
  FetchOptions
    { keyServer :: String
    , fetchMethod :: FetchMethod
    , fetchValidation :: FetchValidationMethod
    , fetchQuery :: String
    }

data InjectSSHAgentOptions =
  InjectSSHAgentOptions
    { injectSSHAgentFromFD :: Maybe Int
    , injectSSHAgentSocket :: Maybe String
    , injectSSHAgentComment :: Maybe String
    }

data FetchMethod
  = HKP
  | WKD
  deriving (Bounded, Enum, Eq, Read, Show)

data Command
  = CmdLint LintOptions
  | CmdCanonicalize
  | CmdFetch FetchOptions
  | CmdInjectSSHAgent InjectSSHAgentOptions

data InjectableAuthSubkey =
  InjectableAuthSubkey
    { injectableAuthSubkeyPKP :: SomePKPayload
    , injectableAuthSubkeySKA :: SKAddendum
    , injectableAuthSubkeyPrimaryUID :: Maybe Text
    }

lintO :: Parser LintOptions
lintO =
  LintOptions <$>
  option
    auto
    (long "output-format" <> metavar "FORMAT" <> value Pretty <> showDefault <>
     ofHelp)
  where
    ofHelp =
      helpDoc . Just $ pretty "output format" <> hardline <>
      list (map (pretty . show) ofchoices)
    ofchoices = [minBound .. maxBound] :: [LintOutputFormat]

fetchO :: Parser FetchOptions
fetchO =
  FetchOptions <$>
  option
    str
    (long "keyserver" <> metavar "URL" <>
     value "http://pool.sks-keyservers.net:11371" <>
     showDefault <>
     help "HKP server (used only when --method=HKP)") <*>
  option
    auto
    (long "method" <> metavar "METHOD" <> value HKP <> showDefault <> fmHelp) <*>
  option
    auto
    (long "validation-method" <> metavar "METHOD" <>
     value MatchPrimaryKeyFingerprint <>
     showDefault <>
     vmHelp) <*>
  argument str (metavar "QUERY")
  where
    fmHelp =
     helpDoc . Just $ pretty "fetch method" <> hardline <>
     list (map (pretty . show) fmchoices)
    fmchoices = [minBound .. maxBound] :: [FetchMethod]
    vmHelp =
     helpDoc . Just $ pretty "validation method" <> hardline <>
     list (map (pretty . show) vmchoices)
    vmchoices = [minBound .. maxBound] :: [FetchValidationMethod]

injectSSHAgentO :: Parser InjectSSHAgentOptions
injectSSHAgentO =
  InjectSSHAgentOptions <$>
  optional
    (option
       auto
       (long "from-fd" <>
        metavar "FD" <>
        help "read binary gpg --export-secret-keys bytes from this already-open file descriptor")) <*>
  optional
    (option
       str
       (long "ssh-agent-socket" <>
        metavar "PATH" <> help "path to ssh-agent socket (defaults to SSH_AUTH_SOCK)")) <*>
  optional
    (option
       str
       (long "comment" <>
        metavar "TEXT" <> help "comment string stored with the injected SSH identity"))

dispatch :: Command -> IO ()
dispatch (CmdFetch o) = banner' stderr >> hFlush stderr >> doFetch o
dispatch (CmdLint o) = banner' stderr >> hFlush stderr >> doLint o
dispatch CmdCanonicalize = banner' stderr >> hFlush stderr >> doCanonicalize
dispatch (CmdInjectSSHAgent o) =
  banner' stderr >> hFlush stderr >> doInjectSSHAgent o

main :: IO ()
main = do
  hSetBuffering stderr LineBuffering
  customExecParser
    (prefs showHelpOnError)
    (info
       (helper <*> versioner "hokey" <*> cmd)
       (headerDoc (Just (banner "hokey")) <>
        progDesc "hOpenPGP Key utility" <>
        footerDoc (Just (warranty "hokey")))) >>=
    dispatch

cmd :: Parser Command
cmd =
  hsubparser
    (command
       "canonicalize"
       (info
          (pure CmdCanonicalize)
          (progDesc "arrange key components in a canonical ordering")) <>
     command
       "fetch"
       (info
          (CmdFetch <$> fetchO)
          (progDesc "fetch key(s) via HKP or WKD")) <>
     command
       "inject-ssh-agent"
       (info
          (CmdInjectSSHAgent <$> injectSSHAgentO)
          (progDesc "Read exported secret key bytes, pick an auth-capable subkey, and add it to ssh-agent")) <>
     command
       "lint"
       (info (CmdLint <$> lintO) (progDesc "check key(s) for 'best practices'")))

doLint :: LintOptions -> IO ()
doLint o = do
  cpt <- getPOSIXTime
  keys <-
    runConduitRes $ CB.sourceHandle stdin .| conduitGet get .|
    conduitToTKsDropping .|
    CL.consume
  output (lintOutputFormat o) cpt keys
  where
    output Pretty cpt = mapM_ (PPA.putDoc . prettyKeyReport cpt)
    output JSON cpt =
      mapM_ (BL.putStr . flip BL.append (BL.singleton 0x0a) . jsonReport cpt)
    output YAML cpt = mapM_ (B.putStr . yamlReport cpt)

doCanonicalize :: IO ()
doCanonicalize =
  runConduitRes $ CB.sourceHandle stdin .| conduitGet get .|
  conduitToTKsDropping .|
  CL.map canonicalize .|
  CL.map put .|
  conduitPut .|
  CB.sinkHandle stdout
  where
    canonicalize tk =
      tk
        { _tkuRevs = sort (_tkuRevs tk)
        , _tkuUIDs = indepthsort (_tkuUIDs tk)
        , _tkuUAts = indepthsort (_tkuUAts tk)
        , _tkuSubs = indepthsort (_tkuSubs tk)
        }
    indepthsort :: (Ord a, Ord b) => [(a, [b])] -> [(a, [b])]
    indepthsort = nub . sort . over (mapped . _2) sort

doFetch :: FetchOptions -> IO ()
doFetch o = do
  ekeys <-
    runExceptT $
    case fetchMethod o of
      HKP -> do
        fp <- ExceptT . return . parseFingerprint . T.pack $ fetchQuery o
        HKP.fetchKeys (keyServer o) (fetchValidation o) fp
      WKD -> WKD.fetchKeys (fetchValidation o) (T.pack (fetchQuery o))
  case ekeys of
    Left e -> hPutStrLn stderr $ "error fetching keys: " ++ e
    Right ks -> B.putStr $ rearmorKeys ks

doInjectSSHAgent :: InjectSSHAgentOptions -> IO ()
doInjectSSHAgent opts = do
  socketPath <- resolveSSHAgentSocketPath (injectSSHAgentSocket opts)
  input <- readInjectedSecretKeyMaterial opts
  cpt <- getPOSIXTime
  authCandidates <-
    runConduitRes $
    CL.sourceList (BL.toChunks input) .| conduitGet get .| conduitToSecretTKs .|
    conduitToAuthSecretSubkeysAt (posixSecondsToUTCTime cpt) .|
    CL.consume
  injectableCandidates <-
    if null authCandidates
      then inferInjectableAuthSubkeys cpt input
      else pure (map candidateFromAuthSecretSubkey authCandidates)
  whenEmpty injectableCandidates "inject-ssh-agent: no authentication-capable secret subkey found"
  selectedRequests <-
    selectInjectableAuthSubkeys
      (injectSSHAgentComment opts)
      injectableCandidates
  mapM_
    (\(selected, request) -> do
       sendAddIdentityToSSHAgent socketPath request
       hPutStrLn stderr $
         "inject-ssh-agent: added authentication subkey " ++
        renderFingerprint (fingerprint (injectableAuthSubkeyPKP selected)) ++
         " to ssh-agent")
    selectedRequests

candidateFromAuthSecretSubkey :: AuthSecretSubkeyAtTime -> InjectableAuthSubkey
candidateFromAuthSecretSubkey authSubkey =
  InjectableAuthSubkey
    { injectableAuthSubkeyPKP = authSecretSubkeyPKP authSubkey
    , injectableAuthSubkeySKA = authSecretSubkeySKA authSubkey
    , injectableAuthSubkeyPrimaryUID = authSecretSubkeyPrimaryUID authSubkey
    }

inferInjectableAuthSubkeys ::
     POSIXTime -> BL.ByteString -> IO [InjectableAuthSubkey]
inferInjectableAuthSubkeys _cpt input = do
  tks <-
    runConduitRes $
    CL.sourceList (BL.toChunks input) .| conduitGet get .| conduitToSecretTKs .|
    CL.consume
  pure (concatMap inferFromTK tks)
  where
    inferFromTK tk =
      let mPrimaryUID = fst <$> listToMaybe (_tkUIDs tk)
       in mapMaybe (inferFromSubkey mPrimaryUID) (_tkSubs tk)
    inferFromSubkey :: Maybe Text -> (KeyPkt k, [SignaturePayload]) -> Maybe InjectableAuthSubkey
    inferFromSubkey mPrimaryUID (KeyPktSecretSubkey pkp ska, sigs)
      | hasAuthCapability sigs =
          Just
            InjectableAuthSubkey
              { injectableAuthSubkeyPKP = pkp
              , injectableAuthSubkeySKA = ska
              , injectableAuthSubkeyPrimaryUID = mPrimaryUID
              }
    inferFromSubkey _ _ = Nothing
    hasAuthCapability sigs =
      any
        (Set.member AuthKey)
        (mapMaybe signatureKeyFlags (newestWithUsageFlags (filter isSKBindingSig sigs)))
    newestWithUsageFlags =
      take 1 . sortOn (Down . take 1 . sigCreationTimes) . filter (any isKUF . signatureHashedSubpackets)
    sigCreationTimes = mapMaybe sigCreationTimeFromSubpacket . signatureHashedSubpackets
    sigCreationTimeFromSubpacket (SigSubPacket _ (SigCreationTime ct)) = Just ct
    sigCreationTimeFromSubpacket _ = Nothing
    signatureHashedSubpackets (SigV4 _ _ _ hasheds _ _ _) = hasheds
    signatureHashedSubpackets (SigV6 _ _ _ _ hasheds _ _ _) = hasheds
    signatureHashedSubpackets _ = []
    signatureKeyFlags sig = do
      sp <- find isKUF (signatureHashedSubpackets sig)
      case sp of
        SigSubPacket _ (KeyFlags flags) -> Just flags
        _ -> Nothing

resolveSSHAgentSocketPath :: Maybe String -> IO String
resolveSSHAgentSocketPath (Just path) = pure path
resolveSSHAgentSocketPath Nothing = do
  envPath <- lookupEnv "SSH_AUTH_SOCK"
  case envPath of
    Just path -> pure path
    Nothing ->
      failInject
        "inject-ssh-agent: SSH_AUTH_SOCK is not set; use --ssh-agent-socket"

readInjectedSecretKeyMaterial :: InjectSSHAgentOptions -> IO BL.ByteString
readInjectedSecretKeyMaterial opts = do
  chunks <-
    case injectSSHAgentFromFD opts of
      Nothing -> runConduitRes $ CB.sourceHandle stdin .| CL.consume
      Just fd
        | fd < 0 ->
          failInject "inject-ssh-agent: --from-fd must be a non-negative integer"
        | otherwise ->
          runConduitRes $ CB.sourceFile ("/dev/fd/" ++ show fd) .| CL.consume
  let input = BL.fromChunks chunks
  if BL.null input
    then
      failInject
        "inject-ssh-agent: no secret key bytes were provided on the selected input stream"
    else pure input

selectInjectableAuthSubkeys ::
     Maybe String -> [InjectableAuthSubkey] -> IO [(InjectableAuthSubkey, BL.ByteString)]
selectInjectableAuthSubkeys mComment candidates
  | null selectedRequests =
      failInject
        ("inject-ssh-agent: auth-capable subkeys were found, but none are supported for ssh-agent injection: " ++
         intercalate "; " (reverse errs))
  | otherwise = pure (reverse selectedRequests)
  where
    (errs, selectedRequests) = foldl' pick ([], []) candidates
    pick (accErrs, accSelected) candidate =
      case
             sshAddIdentityRequest
               (fromMaybe (defaultSSHComment candidate) mComment)
               (injectableAuthSubkeyPKP candidate)
               (injectableAuthSubkeySKA candidate) of
        Left err -> (err : accErrs, accSelected)
        Right request -> (accErrs, (candidate, request) : accSelected)
    defaultSSHComment candidate =
      case injectableAuthSubkeyPrimaryUID candidate of
        Just uid -> T.unpack uid
        Nothing  -> "openpgp:" ++ BC8.unpack (Base16.encode (BL.toStrict (unFingerprint (fingerprint (injectableAuthSubkeyPKP candidate)))))

sshAddIdentityRequest ::
     String -> SomePKPayload -> SKAddendum -> Either String BL.ByteString
sshAddIdentityRequest comment subkeyPKP subkeySKA =
  case subkeySKA of
    SUUnencrypted (RSAPrivateKey (RSA_PrivateKey rsaPrivateKey)) _ ->
      Right $ frameSSHAgentRequest (rsaAddIdentityPayload (BC8.pack comment) rsaPrivateKey)
    SUUnencrypted (EdDSAPrivateKey Ed25519 secretSeed) _ ->
      frameSSHAgentRequest <$>
      ed25519AddIdentityPayload (BC8.pack comment) subkeyPKP secretSeed
    SUUnencrypted (UnknownSKey rawSecret) _
      | isEd25519PKA (_pkalgo subkeyPKP) ->
        frameSSHAgentRequest <$>
        ed25519AddIdentityPayload
          (BC8.pack comment)
          subkeyPKP
          (BL.toStrict rawSecret)
    SUUnencrypted (EdDSAPrivateKey Ed448 _) _ ->
      Left
        ("subkey " ++ renderFingerprint (fingerprint subkeyPKP) ++
         " uses Ed448, which is not supported by ssh-agent add-identity")
    SUUnencrypted _ _ ->
      Left
        ("subkey " ++ renderFingerprint (fingerprint subkeyPKP) ++
         " uses an unsupported key algorithm for ssh-agent injection")
    _ ->
      Left
        ("subkey " ++ renderFingerprint (fingerprint subkeyPKP) ++
         " is encrypted; decrypt it before injection")

authSecretSubkeyPKP :: AuthSecretSubkeyAtTime -> SomePKPayload
authSecretSubkeyPKP = keyPktPKPayload . authSecretSubkeyValue

authSecretSubkeySKA :: AuthSecretSubkeyAtTime -> SKAddendum
authSecretSubkeySKA = secretKeyPktSKAddendum . authSecretSubkeyValue

rsaAddIdentityPayload :: B.ByteString -> RSA.PrivateKey -> BL.ByteString
rsaAddIdentityPayload comment privateKey =
  runPut $ do
    putWord8 17
    putSSHString (BC8.pack "ssh-rsa")
    putSSHMpint (RSA.public_n (RSA.private_pub privateKey))
    putSSHMpint (RSA.public_e (RSA.private_pub privateKey))
    putSSHMpint (RSA.private_d privateKey)
    putSSHMpint (RSA.private_qinv privateKey)
    putSSHMpint (RSA.private_p privateKey)
    putSSHMpint (RSA.private_q privateKey)
    putSSHString comment

ed25519AddIdentityPayload ::
     B.ByteString -> SomePKPayload -> B.ByteString -> Either String BL.ByteString
ed25519AddIdentityPayload comment pkp rawSecret = do
  publicKey <- ed25519PublicPoint pkp
  secretSeed <- normalizeEd25519Secret rawSecret
  pure $
    runPut $ do
      putWord8 17
      putSSHString (BC8.pack "ssh-ed25519")
      putSSHString publicKey
      putSSHString (secretSeed <> publicKey)
      putSSHString comment

ed25519PublicPoint :: SomePKPayload -> Either String B.ByteString
ed25519PublicPoint pkp =
  case _pubkey pkp of
    EdDSAPubKey Ed25519 point ->
      maybe
        (Left ("invalid Ed25519 public point for subkey " ++ renderFingerprint (fingerprint pkp)))
        Right
        (edPointToRawBytes point)
    _ -> Left ("subkey " ++ renderFingerprint (fingerprint pkp) ++ " does not have an Ed25519 public key")

renderFingerprint :: Fingerprint -> String
renderFingerprint =
  T.unpack . PPA.renderStrict . layoutPretty defaultLayoutOptions . pretty

renderKeyID :: EightOctetKeyId -> String
renderKeyID =
  T.unpack . PPA.renderStrict . layoutPretty defaultLayoutOptions . pretty

knownWeakHashAlgorithms :: [HashAlgorithm]
knownWeakHashAlgorithms = [DeprecatedMD5, SHA1, RIPEMD160]

isKnownWeakHashAlgorithm :: HashAlgorithm -> Bool
isKnownWeakHashAlgorithm ha = ha `elem` knownWeakHashAlgorithms

isSubkeyRevocationSignature :: SignaturePayload -> Bool
isSubkeyRevocationSignature (SigV3 st _ _ _ _ _ _) = st == SubkeyRevocationSig
isSubkeyRevocationSignature (SigV4 st _ _ _ _ _ _) = st == SubkeyRevocationSig
isSubkeyRevocationSignature (SigV6 st _ _ _ _ _ _ _) = st == SubkeyRevocationSig
isSubkeyRevocationSignature _ = False

edPointToRawBytes :: EdPoint -> Maybe B.ByteString
edPointToRawBytes (NativeEPoint (EPoint i)) = integerToFixedBytes 32 i
edPointToRawBytes (PrefixedNativeEPoint (EPoint i)) = do
  prefixed <- integerToFixedBytes 33 i
  case B.uncons prefixed of
    Just (0x40, raw) -> Just raw
    _ -> Nothing

normalizeEd25519Secret :: B.ByteString -> Either String B.ByteString
normalizeEd25519Secret rawSecret
  | B.length rawSecret == 32 = Right rawSecret
  | otherwise =
    Left
      ("expected 32-byte Ed25519 secret seed, got " ++ show (B.length rawSecret) ++ " bytes")

putSSHString :: B.ByteString -> Put
putSSHString bs = putWord32be (fromIntegral (B.length bs)) >> putByteString bs

putSSHMpint :: Integer -> Put
putSSHMpint n
  | n <= 0 = putWord32be 0
  | otherwise = putSSHString encoded
  where
    raw = integerToUnsignedBytes n
    encoded =
      case B.uncons raw of
        Just (firstByte, _)
          | testBit firstByte 7 -> B.cons 0x00 raw
        _ -> raw

integerToFixedBytes :: Int -> Integer -> Maybe B.ByteString
integerToFixedBytes width n
  | n < 0 = Nothing
  | B.length raw > width = Nothing
  | otherwise = Just (B.replicate (width - B.length raw) 0x00 <> raw)
  where
    raw =
      if n == 0
        then B.singleton 0x00
        else integerToUnsignedBytes n

integerToUnsignedBytes :: Integer -> B.ByteString
integerToUnsignedBytes n =
  B.reverse $
  B.unfoldr
    (\value ->
       if value == 0
         then Nothing
         else Just (fromIntegral (value .&. 0xff), value `shiftR` 8))
    n

isEd25519PKA :: PubKeyAlgorithm -> Bool
isEd25519PKA pka = fromFVal pka == 27

frameSSHAgentRequest :: BL.ByteString -> BL.ByteString
frameSSHAgentRequest body =
  runPut $ putWord32be (fromIntegral (BL.length body)) >> putLazyByteString body

sendAddIdentityToSSHAgent :: FilePath -> BL.ByteString -> IO ()
sendAddIdentityToSSHAgent socketPath request =
  bracket
    (socket AF_UNIX Stream defaultProtocol)
    close
    (\sock -> do
       connect sock (SockAddrUnix socketPath)
       NSB.sendAll sock (BL.toStrict request)
       response <- readSSHAgentPacket sock
       case B.uncons response of
         Just (6, _) -> pure ()
         Just (5, _) ->
           failInject "inject-ssh-agent: ssh-agent rejected the supplied key"
         Just (code, _) ->
           failInject
             ("inject-ssh-agent: ssh-agent returned unexpected response type " ++
              show code)
         Nothing ->
           failInject
             "inject-ssh-agent: ssh-agent returned an empty response packet")

readSSHAgentPacket :: Socket -> IO B.ByteString
readSSHAgentPacket sock = do
  lenPrefix <- recvExact sock 4
  let packetLen = fromIntegral (runGet getWord32be (BL.fromStrict lenPrefix))
  recvExact sock packetLen

recvExact :: Socket -> Int -> IO B.ByteString
recvExact _ 0 = pure B.empty
recvExact sock remaining = go B.empty remaining
  where
    go acc 0 = pure acc
    go acc bytesRemaining = do
      chunk <- NSB.recv sock bytesRemaining
      if B.null chunk
        then
          failInject
            "inject-ssh-agent: ssh-agent socket closed while reading response"
        else go (acc <> chunk) (bytesRemaining - B.length chunk)

whenEmpty :: [a] -> String -> IO ()
whenEmpty [] msg = failInject msg
whenEmpty _ _ = pure ()

failInject :: String -> IO a
failInject msg = hPutStrLn stderr msg >> exitFailure

banner' :: Handle -> IO ()
banner' h =
  PPA.hPutDoc h (banner "hokey" <> hardline <> warranty "hokey" <> hardline)

sigissuer :: SignaturePayload -> Maybe EightOctetKeyId
getIssuer :: SigSubPacketPayload -> Maybe EightOctetKeyId
hashAlgo :: SignaturePayload -> HashAlgorithm
sigissuer (SigVOther 2 _) = Nothing
sigissuer SigV3 {} = Nothing
sigissuer (SigV4 _ _ _ ys xs _ _) =
  listToMaybe . mapMaybe (getIssuer . _sspPayload) $ (ys ++ xs) -- FIXME: what should this be if there are multiple matches?
sigissuer (SigV6 _ _ _ _ ys xs _ _) =
  listToMaybe . mapMaybe (getIssuer . _sspPayload) $ (ys ++ xs) -- FIXME: what should this be if there are multiple matches?
sigissuer (SigVOther _ _) = Nothing

getIssuer (Issuer i) = Just i
getIssuer _ = Nothing

hashAlgo (SigV3 _ _ _ _ x _ _) = x
hashAlgo (SigV4 _ _ x _ _ _ _) = x
hashAlgo (SigV6 _ _ x _ _ _ _ _) = x
hashAlgo (SigVOther _ _) = OtherHA 0
