use super::parameter_range::check_compatibility;
use super::request::check_parameter_range;
use crate::Error;
use crate::derec_message::{DeRecMessageBuilder, current_timestamp, open_plaintext_message};
use crate::extensions::advertised_endpoints::AdvertisedEndpoints as _;
use crate::extensions::contact_message::ContactMessageExt as _;
use crate::extensions::derec_result::DeRecResultExt as _;
use crate::extensions::pair_request::PairRequestMessageExt as _;
use crate::primitives::pairing::PairingError;
use crate::transport::TransportPolicy;
use crate::types::ChannelId;
use crate::utils::verify_protocol_version;
use crate::utils::{generate_seed, verify_timestamps};
use derec_cryptography::pairing::{
self as cryptography_pairing, DerecPairingError, FingerprintCommitment, FingerprintNonce,
PairingSecretKeyMaterial, PairingSharedKey, envelope as pairing_envelope,
};
use derec_proto::{
CommunicationInfo, ContactMessage, ContactMode, DeRecMessage, DeRecResult, MessageBody,
PairRequestMessage, PairResponseMessage, ParameterRange, PrePairRequestMessage,
PrePairResponseMessage, StatusEnum, TransportProtocol,
};
use prost::Message;
use sha2::{Digest, Sha384};
use subtle::ConstantTimeEq;
pub struct ProduceResult {
pub envelope: Vec<u8>,
pub peer_transports: Vec<TransportProtocol>,
pub shared_key: PairingSharedKey,
pub channel_id: ChannelId,
}
pub struct ExtractResult {
pub response: PairResponseMessage,
}
pub struct ProcessResult {
pub shared_key: PairingSharedKey,
pub channel_id: ChannelId,
}
pub struct ProducePrePairResult {
pub envelope: Vec<u8>,
}
pub struct ProducePrePairNoKeysResult {
pub envelope: Vec<u8>,
pub pairing_secret_key_material: PairingSecretKeyMaterial,
}
pub struct PrePairExtractResult {
pub response: PrePairResponseMessage,
}
pub struct ProcessPrePairResult {
pub mlkem_encapsulation_key: Vec<u8>,
pub ecies_public_key: Vec<u8>,
pub nonce: u64,
pub fingerprint_commitment: Vec<u8>,
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
pub fn produce(
channel_id: ChannelId,
request: &PairRequestMessage,
pairing_secret_key_material: &PairingSecretKeyMaterial,
communication_info: Option<CommunicationInfo>,
parameter_range: Option<ParameterRange>,
policy: TransportPolicy,
) -> Result<ProduceResult, Error> {
request.validate()?;
check_parameter_range(request, parameter_range.as_ref())?;
let peer_transports = policy.admit_peer_endpoints(request.advertised_endpoints())?;
let pairing_request = cryptography_pairing::PairingRequestMessageMaterial {
mlkem_ciphertext: request.mlkem_ciphertext.clone(),
ecies_public_key: request.ecies_public_key.clone(),
};
let initiator_material = match pairing_secret_key_material {
PairingSecretKeyMaterial::Initiator(m) => m,
_ => {
return Err(PairingError::Invariant(
"expected Initiator key material for pairing response",
)
.into());
}
};
let shared_key =
cryptography_pairing::finish_pairing_initiator(initiator_material, &pairing_request)
.map_err(|e| PairingError::FinishPairingInitiator { source: e })?;
let rekeyed_channel_id = derive_rekeyed_channel_id(channel_id, &shared_key);
let timestamp = current_timestamp();
let response = PairResponseMessage {
result: Some(DeRecResult::ok()),
nonce: request.nonce,
communication_info,
parameter_range,
timestamp: Some(timestamp),
channel_id: rekeyed_channel_id.into(),
fingerprint_nonce: Some(initiator_material.fingerprint_nonce.to_vec()),
};
let envelope = DeRecMessageBuilder::pairing()
.channel_id(channel_id)
.timestamp(timestamp)
.message_body(MessageBody::PairResponse(response))
.encrypt_pairing(&request.ecies_public_key)?
.build()?
.encode_to_vec();
#[cfg(feature = "logging")]
tracing::info!("pairing response envelope produced; initiator shared key derived");
Ok(ProduceResult {
envelope,
shared_key,
peer_transports,
channel_id: rekeyed_channel_id,
})
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
pub fn produce_pre_pair(
channel_id: ChannelId,
request: &PrePairRequestMessage,
pairing_secret_key_material: &PairingSecretKeyMaterial,
) -> Result<ProducePrePairResult, Error> {
let initiator_material = match pairing_secret_key_material {
PairingSecretKeyMaterial::Initiator(m) => m,
_ => {
#[cfg(feature = "logging")]
tracing::warn!("expected Initiator key material for PrePair response");
return Err(PairingError::Invariant(
"expected Initiator key material for PrePair response",
)
.into());
}
};
let commitment = initiator_material
.fingerprint_commitment()
.map_err(|source| PairingError::ContactMessageKeygen { source })?;
let timestamp = current_timestamp();
let response = PrePairResponseMessage {
result: Some(DeRecResult::ok()),
mlkem_encapsulation_key: Some(initiator_material.mlkem_encapsulation_key.clone()),
ecies_public_key: Some(initiator_material.ecies_public_key.clone()),
nonce: request.nonce,
timestamp: Some(timestamp),
fingerprint_commitment: Some(commitment.to_vec()),
};
let envelope = DeRecMessageBuilder::plaintext()
.channel_id(channel_id)
.timestamp(timestamp)
.message_body(MessageBody::PrePairResponse(response))
.build()?
.encode_to_vec();
#[cfg(feature = "logging")]
tracing::info!("PrePair response envelope produced");
Ok(ProducePrePairResult { envelope })
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
pub fn produce_pre_pair_no_keys(
channel_id: ChannelId,
request: &PrePairRequestMessage,
) -> Result<ProducePrePairNoKeysResult, Error> {
let seed = generate_seed::<32>();
let (pk, secret_key) = cryptography_pairing::contact_message(*seed)
.map_err(|e| PairingError::ContactMessageKeygen { source: e })?;
let commitment = secret_key
.fingerprint_commitment()
.map_err(|source| PairingError::ContactMessageKeygen { source })?;
let timestamp = current_timestamp();
let response = PrePairResponseMessage {
result: Some(DeRecResult::ok()),
mlkem_encapsulation_key: Some(pk.mlkem_encapsulation_key.clone()),
ecies_public_key: Some(pk.ecies_public_key.clone()),
nonce: request.nonce,
timestamp: Some(timestamp),
fingerprint_commitment: Some(commitment.to_vec()),
};
let envelope = DeRecMessageBuilder::plaintext()
.channel_id(channel_id)
.timestamp(timestamp)
.message_body(MessageBody::PrePairResponse(response))
.build()?
.encode_to_vec();
#[cfg(feature = "logging")]
tracing::info!("NoKeys PrePair response envelope produced with fresh key material");
Ok(ProducePrePairNoKeysResult {
envelope,
pairing_secret_key_material: PairingSecretKeyMaterial::Initiator(secret_key),
})
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(envelope_len = envelope_bytes.len()))
)]
pub fn extract(envelope_bytes: &[u8], ecies_secret_key: &[u8]) -> Result<ExtractResult, Error> {
let envelope = DeRecMessage::decode(envelope_bytes).map_err(Error::ProtobufDecode)?;
let plaintext = pairing_envelope::decrypt(&envelope.message, ecies_secret_key)
.map_err(PairingError::PairingEncryption)?;
let (body, version) =
MessageBody::decode_versioned(plaintext.as_slice()).map_err(Error::ProtobufDecode)?;
verify_protocol_version(&envelope, version)?;
let response = match body {
MessageBody::PairResponse(r) => r,
_ => {
#[cfg(feature = "logging")]
tracing::warn!("unexpected message type; expected PairResponseMessage");
return Err(Error::Invariant(
"Invalid message. Expected: PairResponseMessage",
));
}
};
verify_timestamps(envelope.timestamp, response.timestamp)?;
#[cfg(feature = "logging")]
tracing::info!("pairing response extracted and validated");
Ok(ExtractResult { response })
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(envelope_len = envelope_bytes.len()))
)]
pub fn extract_pre_pair(envelope_bytes: &[u8]) -> Result<PrePairExtractResult, Error> {
let envelope = DeRecMessage::decode(envelope_bytes).map_err(Error::ProtobufDecode)?;
let response = match open_plaintext_message(&envelope)? {
MessageBody::PrePairResponse(r) => r,
_ => {
#[cfg(feature = "logging")]
tracing::warn!("unexpected message type; expected PrePairResponseMessage");
return Err(Error::Invariant(
"Invalid message. Expected: PrePairResponseMessage",
));
}
};
verify_timestamps(envelope.timestamp, response.timestamp)?;
#[cfg(feature = "logging")]
tracing::info!("PrePair response envelope decoded and validated");
Ok(PrePairExtractResult { response })
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(channel_id = contact_message.channel_id))
)]
pub fn process(
contact_message: &ContactMessage,
response: &PairResponseMessage,
pairing_secret_key_material: &PairingSecretKeyMaterial,
parameter_range: Option<&ParameterRange>,
) -> Result<ProcessResult, Error> {
check_compatibility(parameter_range, response.parameter_range.as_ref())?;
let responder_material =
validate_process_inputs(contact_message, response, pairing_secret_key_material)?;
let pairing_contact_key_material = build_pairing_contact_material(contact_message);
let (fingerprint_commitment, fingerprint_nonce) =
fingerprint_opening(contact_message, response)?;
let shared_key = cryptography_pairing::finish_pairing_responder(
responder_material,
&pairing_contact_key_material,
&fingerprint_commitment,
&fingerprint_nonce,
)
.map_err(|e| match e {
DerecPairingError::FingerprintCommitmentMismatch => {
PairingError::FingerprintCommitmentMismatch
}
source => PairingError::FinishPairingResponder { source },
})?;
let expected_channel_id =
validate_rekeyed_channel_id(response, ChannelId(contact_message.channel_id), &shared_key)?;
#[cfg(feature = "logging")]
tracing::info!("pairing complete; responder shared key derived");
Ok(ProcessResult {
shared_key,
channel_id: expected_channel_id,
})
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(channel_id = contact_message.channel_id))
)]
pub fn process_pre_pair(
contact_message: &ContactMessage,
response: &PrePairResponseMessage,
) -> Result<ProcessPrePairResult, Error> {
validate_process_pre_pair_inputs(contact_message, response, ContactMode::HashedKeys)?;
let (mlkem_encapsulation_key, ecies_public_key) =
validate_contact_binding_hash(contact_message, response)?;
#[cfg(feature = "logging")]
tracing::info!("PrePair response validated against contact binding hash");
Ok(ProcessPrePairResult {
mlkem_encapsulation_key,
ecies_public_key,
nonce: response.nonce,
fingerprint_commitment: response
.fingerprint_commitment
.clone()
.expect("validate_process_pre_pair_inputs guarantees fingerprint_commitment is Some"),
})
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(channel_id = contact_message.channel_id))
)]
pub fn process_pre_pair_no_keys(
contact_message: &ContactMessage,
response: &PrePairResponseMessage,
) -> Result<ProcessPrePairResult, Error> {
validate_process_pre_pair_inputs(contact_message, response, ContactMode::NoKeys)?;
let mlkem_encapsulation_key = response
.mlkem_encapsulation_key
.clone()
.expect("validate_process_pre_pair_inputs guarantees mlkem_encapsulation_key is Some");
let ecies_public_key = response
.ecies_public_key
.clone()
.expect("validate_process_pre_pair_inputs guarantees ecies_public_key is Some");
#[cfg(feature = "logging")]
tracing::info!("NoKeys PrePair response accepted without hash verification");
Ok(ProcessPrePairResult {
mlkem_encapsulation_key,
ecies_public_key,
nonce: response.nonce,
fingerprint_commitment: response
.fingerprint_commitment
.clone()
.expect("validate_process_pre_pair_inputs guarantees fingerprint_commitment is Some"),
})
}
fn validate_process_inputs<'a>(
contact_message: &ContactMessage,
response: &PairResponseMessage,
pairing_secret_key_material: &'a PairingSecretKeyMaterial,
) -> Result<&'a cryptography_pairing::ResponderSecretKeyMaterial, Error> {
let res = response
.result
.as_ref()
.ok_or(PairingError::InvalidPairResponseMessage("missing result"))?;
if res.status != StatusEnum::Ok as i32 {
#[cfg(feature = "logging")]
tracing::warn!(status = res.status, memo = %res.memo, "pair response status is not Ok");
return Err(PairingError::NonOkStatus {
status: res.status,
memo: res.memo.to_owned(),
}
.into());
}
let mlkem_present = contact_message
.mlkem_encapsulation_key
.as_ref()
.is_some_and(|v| !v.is_empty());
if !mlkem_present {
#[cfg(feature = "logging")]
tracing::warn!("contact message missing mlkem_encapsulation_key");
return Err(PairingError::InvalidContactMessage("mlkem_encapsulation_key is empty").into());
}
let ecies_present = contact_message
.ecies_public_key
.as_ref()
.is_some_and(|v| !v.is_empty());
if !ecies_present {
#[cfg(feature = "logging")]
tracing::warn!("contact message missing ecies_public_key");
return Err(PairingError::InvalidContactMessage("ecies_public_key is empty").into());
}
if response.nonce != contact_message.nonce {
#[cfg(feature = "logging")]
tracing::warn!("nonce mismatch; possible replay or wrong pairing session");
return Err(PairingError::ProtocolViolation("nonce mismatch").into());
}
match pairing_secret_key_material {
PairingSecretKeyMaterial::Responder(m) => Ok(m),
PairingSecretKeyMaterial::Initiator(_) => Err(PairingError::Invariant(
"expected Responder key material for pairing process",
)
.into()),
}
}
fn fingerprint_opening(
contact_message: &ContactMessage,
response: &PairResponseMessage,
) -> Result<(FingerprintCommitment, FingerprintNonce), Error> {
let commitment = contact_message
.fingerprint_commitment
.as_deref()
.and_then(|c| FingerprintCommitment::try_from(c).ok())
.ok_or(PairingError::InvalidContactMessage(
"contact carries no 32-byte fingerprint_commitment",
))?;
let nonce = response
.fingerprint_nonce
.as_deref()
.and_then(|n| FingerprintNonce::try_from(n).ok())
.ok_or(PairingError::InvalidPairResponseMessage(
"pair response carries no 32-byte fingerprint_nonce",
))?;
Ok((commitment, nonce))
}
fn build_pairing_contact_material(
contact_message: &ContactMessage,
) -> cryptography_pairing::PairingContactMessageMaterial {
let mlkem_encapsulation_key = contact_message
.mlkem_encapsulation_key
.as_ref()
.expect("validate_process_inputs guarantees mlkem_encapsulation_key is Some")
.clone();
let ecies_public_key = contact_message
.ecies_public_key
.as_ref()
.expect("validate_process_inputs guarantees ecies_public_key is Some")
.clone();
cryptography_pairing::PairingContactMessageMaterial {
mlkem_encapsulation_key,
ecies_public_key,
}
}
fn validate_rekeyed_channel_id(
response: &PairResponseMessage,
original_channel_id: ChannelId,
shared_key: &PairingSharedKey,
) -> Result<ChannelId, Error> {
let expected_channel_id = derive_rekeyed_channel_id(original_channel_id, shared_key);
if response.channel_id != u64::from(expected_channel_id) {
#[cfg(feature = "logging")]
tracing::warn!(
advertised = response.channel_id,
expected = u64::from(expected_channel_id),
"channel id rekey mismatch"
);
return Err(PairingError::ProtocolViolation("channel_id rekey mismatch").into());
}
Ok(expected_channel_id)
}
fn validate_process_pre_pair_inputs(
contact_message: &ContactMessage,
response: &PrePairResponseMessage,
expected_mode: ContactMode,
) -> Result<(), Error> {
let res = response
.result
.as_ref()
.ok_or(PairingError::InvalidPairResponseMessage("missing result"))?;
if res.status != StatusEnum::Ok as i32 {
#[cfg(feature = "logging")]
tracing::warn!(
status = res.status,
memo = %res.memo,
"PrePair response status is not Ok"
);
return Err(PairingError::NonOkStatus {
status: res.status,
memo: res.memo.to_owned(),
}
.into());
}
contact_message.validate_for_mode(expected_mode)?;
let mlkem_present = response
.mlkem_encapsulation_key
.as_ref()
.is_some_and(|v| !v.is_empty());
if !mlkem_present {
#[cfg(feature = "logging")]
tracing::warn!("PrePair response missing mlkem_encapsulation_key");
return Err(
PairingError::InvalidPairResponseMessage("mlkem_encapsulation_key is empty").into(),
);
}
let ecies_present = response
.ecies_public_key
.as_ref()
.is_some_and(|v| !v.is_empty());
if !ecies_present {
#[cfg(feature = "logging")]
tracing::warn!("PrePair response missing ecies_public_key");
return Err(PairingError::InvalidPairResponseMessage("ecies_public_key is empty").into());
}
if response
.fingerprint_commitment
.as_ref()
.is_none_or(|c| c.len() != 32)
{
#[cfg(feature = "logging")]
tracing::warn!("PrePair response carries no 32-byte fingerprint_commitment");
return Err(PairingError::InvalidPairResponseMessage(
"fingerprint_commitment is not a SHA-256 digest",
)
.into());
}
if response.nonce != contact_message.nonce {
#[cfg(feature = "logging")]
tracing::warn!("nonce mismatch; possible replay or wrong pairing session");
return Err(PairingError::ProtocolViolation("nonce mismatch").into());
}
Ok(())
}
fn derive_rekeyed_channel_id(
original_channel_id: ChannelId,
shared_key: &PairingSharedKey,
) -> ChannelId {
let mut hasher = Sha384::new();
hasher.update(u64::from(original_channel_id).to_be_bytes());
hasher.update(shared_key.as_slice());
let digest = hasher.finalize();
let prefix: [u8; 8] = digest[..8]
.try_into()
.expect("SHA-384 digest has at least 8 bytes");
ChannelId(u64::from_be_bytes(prefix))
}
fn validate_contact_binding_hash(
contact_message: &ContactMessage,
response: &PrePairResponseMessage,
) -> Result<(Vec<u8>, Vec<u8>), Error> {
let mlkem_encapsulation_key = response
.mlkem_encapsulation_key
.clone()
.expect("validate_process_pre_pair_inputs guarantees mlkem_encapsulation_key is Some");
let ecies_public_key = response
.ecies_public_key
.clone()
.expect("validate_process_pre_pair_inputs guarantees ecies_public_key is Some");
let expected_hash = contact_message
.contact_binding_hash
.as_ref()
.expect("validate_process_pre_pair_inputs guarantees contact_binding_hash is Some");
let recomputed = cryptography_pairing::contact_binding_hash(
&mlkem_encapsulation_key,
&ecies_public_key,
contact_message.nonce,
contact_message.channel_id,
)
.map_err(|_e| {
#[cfg(feature = "logging")]
tracing::warn!(error = %_e, "published keys do not have the committed sizes");
Error::from(PairingError::PrePairHashMismatch)
})?;
let matched: bool = recomputed.as_slice().ct_eq(expected_hash.as_slice()).into();
if !matched {
#[cfg(feature = "logging")]
tracing::warn!(
"contact binding hash mismatch; published keys do not match the contact commitment"
);
return Err(PairingError::PrePairHashMismatch.into());
}
Ok((mlkem_encapsulation_key, ecies_public_key))
}