{- | Noise authentication for libp2p WebTransport sessions.

WebTransport uses Noise only on the first session stream to authenticate
peer identities and bind the server's TLS certificate hashes. The resulting
Noise transport cipher is deliberately discarded: subsequent WebTransport
streams are protected by QUIC TLS and are not double-encrypted.
-}
module LibP2P.Noise.WebTransport (
  performWebTransportInitiator,
  performWebTransportResponder,
) where

import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import LibP2P.Core.Binary (readWord16BE)
import LibP2P.Crypto.Key (KeyPair, PublicKey)
import LibP2P.Crypto.PeerId (fromPublicKey)
import LibP2P.Crypto.Protobuf qualified as Protobuf
import LibP2P.MultistreamSelect.Negotiation (StreamIO (..))
import LibP2P.Noise.Framing (encodeFrame)
import LibP2P.Noise.Handshake (
  HandshakeResult (..),
  HandshakeState,
  NoisePayload (..),
  buildHandshakePayload,
  decodeNoiseCerthashes,
  decodeNoisePayload,
  encodeNoisePayload,
  encodeNoisePayloadWithCerthashes,
  getRemoteNoiseStaticKey,
  initHandshakeInitiator,
  initHandshakeResponder,
  readHandshakeMsg,
  verifyStaticKey,
  writeHandshakeMsg,
 )

{- | Authenticate an outbound WebTransport session and return the remote peer
plus the certificate hashes bound into the responder's Noise payload.
-}
performWebTransportInitiator ::
  KeyPair -> StreamIO -> IO (HandshakeResult, [ByteString])
performWebTransportInitiator :: KeyPair -> StreamIO -> IO (HandshakeResult, [ByteString])
performWebTransportInitiator KeyPair
identity StreamIO
stream = do
  (initial, staticKey) <- KeyPair -> IO (HandshakeState, ByteString)
initHandshakeInitiator KeyPair
identity
  state1 <- sendFirstMessage stream initial
  (remotePayload, state2) <- receiveIdentityMessage "initiator" stream state1
  result <- verifyRemoteIdentity "initiator" state2 remotePayload
  localPayload <- buildEncodedPayload identity staticKey []
  sendFinalMessage "initiator" stream state2 localPayload
  hashes <-
    either (fail . ("initiator decode extensions: " <>)) pure $
      decodeNoiseCerthashes remotePayload
  pure (result, hashes)

{- | Authenticate an inbound WebTransport session. The supplied certificate
multihashes are sent in the responder's signed Noise payload.
-}
performWebTransportResponder ::
  KeyPair -> [ByteString] -> StreamIO -> IO HandshakeResult
performWebTransportResponder :: KeyPair -> [ByteString] -> StreamIO -> IO HandshakeResult
performWebTransportResponder KeyPair
identity [ByteString]
certificateHashes StreamIO
stream = do
  (initial, staticKey) <- KeyPair -> IO (HandshakeState, ByteString)
initHandshakeResponder KeyPair
identity
  state1 <- receiveFirstMessage stream initial
  localPayload <- buildEncodedPayload identity staticKey certificateHashes
  state2 <- sendIdentityMessage "responder" stream state1 localPayload
  (remotePayload, finalState) <- receiveIdentityMessage "responder" stream state2
  verifyRemoteIdentity "responder" finalState remotePayload

sendFirstMessage :: StreamIO -> HandshakeState -> IO HandshakeState
sendFirstMessage :: StreamIO -> HandshakeState -> IO HandshakeState
sendFirstMessage StreamIO
stream HandshakeState
state = do
  (message, next) <-
    (String -> IO (ByteString, HandshakeState))
-> ((ByteString, HandshakeState)
    -> IO (ByteString, HandshakeState))
-> Either String (ByteString, HandshakeState)
-> IO (ByteString, HandshakeState)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO (ByteString, HandshakeState)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (ByteString, HandshakeState))
-> (String -> String) -> String -> IO (ByteString, HandshakeState)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"initiator msg1 write: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)) (ByteString, HandshakeState) -> IO (ByteString, HandshakeState)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String (ByteString, HandshakeState)
 -> IO (ByteString, HandshakeState))
-> Either String (ByteString, HandshakeState)
-> IO (ByteString, HandshakeState)
forall a b. (a -> b) -> a -> b
$
      HandshakeState
-> ByteString -> Either String (ByteString, HandshakeState)
writeHandshakeMsg HandshakeState
state ByteString
BS.empty
  writeFramedMessage stream message
  pure next

receiveFirstMessage :: StreamIO -> HandshakeState -> IO HandshakeState
receiveFirstMessage :: StreamIO -> HandshakeState -> IO HandshakeState
receiveFirstMessage StreamIO
stream HandshakeState
state = do
  message <- StreamIO -> IO ByteString
readFramedMessage StreamIO
stream
  (_, next) <-
    either (fail . ("responder msg1 read: " <>)) pure $
      readHandshakeMsg state message
  pure next

sendIdentityMessage ::
  String -> StreamIO -> HandshakeState -> ByteString -> IO HandshakeState
sendIdentityMessage :: String
-> StreamIO -> HandshakeState -> ByteString -> IO HandshakeState
sendIdentityMessage String
role StreamIO
stream HandshakeState
state ByteString
payload = do
  (message, next) <-
    (String -> IO (ByteString, HandshakeState))
-> ((ByteString, HandshakeState)
    -> IO (ByteString, HandshakeState))
-> Either String (ByteString, HandshakeState)
-> IO (ByteString, HandshakeState)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO (ByteString, HandshakeState)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (ByteString, HandshakeState))
-> (String -> String) -> String -> IO (ByteString, HandshakeState)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" msg2 write: ") String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)) (ByteString, HandshakeState) -> IO (ByteString, HandshakeState)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String (ByteString, HandshakeState)
 -> IO (ByteString, HandshakeState))
-> Either String (ByteString, HandshakeState)
-> IO (ByteString, HandshakeState)
forall a b. (a -> b) -> a -> b
$
      HandshakeState
-> ByteString -> Either String (ByteString, HandshakeState)
writeHandshakeMsg HandshakeState
state ByteString
payload
  writeFramedMessage stream message
  pure next

sendFinalMessage :: String -> StreamIO -> HandshakeState -> ByteString -> IO ()
sendFinalMessage :: String -> StreamIO -> HandshakeState -> ByteString -> IO ()
sendFinalMessage String
role StreamIO
stream HandshakeState
state ByteString
payload = do
  (message, _) <-
    (String -> IO (ByteString, HandshakeState))
-> ((ByteString, HandshakeState)
    -> IO (ByteString, HandshakeState))
-> Either String (ByteString, HandshakeState)
-> IO (ByteString, HandshakeState)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO (ByteString, HandshakeState)
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO (ByteString, HandshakeState))
-> (String -> String) -> String -> IO (ByteString, HandshakeState)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" msg3 write: ") String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)) (ByteString, HandshakeState) -> IO (ByteString, HandshakeState)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String (ByteString, HandshakeState)
 -> IO (ByteString, HandshakeState))
-> Either String (ByteString, HandshakeState)
-> IO (ByteString, HandshakeState)
forall a b. (a -> b) -> a -> b
$
      HandshakeState
-> ByteString -> Either String (ByteString, HandshakeState)
writeHandshakeMsg HandshakeState
state ByteString
payload
  writeFramedMessage stream message

receiveIdentityMessage ::
  String -> StreamIO -> HandshakeState -> IO (ByteString, HandshakeState)
receiveIdentityMessage :: String
-> StreamIO -> HandshakeState -> IO (ByteString, HandshakeState)
receiveIdentityMessage String
role StreamIO
stream HandshakeState
state = do
  message <- StreamIO -> IO ByteString
readFramedMessage StreamIO
stream
  either (fail . ((role <> " handshake read: ") <>)) pure $
    readHandshakeMsg state message

buildEncodedPayload ::
  KeyPair -> ByteString -> [ByteString] -> IO ByteString
buildEncodedPayload :: KeyPair -> ByteString -> [ByteString] -> IO ByteString
buildEncodedPayload KeyPair
identity ByteString
staticKey [ByteString]
hashes = do
  payload <-
    (String -> IO NoisePayload)
-> (NoisePayload -> IO NoisePayload)
-> Either String NoisePayload
-> IO NoisePayload
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO NoisePayload
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO NoisePayload)
-> (String -> String) -> String -> IO NoisePayload
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"Noise identity payload: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)) NoisePayload -> IO NoisePayload
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String NoisePayload -> IO NoisePayload)
-> Either String NoisePayload -> IO NoisePayload
forall a b. (a -> b) -> a -> b
$
      KeyPair -> ByteString -> Either String NoisePayload
buildHandshakePayload KeyPair
identity ByteString
staticKey
  pure $
    if null hashes
      then encodeNoisePayload payload
      else encodeNoisePayloadWithCerthashes payload hashes

verifyRemoteIdentity ::
  String -> HandshakeState -> ByteString -> IO HandshakeResult
verifyRemoteIdentity :: String -> HandshakeState -> ByteString -> IO HandshakeResult
verifyRemoteIdentity String
role HandshakeState
state ByteString
bytes = do
  payload <-
    (String -> IO NoisePayload)
-> (NoisePayload -> IO NoisePayload)
-> Either String NoisePayload
-> IO NoisePayload
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> IO NoisePayload
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO NoisePayload)
-> (String -> String) -> String -> IO NoisePayload
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" decode payload: ") String -> String -> String
forall a. Semigroup a => a -> a -> a
<>)) NoisePayload -> IO NoisePayload
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String NoisePayload -> IO NoisePayload)
-> Either String NoisePayload -> IO NoisePayload
forall a b. (a -> b) -> a -> b
$
      ByteString -> Either String NoisePayload
decodeNoisePayload ByteString
bytes
  publicKey <-
    either (fail . ((role <> " decode public key: ") <>)) pure $
      Protobuf.decodePublicKey (npIdentityKey payload)
  verifyIdentitySignature role state publicKey payload
  pure
    HandshakeResult
      { hrRemotePeerId = fromPublicKey publicKey
      , hrRemotePublicKey = publicKey
      }

verifyIdentitySignature ::
  String -> HandshakeState -> PublicKey -> NoisePayload -> IO ()
verifyIdentitySignature :: String -> HandshakeState -> PublicKey -> NoisePayload -> IO ()
verifyIdentitySignature String
role HandshakeState
state PublicKey
publicKey NoisePayload
payload =
  case HandshakeState -> Maybe ByteString
getRemoteNoiseStaticKey HandshakeState
state of
    Maybe ByteString
Nothing -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": remote Noise static key unavailable"
    Just ByteString
remoteStatic
      | PublicKey -> ByteString -> ByteString -> Bool
verifyStaticKey PublicKey
publicKey ByteString
remoteStatic (NoisePayload -> ByteString
npIdentitySig NoisePayload
payload) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
      | Bool
otherwise -> String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
role String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": identity signature verification failed"

writeFramedMessage :: StreamIO -> ByteString -> IO ()
writeFramedMessage :: StreamIO -> ByteString -> IO ()
writeFramedMessage StreamIO
stream ByteString
message =
  (String -> IO ())
-> (ByteString -> IO ()) -> Either String ByteString -> IO ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO ()
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream) (ByteString -> Either String ByteString
encodeFrame ByteString
message)

readFramedMessage :: StreamIO -> IO ByteString
readFramedMessage :: StreamIO -> IO ByteString
readFramedMessage StreamIO
stream = do
  lengthBytes <- StreamIO -> Int -> IO ByteString
readExact StreamIO
stream Int
2
  let size = Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Word16
readWord16BE ByteString
lengthBytes)
  readExact stream size

readExact :: StreamIO -> Int -> IO ByteString
readExact :: StreamIO -> Int -> IO ByteString
readExact StreamIO
stream Int
wanted = ByteString -> Int -> IO ByteString
go ByteString
BS.empty Int
wanted
 where
  go :: ByteString -> Int -> IO ByteString
go ByteString
acc Int
0 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
acc
  go ByteString
acc Int
remaining = do
    chunk <- StreamIO -> Int -> IO ByteString
streamReadChunk StreamIO
stream Int
remaining
    if BS.null chunk
      then fail "WebTransport Noise stream closed unexpectedly"
      else go (acc <> chunk) (remaining - BS.length chunk)