use std::fmt;
use std::time::{Duration, Instant};
#[cfg(feature = "pairing-code")]
use anyhow::bail;
use anyhow::{Context, Result};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
#[cfg(feature = "pairing-code")]
use syncspin_core::pairing::code::commitment;
#[cfg(feature = "pairing-code")]
use syncspin_core::pairing::code::DynamicCode;
#[cfg(feature = "pairing-code")]
use syncspin_core::pairing::pake::{self, SHARE_LEN, TAG_LEN};
#[cfg(feature = "pairing-code")]
use syncspin_core::pairing::wrap::{self, NONCE_LABEL, PSK_LABEL};
#[cfg(feature = "pairing-code")]
use crate::config::CodeFormat;
use crate::config::{PskCategory, StoredPsk};
use crate::storage::Storage;
#[cfg(feature = "pairing-code")]
use syncspin_core::noise::Suite;
use syncspin_core::noise::SENTINEL_PSK;
pub(crate) const METHOD_PAIRING_PSK: &str = "pairing_psk";
#[cfg(feature = "pairing-code")]
pub(crate) const METHOD_STATIC_PAIRING_CODE: &str = "static_pairing_code";
#[cfg(feature = "pairing-code")]
pub(crate) const METHOD_DYNAMIC_PAIRING_CODE: &str = "dynamic_pairing_code";
#[cfg(feature = "pairing-code")]
const PAKE_SID_LABEL: &[u8] = b"sendspin-pair-pake-v1";
#[cfg(feature = "pairing-code")]
const AD_SERVER: &[u8] = b"server";
#[cfg(feature = "pairing-code")]
const AD_CLIENT: &[u8] = b"client";
#[cfg(feature = "pairing-code")]
pub(crate) const STATIC_CODE_ROUND: u32 = 1;
#[cfg(feature = "pairing-code")]
const SEALED_LEN: usize = 48;
#[cfg(feature = "pairing-code")]
pub(crate) fn pake_sid(handshake_hash: &[u8; 32], pairing_index: u32, round: u32) -> Vec<u8> {
let mut sid = Vec::with_capacity(PAKE_SID_LABEL.len() + 32 + 8);
sid.extend_from_slice(PAKE_SID_LABEL);
sid.extend_from_slice(handshake_hash);
sid.extend_from_slice(&pairing_index.to_be_bytes());
sid.extend_from_slice(&round.to_be_bytes());
sid
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct PairingPsk(pub(crate) [u8; 32]);
impl PairingPsk {
pub(crate) fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl fmt::Debug for PairingPsk {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("PairingPsk")
.field(&"<redacted>")
.finish()
}
}
pub(crate) fn load_or_draw_pairing_psk(storage: &dyn Storage) -> Result<PairingPsk> {
if let Some(psk) = storage
.pairing_psk()
.context("the pairing store did not return the pairing PSK")?
{
return Ok(PairingPsk(psk));
}
let psk = draw_key();
storage
.store_pairing_psk(&psk)
.context("the pairing store did not accept the new pairing PSK")?;
Ok(PairingPsk(psk))
}
fn draw_key() -> [u8; 32] {
let mut key = [0u8; 32];
getrandom::fill(&mut key).expect("the operating system CSPRNG is available");
key
}
fn draw_long_term_psk(pairing_psk: Option<[u8; 32]>) -> [u8; 32] {
draw_long_term_psk_with(pairing_psk, draw_key)
}
fn draw_long_term_psk_with(
pairing_psk: Option<[u8; 32]>,
mut draw: impl FnMut() -> [u8; 32],
) -> [u8; 32] {
loop {
let key = draw();
if key != SENTINEL_PSK && pairing_psk != Some(key) {
return key;
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Candidates {
pairing: Option<PairingPsk>,
records: Vec<StoredPsk>,
}
impl Candidates {
pub(crate) fn load(
storage: Option<&dyn Storage>,
explicit: &[StoredPsk],
pairing: Option<PairingPsk>,
) -> Result<Candidates> {
let mut records = match storage {
Some(storage) => storage
.load_pairings()
.context("the pairing store did not return its records")?,
None => Vec::new(),
};
for record in explicit {
if !records
.iter()
.any(|held| held.server_id == record.server_id)
{
records.push(record.clone());
}
}
Ok(Candidates { pairing, records })
}
pub(crate) fn pairing(&self) -> Option<[u8; 32]> {
self.pairing.map(|psk| *psk.as_bytes())
}
pub(crate) fn remember(&mut self, record: StoredPsk) {
self.records
.retain(|held| held.server_id != record.server_id);
self.records.push(record);
}
pub(crate) fn records(&self) -> &[StoredPsk] {
&self.records
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MatchedPsk {
Sentinel,
PairingPsk,
Stored(PskCategory),
}
#[cfg(feature = "pairing-code")]
enum Flow {
PairingPsk,
Static(CodePhase),
Dynamic(DynamicFlow),
}
#[cfg(feature = "pairing-code")]
struct DynamicFlow {
nonce_b: [u8; 32],
nonce_a: Option<[u8; 32]>,
code: Option<DynamicCode>,
format: CodeFormat,
round: u32,
phase: CodePhase,
}
#[cfg(feature = "pairing-code")]
enum CodePhase {
RoundStart,
Auth,
Confirm(Box<RoundProof>),
Finalization,
}
#[cfg(feature = "pairing-code")]
impl CodePhase {
fn is_round_start(&self) -> bool {
matches!(self, CodePhase::RoundStart)
}
fn is_auth(&self) -> bool {
matches!(self, CodePhase::Auth)
}
fn is_confirm(&self) -> bool {
matches!(self, CodePhase::Confirm(_))
}
fn is_finalization(&self) -> bool {
matches!(self, CodePhase::Finalization)
}
}
#[cfg(feature = "pairing-code")]
struct RoundProof {
expected_server_tag: [u8; TAG_LEN],
client_tag: [u8; TAG_LEN],
wrapped_psk: [u8; SEALED_LEN],
wrapped_nonce_b: Option<[u8; SEALED_LEN]>,
}
#[cfg(feature = "pairing-code")]
pub(crate) struct Confirmation {
pub(crate) client_kc: String,
pub(crate) wrapped_psk: String,
pub(crate) wrapped_nonce_b: Option<String>,
}
#[cfg(feature = "pairing-code")]
pub(crate) struct CodeEmission {
pub(crate) code: String,
pub(crate) format: CodeFormat,
pub(crate) round: u32,
}
#[cfg(feature = "pairing-code")]
pub(crate) enum TagOutcome {
Confirmed(Confirmation),
Mismatch,
}
pub(crate) struct PairingAttempt {
pub(crate) pairing_index: u32,
pub(crate) deadline: Instant,
psk: [u8; 32],
#[cfg(feature = "pairing-code")]
flow: Flow,
}
impl PairingAttempt {
pub(crate) fn new(
pairing_index: u32,
timeout: Duration,
pairing_psk: Option<[u8; 32]>,
) -> PairingAttempt {
PairingAttempt {
pairing_index,
deadline: Instant::now() + timeout,
psk: draw_long_term_psk(pairing_psk),
#[cfg(feature = "pairing-code")]
flow: Flow::PairingPsk,
}
}
#[cfg(feature = "pairing-code")]
pub(crate) fn static_code(
pairing_index: u32,
timeout: Duration,
pairing_psk: Option<[u8; 32]>,
) -> PairingAttempt {
PairingAttempt {
pairing_index,
deadline: Instant::now() + timeout,
psk: draw_long_term_psk(pairing_psk),
flow: Flow::Static(CodePhase::Auth),
}
}
#[cfg(feature = "pairing-code")]
pub(crate) fn dynamic_code(
pairing_index: u32,
timeout: Duration,
pairing_psk: Option<[u8; 32]>,
format: CodeFormat,
) -> PairingAttempt {
PairingAttempt {
pairing_index,
deadline: Instant::now() + timeout,
psk: draw_long_term_psk(pairing_psk),
flow: Flow::Dynamic(DynamicFlow {
nonce_b: draw_key(),
nonce_a: None,
code: None,
format,
round: 0,
phase: CodePhase::RoundStart,
}),
}
}
#[cfg(feature = "pairing-code")]
pub(crate) fn is_static_code(&self) -> bool {
matches!(self.flow, Flow::Static(_))
}
#[cfg(feature = "pairing-code")]
pub(crate) fn is_dynamic_code(&self) -> bool {
matches!(self.flow, Flow::Dynamic(_))
}
#[cfg(feature = "pairing-code")]
pub(crate) fn commit_b(&self) -> Option<String> {
match &self.flow {
Flow::Dynamic(state) => Some(URL_SAFE_NO_PAD.encode(commitment(&state.nonce_b))),
_ => None,
}
}
#[cfg(feature = "pairing-code")]
pub(crate) fn awaiting_server_init(&self) -> bool {
matches!(
self.flow,
Flow::Dynamic(DynamicFlow {
phase: CodePhase::RoundStart,
..
})
)
}
#[cfg(feature = "pairing-code")]
pub(crate) fn awaiting_server_auth(&self) -> bool {
self.phase_is(CodePhase::is_auth)
}
#[cfg(feature = "pairing-code")]
pub(crate) fn awaiting_server_confirm(&self) -> bool {
self.phase_is(CodePhase::is_confirm)
}
#[cfg(feature = "pairing-code")]
pub(crate) fn awaiting_finalize(&self) -> bool {
self.phase_is(CodePhase::is_finalization)
}
#[cfg(feature = "pairing-code")]
fn phase_is(&self, check: fn(&CodePhase) -> bool) -> bool {
match &self.flow {
Flow::Static(phase) => check(phase),
Flow::Dynamic(state) => check(&state.phase),
Flow::PairingPsk => false,
}
}
#[cfg(feature = "pairing-code")]
pub(crate) fn round(&self) -> u32 {
match &self.flow {
Flow::Dynamic(state) => state.round.max(STATIC_CODE_ROUND),
_ => STATIC_CODE_ROUND,
}
}
#[cfg(feature = "pairing-code")]
pub(crate) fn code_emission(&self) -> Option<CodeEmission> {
let Flow::Dynamic(state) = &self.flow else {
return None;
};
let code = state.code.as_ref()?;
Some(CodeEmission {
code: match state.format {
CodeFormat::Digits => code.digits_text(),
CodeFormat::QrCode => code.qr_token(),
},
format: state.format,
round: state.round,
})
}
#[cfg(feature = "pairing-code")]
pub(crate) fn prs(&self) -> Option<Vec<u8>> {
let Flow::Dynamic(state) = &self.flow else {
return None;
};
let code = state.code.as_ref()?;
Some(match state.format {
CodeFormat::Digits => code.digits().to_vec(),
CodeFormat::QrCode => code.qr_payload().to_vec(),
})
}
#[cfg(feature = "pairing-code")]
pub(crate) fn begin_round(
&mut self,
nonce_a: Option<[u8; 32]>,
handshake_hash: &[u8; 32],
) -> Result<CodeEmission> {
let Flow::Dynamic(state) = &mut self.flow else {
bail!("the attempt does not run the dynamic pairing code flow");
};
if !state.phase.is_round_start() {
bail!("the attempt is not waiting for server/pair-init");
}
match (state.nonce_a, nonce_a) {
(None, None) => {
bail!("the first round's server/pair-init carries no nonce_A")
}
(None, Some(nonce)) => state.nonce_a = Some(nonce),
(Some(_), Some(_)) => {
bail!("the server repeated nonce_A after the first round")
}
(Some(_), None) => {}
}
state.round = state.round.saturating_add(1);
if state.code.is_none() {
let nonce_a = state
.nonce_a
.expect("the first round set the server nonce before the code is derived");
state.code = Some(DynamicCode::derive(
handshake_hash,
&nonce_a,
&state.nonce_b,
));
}
state.phase = CodePhase::Auth;
self.code_emission()
.ok_or_else(|| anyhow::anyhow!("the pairing code was not derived"))
}
#[cfg(feature = "pairing-code")]
pub(crate) fn accept_server_share(
&mut self,
prs: &[u8],
sid: &[u8],
peer_share: &[u8; SHARE_LEN],
suite: Suite,
) -> Result<[u8; SHARE_LEN]> {
if !self.awaiting_server_auth() {
bail!("the attempt is not waiting for the server's CPace share");
}
let generator = pake::generator(prs, b"", sid);
let scalar = draw_key();
let share = pake::public_share(&scalar, &generator)
.context("the CPace generator did not yield a group element")?;
let point = pake::scalar_mult_vfy(&scalar, peer_share)?;
let transcript = pake::transcript_ir(peer_share, AD_SERVER, &share, AD_CLIENT);
let isk = pake::intermediate_session_key(sid, &point, &transcript);
let expected_server_tag = pake::key_confirmation_tag(sid, &isk, peer_share, AD_SERVER);
let client_tag = pake::key_confirmation_tag(sid, &isk, &share, AD_CLIENT);
let wrapped_psk = wrap::wrap(suite, &wrap::k_wrap(PSK_LABEL, sid, &isk), &self.psk)?;
let wrapped_nonce_b = match &self.flow {
Flow::Dynamic(state) => Some(wrap::wrap(
suite,
&wrap::k_wrap(NONCE_LABEL, sid, &isk),
&state.nonce_b,
)?),
_ => None,
};
let proof = RoundProof {
expected_server_tag,
client_tag,
wrapped_psk,
wrapped_nonce_b,
};
match &mut self.flow {
Flow::Static(phase) => *phase = CodePhase::Confirm(Box::new(proof)),
Flow::Dynamic(state) => state.phase = CodePhase::Confirm(Box::new(proof)),
Flow::PairingPsk => bail!("the attempt does not run a code flow"),
}
Ok(share)
}
#[cfg(feature = "pairing-code")]
pub(crate) fn verify_server_tag(&mut self, received: &[u8; TAG_LEN]) -> TagOutcome {
let proof = match &mut self.flow {
Flow::Static(CodePhase::Confirm(proof)) => proof,
Flow::Dynamic(state) => match &mut state.phase {
CodePhase::Confirm(proof) => proof,
_ => return TagOutcome::Mismatch,
},
_ => return TagOutcome::Mismatch,
};
if !pake::verify_key_confirmation_tag(&proof.expected_server_tag, received) {
if let Flow::Dynamic(state) = &mut self.flow {
state.phase = CodePhase::RoundStart;
}
return TagOutcome::Mismatch;
}
let confirmation = Confirmation {
client_kc: URL_SAFE_NO_PAD.encode(proof.client_tag),
wrapped_psk: URL_SAFE_NO_PAD.encode(proof.wrapped_psk),
wrapped_nonce_b: proof
.wrapped_nonce_b
.map(|sealed| URL_SAFE_NO_PAD.encode(sealed)),
};
match &mut self.flow {
Flow::Static(phase) => *phase = CodePhase::Finalization,
Flow::Dynamic(state) => state.phase = CodePhase::Finalization,
Flow::PairingPsk => unreachable!("only a code flow has a round to confirm"),
}
TagOutcome::Confirmed(confirmation)
}
pub(crate) fn psk_base64(&self) -> String {
URL_SAFE_NO_PAD.encode(self.psk)
}
pub(crate) fn psk(&self) -> [u8; 32] {
self.psk
}
}
impl fmt::Debug for PairingAttempt {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = formatter.debug_struct("PairingAttempt");
debug
.field("pairing_index", &self.pairing_index)
.field("deadline", &self.deadline)
.field("psk", &"<redacted>");
#[cfg(feature = "pairing-code")]
{
let flow = match &self.flow {
Flow::PairingPsk => "pairing_psk",
Flow::Static(phase) => match phase {
CodePhase::RoundStart => "static_pairing_code/round_start",
CodePhase::Auth => "static_pairing_code/awaiting_auth",
CodePhase::Confirm(_) => "static_pairing_code/awaiting_confirm",
CodePhase::Finalization => "static_pairing_code/awaiting_finalize",
},
Flow::Dynamic(state) => match state.phase {
CodePhase::RoundStart => "dynamic_pairing_code/awaiting_server_init",
CodePhase::Auth => "dynamic_pairing_code/awaiting_auth",
CodePhase::Confirm(_) => "dynamic_pairing_code/awaiting_confirm",
CodePhase::Finalization => "dynamic_pairing_code/awaiting_finalize",
},
};
debug.field("flow", &flow);
if let Flow::Dynamic(state) = &self.flow {
debug
.field("round", &state.round)
.field("nonce_b", &"<redacted>")
.field("code", &state.code.as_ref().map(|_| "<redacted>"));
}
}
debug.finish()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use crate::test_support::MemoryStore;
const KEY: [u8; 32] = [0x5a; 32];
fn record(server_id: &str) -> StoredPsk {
StoredPsk {
category: PskCategory::LongTerm,
psk: KEY,
server_id: server_id.to_owned(),
}
}
#[test]
fn a_restored_pairing_psk_is_used_as_it_is() {
let storage = MemoryStore::holding(KEY);
let psk = load_or_draw_pairing_psk(&storage).expect("the stored key is accepted");
assert_eq!(psk.as_bytes(), &KEY);
assert_eq!(
storage.stored_pairing_psks(),
0,
"a restored key must never be replaced"
);
}
#[test]
fn a_missing_pairing_psk_is_drawn_once_and_stored() {
let storage = MemoryStore::default();
let psk = load_or_draw_pairing_psk(&storage).expect("a key is drawn");
assert_eq!(
storage.pairing_psk_value().as_ref(),
Some(psk.as_bytes()),
"the drawn key must be the one the store keeps"
);
assert_eq!(storage.stored_pairing_psks(), 1);
assert_ne!(psk.as_bytes(), &[0u8; 32], "a drawn key is not all zeroes");
let again = load_or_draw_pairing_psk(&storage).expect("the stored key is accepted");
assert_eq!(again.as_bytes(), psk.as_bytes());
assert_eq!(storage.stored_pairing_psks(), 1, "a key is never rotated");
}
#[test]
fn a_store_that_fails_is_reported_and_never_silently_replaced() {
let error = load_or_draw_pairing_psk(&MemoryStore::failing_reads())
.expect_err("a read failure is an error");
assert!(
format!("{error:#}").contains("pairing PSK"),
"got: {error:#}"
);
let error = load_or_draw_pairing_psk(&MemoryStore::failing_writes())
.expect_err("a write failure is an error");
assert!(
format!("{error:#}").contains("did not accept"),
"got: {error:#}"
);
}
#[test]
fn the_candidates_read_the_store_and_let_the_store_win() {
let storage = MemoryStore::default();
storage.preload(record("from-store"));
let explicit = [record("from-host"), record("from-store")];
let candidates = Candidates::load(Some(&storage), &explicit, None).unwrap();
let ids: Vec<&str> = candidates
.records()
.iter()
.map(|record| record.server_id.as_str())
.collect();
assert_eq!(
ids,
vec!["from-store", "from-host"],
"the store's records come first and its record for a server wins"
);
assert_eq!(candidates.pairing(), None);
let pairing = PairingPsk(KEY);
let candidates = Candidates::load(None, &[], Some(pairing)).unwrap();
assert_eq!(candidates.pairing(), Some(KEY));
assert!(candidates.records().is_empty());
}
#[test]
fn a_record_stored_during_the_connection_becomes_a_candidate() {
let mut candidates =
Candidates::load(None, &[record("from-host")], None).expect("the set builds");
assert_eq!(candidates.records().len(), 1);
candidates.remember(record("from-host"));
assert_eq!(
candidates.records().len(),
1,
"one record per server, as the store keeps it"
);
candidates.remember(record("just-paired"));
let ids: Vec<&str> = candidates
.records()
.iter()
.map(|record| record.server_id.as_str())
.collect();
assert_eq!(ids, vec!["from-host", "just-paired"]);
}
#[test]
fn a_store_that_cannot_be_read_is_an_error() {
let error = Candidates::load(Some(&MemoryStore::failing_reads()), &[], None)
.expect_err("a read failure must not fall back to fewer keys");
assert!(format!("{error:#}").contains("records"), "got: {error:#}");
}
#[test]
fn key_material_is_redacted_in_every_debug_format() {
let encoded = URL_SAFE_NO_PAD.encode(KEY);
let pairing = PairingPsk(KEY);
let attempt = PairingAttempt::new(1, Duration::from_secs(120), None);
let candidates = Candidates {
pairing: Some(pairing),
records: vec![record("a-server")],
};
for text in [
format!("{pairing:?}"),
format!("{attempt:?}"),
format!("{candidates:?}"),
] {
assert!(text.contains("<redacted>"), "unexpected format: {text}");
assert!(
!text.contains(&encoded),
"the key must not appear encoded: {text}"
);
assert!(
!text.contains(&format!("{KEY:?}")),
"not even the raw bytes may appear: {text}"
);
}
}
#[test]
fn an_attempt_expires_at_its_configured_timeout() {
let started = Instant::now();
let attempt = PairingAttempt::new(4, Duration::from_secs(120), None);
assert_eq!(attempt.pairing_index, 4);
assert!(attempt.deadline >= started + Duration::from_secs(120));
assert_ne!(attempt.psk(), [0u8; 32], "the attempt draws its own key");
assert_eq!(
attempt.psk_base64().len(),
43,
"the wire carries the key unpadded base64url"
);
}
#[test]
fn a_drawn_long_term_psk_is_never_a_forbidden_key() {
let pairing = [0x11; 32];
let allowed = [0x22; 32];
let mut draws = [SENTINEL_PSK, pairing, allowed].into_iter();
let key = draw_long_term_psk_with(Some(pairing), || {
draws.next().expect("the sequence holds enough draws")
});
assert_eq!(key, allowed);
assert!(
draws.next().is_none(),
"the loop stops at the first allowed key"
);
let mut draws = [SENTINEL_PSK, allowed].into_iter();
assert_eq!(
draw_long_term_psk_with(None, || {
draws.next().expect("the sequence holds enough draws")
}),
allowed
);
}
#[test]
fn a_store_behind_an_arc_is_still_a_candidate_source() {
let storage: Arc<dyn Storage> = Arc::new(MemoryStore::holding(KEY));
let candidates = Candidates::load(Some(storage.as_ref()), &[], None).unwrap();
assert!(candidates.records().is_empty());
}
#[cfg(feature = "pairing-code")]
const CODE: &str = "12345678";
#[cfg(feature = "pairing-code")]
fn static_round() -> (PairingAttempt, Vec<u8>, [u8; 32], [u8; 64], [u8; 64]) {
let sid = pake_sid(&[0x33; 32], 7, STATIC_CODE_ROUND);
let generator = pake::generator(CODE.as_bytes(), b"", &sid);
let server_scalar = [0x44; 32];
let peer_share = pake::public_share(&server_scalar, &generator).expect("a group element");
let mut attempt = PairingAttempt::static_code(7, Duration::from_secs(120), None);
let share = attempt
.accept_server_share(CODE.as_bytes(), &sid, &peer_share, Suite::ChaChaPoly)
.expect("the server's share is a group element");
let point = pake::scalar_mult_vfy(&server_scalar, &share).expect("a group element");
let transcript = pake::transcript_ir(&peer_share, b"server", &share, b"client");
let isk = pake::intermediate_session_key(&sid, &point, &transcript);
let server_tag = pake::key_confirmation_tag(&sid, &isk, &peer_share, b"server");
(attempt, sid, share, server_tag, isk)
}
#[cfg(feature = "pairing-code")]
#[test]
fn the_pake_sid_is_the_label_handshake_hash_and_indexes() {
let handshake_hash = [0x11; 32];
let sid = pake_sid(&handshake_hash, 0x0102_0304, 1);
let mut expected = Vec::from(b"sendspin-pair-pake-v1".as_slice());
expected.extend_from_slice(&handshake_hash);
expected.extend_from_slice(&[1, 2, 3, 4]);
expected.extend_from_slice(&[0, 0, 0, 1]);
assert_eq!(sid, expected);
assert_eq!(sid.len(), 21 + 32 + 8, "label, h and two u32");
assert_ne!(
pake_sid(&handshake_hash, 1, 1),
pake_sid(&handshake_hash, 2, 1)
);
assert_ne!(
pake_sid(&handshake_hash, 1, 1),
pake_sid(&handshake_hash, 1, 2)
);
let mut other_hash = handshake_hash;
other_hash[0] ^= 0x01;
assert_ne!(pake_sid(&other_hash, 1, 1), sid);
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_static_attempt_seals_the_key_and_releases_it_only_after_the_server_tag() {
let (mut attempt, sid, share, server_tag, isk) = static_round();
assert!(attempt.awaiting_server_confirm());
let mut tampered = server_tag;
tampered[0] ^= 0x80;
assert!(matches!(
attempt.verify_server_tag(&tampered),
TagOutcome::Mismatch
));
assert!(
attempt.awaiting_server_confirm(),
"a mismatch leaves the attempt for the caller to abort"
);
let TagOutcome::Confirmed(confirmation) = attempt.verify_server_tag(&server_tag) else {
panic!("the server's tag verifies");
};
assert!(attempt.awaiting_finalize());
assert_eq!(
confirmation.client_kc,
URL_SAFE_NO_PAD.encode(pake::key_confirmation_tag(&sid, &isk, &share, b"client"))
);
let sealed: [u8; 48] = URL_SAFE_NO_PAD
.decode(&confirmation.wrapped_psk)
.expect("the sealed key is base64url")
.try_into()
.expect("a sealed value is 48 bytes");
let key = wrap::k_wrap(PSK_LABEL, &sid, &isk);
assert_eq!(
wrap::unwrap(Suite::ChaChaPoly, &key, &sealed)
.expect("the seal opens under the server's key"),
attempt.psk(),
"the server recovers exactly the long-term PSK the record keeps"
);
assert_ne!(
attempt.psk(),
[0u8; 32],
"the attempt draws its own long-term key"
);
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_static_attempt_formats_without_its_cpace_values() {
let (attempt, _sid, _share, server_tag, _isk) = static_round();
let text = format!("{attempt:?}");
assert!(
text.contains("static_pairing_code/awaiting_confirm"),
"the phase is not secret and names itself: {text}"
);
assert!(text.contains("psk: \"<redacted>\""), "got: {text}");
assert!(
!text.contains(&URL_SAFE_NO_PAD.encode(server_tag)),
"the tag must never appear: {text}"
);
assert!(
!text.contains(&format!("{server_tag:?}")),
"not even the raw tag bytes may appear: {text}"
);
let fresh = PairingAttempt::static_code(1, Duration::from_secs(120), None);
let text = format!("{fresh:?}");
assert!(
text.contains("static_pairing_code/awaiting_auth"),
"got: {text}"
);
assert!(fresh.is_static_code());
assert!(!fresh.awaiting_server_confirm());
assert!(!fresh.awaiting_finalize());
}
#[cfg(feature = "pairing-code")]
const HASH: [u8; 32] = [0x33; 32];
#[cfg(feature = "pairing-code")]
const NONCE_A: [u8; 32] = [0x51; 32];
#[cfg(feature = "pairing-code")]
const NONCE_B: [u8; 32] = [0x77; 32];
#[cfg(feature = "pairing-code")]
fn dynamic_attempt(format: CodeFormat) -> PairingAttempt {
PairingAttempt {
pairing_index: 9,
deadline: Instant::now() + Duration::from_secs(120),
psk: [0x2a; 32],
flow: Flow::Dynamic(DynamicFlow {
nonce_b: NONCE_B,
nonce_a: None,
code: None,
format,
round: 0,
phase: CodePhase::RoundStart,
}),
}
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_dynamic_attempt_commits_to_a_fresh_nonce() {
let attempt = dynamic_attempt(CodeFormat::Digits);
let commitment = attempt.commit_b().expect("the dynamic flow commits");
assert_eq!(
commitment,
URL_SAFE_NO_PAD.encode(syncspin_core::pairing::code::commitment(&NONCE_B)),
"the commitment is the digest of the pinned nonce"
);
assert!(attempt.awaiting_server_init());
assert!(!attempt.awaiting_server_auth());
assert!(attempt.is_dynamic_code());
assert!(!attempt.is_static_code());
let other =
PairingAttempt::dynamic_code(9, Duration::from_secs(120), None, CodeFormat::Digits);
assert_ne!(
commitment,
other.commit_b().expect("the other attempt commits too"),
"a second attempt commits to a different nonce"
);
let static_attempt = PairingAttempt::static_code(1, Duration::from_secs(120), None);
assert_eq!(static_attempt.commit_b(), None);
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_dynamic_round_derives_the_code_both_sides_repeat() {
let mut attempt = dynamic_attempt(CodeFormat::Digits);
let first = attempt
.begin_round(Some(NONCE_A), &HASH)
.expect("the first round carries nonce_A");
let expected = DynamicCode::derive(&HASH, &NONCE_A, &NONCE_B);
assert_eq!(first.round, 1);
assert_eq!(first.format, CodeFormat::Digits);
assert_eq!(first.code, expected.digits_text());
assert_eq!(
attempt.prs().as_deref(),
Some(expected.digits().as_slice()),
"the digits are also CPace's PRS"
);
assert!(attempt.awaiting_server_auth());
let deadline = attempt.deadline;
fail_the_round(&mut attempt);
let retried = attempt
.begin_round(None, &HASH)
.expect("a later round carries no nonce");
assert_eq!(retried.round, 2);
assert_eq!(retried.code, first.code, "the code does not change");
assert_eq!(
attempt.deadline, deadline,
"a retry keeps the attempt's deadline"
);
assert!(
attempt.begin_round(None, &HASH).is_err(),
"a third round may not begin while the second is running"
);
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_qr_attempt_uses_the_24_byte_code() {
let mut attempt = dynamic_attempt(CodeFormat::QrCode);
let first = attempt
.begin_round(Some(NONCE_A), &HASH)
.expect("the first round carries nonce_A");
let expected = DynamicCode::derive(&HASH, &NONCE_A, &NONCE_B);
assert_eq!(first.code, expected.qr_token());
assert!(first.code.starts_with("SP:1"));
assert_eq!(
attempt.prs().as_deref(),
Some(expected.qr_payload().as_slice()),
"the raw 24-byte code is CPace's PRS"
);
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_round_rejects_a_missing_or_repeated_server_nonce() {
let mut attempt = dynamic_attempt(CodeFormat::Digits);
assert!(
attempt.begin_round(None, &HASH).is_err(),
"the first round has to carry nonce_A"
);
attempt
.begin_round(Some(NONCE_A), &HASH)
.expect("the first round is accepted");
fail_the_round(&mut attempt);
assert!(
attempt.begin_round(Some(NONCE_A), &HASH).is_err(),
"a repeated nonce_A in a later round is a message no conformant server sends"
);
let mut changed = NONCE_A;
changed[0] ^= 0x01;
assert!(
attempt.begin_round(Some(changed), &HASH).is_err(),
"a changed nonce_A would silently change the operator's code"
);
let retried = attempt
.begin_round(None, &HASH)
.expect("a later round carries no nonce_A");
assert_eq!(
retried.code,
DynamicCode::derive(&HASH, &NONCE_A, &NONCE_B).digits_text(),
"the binding values, and so the code, stay the same"
);
let mut static_attempt = PairingAttempt::static_code(1, Duration::from_secs(120), None);
assert!(static_attempt.begin_round(Some(NONCE_A), &HASH).is_err());
}
#[cfg(feature = "pairing-code")]
fn cross_the_round(attempt: &mut PairingAttempt) -> (Vec<u8>, [u8; 64], [u8; 64]) {
let prs = attempt.prs().expect("the code was derived");
let sid = pake_sid(&HASH, attempt.pairing_index, attempt.round());
let generator = pake::generator(&prs, b"", &sid);
let server_scalar = [0x44; 32];
let peer_share = pake::public_share(&server_scalar, &generator).expect("a group element");
let share = attempt
.accept_server_share(&prs, &sid, &peer_share, Suite::ChaChaPoly)
.expect("the server's share is a group element");
let point = pake::scalar_mult_vfy(&server_scalar, &share).expect("a group element");
let transcript = pake::transcript_ir(&peer_share, b"server", &share, b"client");
let isk = pake::intermediate_session_key(&sid, &point, &transcript);
let server_tag = pake::key_confirmation_tag(&sid, &isk, &peer_share, b"server");
(sid, server_tag, isk)
}
#[cfg(feature = "pairing-code")]
fn fail_the_round(attempt: &mut PairingAttempt) {
let (_sid, server_tag, _isk) = cross_the_round(attempt);
let mut tampered = server_tag;
tampered[0] ^= 0x80;
assert!(matches!(
attempt.verify_server_tag(&tampered),
TagOutcome::Mismatch
));
assert!(
attempt.awaiting_server_init(),
"a failed round waits for the next server/pair-init"
);
}
#[cfg(feature = "pairing-code")]
fn dynamic_round(format: CodeFormat) -> (PairingAttempt, Vec<u8>, [u8; 64], [u8; 64]) {
let mut attempt = dynamic_attempt(format);
let emission = attempt
.begin_round(Some(NONCE_A), &HASH)
.expect("the first round carries nonce_A");
let prs = attempt.prs().expect("the code was derived");
assert_eq!(
prs.len(),
match format {
CodeFormat::Digits => 6,
CodeFormat::QrCode => 24,
},
"the PRS belongs to the emission format: {}",
emission.code.len()
);
let (sid, server_tag, isk) = cross_the_round(&mut attempt);
(attempt, sid, server_tag, isk)
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_dynamic_attempt_seals_the_nonce_and_releases_it_only_after_the_server_tag() {
let (mut attempt, sid, server_tag, isk) = dynamic_round(CodeFormat::Digits);
assert!(attempt.awaiting_server_confirm());
let mut tampered = server_tag;
tampered[0] ^= 0x80;
assert!(matches!(
attempt.verify_server_tag(&tampered),
TagOutcome::Mismatch
));
assert!(
attempt.awaiting_server_init(),
"a failed round waits for the next server/pair-init"
);
assert!(
attempt.code_emission().is_some(),
"the code survives the failed round"
);
let emission = attempt
.begin_round(None, &HASH)
.expect("the retry's round begins without a nonce");
assert_eq!(emission.round, 2);
let (retry_sid, retry_tag, retry_isk) = cross_the_round(&mut attempt);
let TagOutcome::Confirmed(confirmation) = attempt.verify_server_tag(&retry_tag) else {
panic!("the server's tag verifies");
};
assert!(attempt.awaiting_finalize());
let sealed: [u8; 48] = URL_SAFE_NO_PAD
.decode(
confirmation
.wrapped_nonce_b
.as_deref()
.expect("the dynamic flow seals its nonce"),
)
.expect("the sealed nonce is base64url")
.try_into()
.expect("a sealed value is 48 bytes");
let nonce_key = wrap::k_wrap(NONCE_LABEL, &retry_sid, &retry_isk);
assert_eq!(
wrap::unwrap(Suite::ChaChaPoly, &nonce_key, &sealed)
.expect("the seal opens under the server's key"),
NONCE_B,
"the server recovers exactly the nonce it committed to"
);
let sealed_psk: [u8; 48] = URL_SAFE_NO_PAD
.decode(&confirmation.wrapped_psk)
.expect("the sealed key is base64url")
.try_into()
.expect("a sealed value is 48 bytes");
let psk_key = wrap::k_wrap(PSK_LABEL, &retry_sid, &retry_isk);
assert_eq!(
wrap::unwrap(Suite::ChaChaPoly, &psk_key, &sealed_psk).expect("the seal opens"),
attempt.psk()
);
assert_ne!(sid, retry_sid, "each round has its own sid");
assert_ne!(isk, retry_isk, "each round derives its own session key");
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_dynamic_attempt_formats_without_its_nonce_or_code() {
let mut attempt = dynamic_attempt(CodeFormat::Digits);
let text = format!("{attempt:?}");
assert!(
text.contains("dynamic_pairing_code/awaiting_server_init"),
"the phase names itself: {text}"
);
assert!(
!text.contains(&format!("{:?}", NONCE_B)),
"the nonce must never appear: {text}"
);
assert!(text.contains("nonce_b: \"<redacted>\""), "got: {text}");
assert!(text.contains("code: None"), "got: {text}");
let emission = attempt
.begin_round(Some(NONCE_A), &HASH)
.expect("the first round carries nonce_A");
let text = format!("{attempt:?}");
assert!(
text.contains("dynamic_pairing_code/awaiting_auth"),
"got: {text}"
);
assert!(text.contains("code: Some(\"<redacted>\")"), "got: {text}");
assert!(
!text.contains(&emission.code),
"the code reaches the operator through the event, not a log line: {text}"
);
assert!(
!text.contains(&format!("{:?}", NONCE_A)),
"the server nonce stays out of a format as well: {text}"
);
}
}