rtci-ice 0.5.0

Sans-I/O ICE agent (RFC 8445) with trickle ICE, ICE-TCP and consent freshness, for WebRTC
Documentation
//! RFC 8838 rows of the agent: a local candidate is paired only once it has been conveyed to
//! the peer (Section 10), and candidates are paired in the order they are conveyed (Section
//! 17). Read from the wire in virtual time, as the other agent tests.

use std::sync::Arc;
use std::time::{Duration, Instant};

use super::agent_rfc8445_test::*;
use super::*;

/// An agent with the peer's credentials and its candidate `REMOTE_A`, and no local candidate.
fn agent_without_local_candidates(now: Instant, config: AgentConfig) -> Agent {
    let mut a = Agent::new(now, Arc::new(config), provider()).unwrap();
    a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
    a.start_connectivity_checks(now, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
        .unwrap();
    a
}

/// Section 10, item 1: "A Trickle ICE agent MUST NOT pair a local candidate until it has been
/// trickled to the remote party." Items 2 and 3: once conveyed, it is paired with the remote
/// candidates known.
#[test]
fn test_unconveyed_local_candidate_is_paired_and_checked_only_once_conveyed() {
    let now = Instant::now();
    let mut a = agent_without_local_candidates(now, config(true));
    let local = host(addr(LOCAL));
    let id = local.id().to_owned();
    assert!(a.add_unconveyed_local_candidate(local).unwrap());
    assert!(a.is_local_candidate_unconveyed(&id));
    assert!(a.get_candidate_pairs().is_empty(), "paired before conveyed");
    let later = now + Duration::from_secs(2);
    assert!(
        requests(&run(&mut a, now, later)).is_empty(),
        "a check left on an unconveyed candidate"
    );
    // The candidate is still one to signal.
    assert_eq!(a.get_local_candidates_to_signal().len(), 1);

    assert!(a.local_candidate_conveyed(&id));
    assert!(!a.is_local_candidate_unconveyed(&id));
    assert!(!a.local_candidate_conveyed(&id), "conveyed once");
    assert_eq!(a.get_candidate_pairs().len(), 1);
    let out = run(&mut a, later, later + Duration::from_secs(1));
    assert!(
        requests(&out).iter().any(|(_, to)| *to == addr(REMOTE_A)),
        "the conveyed candidate is checked"
    );
}

/// A remote candidate that arrives while a local candidate is held is not paired with it
/// either; `all_local_candidates_conveyed` (a description listing them was set) pairs them.
#[test]
fn test_remote_candidate_waits_for_the_held_local_candidate_to_be_conveyed() {
    let now = Instant::now();
    let cfg = AgentConfig {
        hold_local_candidates_until_conveyed: true,
        ..config(true)
    };
    let mut a = Agent::new(now, Arc::new(cfg), provider()).unwrap();
    // With the setting, `add_local_candidate` holds the candidate too.
    a.add_local_candidate(host(addr(LOCAL))).unwrap();
    a.start_connectivity_checks(now, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
        .unwrap();
    a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
    a.add_remote_candidate(host(addr(REMOTE_B))).unwrap();
    assert!(a.get_candidate_pairs().is_empty());
    assert!(requests(&run(&mut a, now, now + Duration::from_secs(1))).is_empty());

    a.all_local_candidates_conveyed();
    assert_eq!(a.get_candidate_pairs().len(), 2);
}

/// Section 17: "an agent SHOULD pair candidates in the order in which they are conveyed":
/// two local candidates conveyed in the opposite order of their gathering are paired (and
/// their pairs listed) in the order conveyed.
#[test]
fn test_local_candidates_are_paired_in_the_order_they_are_conveyed() {
    let now = Instant::now();
    let mut a = agent_without_local_candidates(now, config(true));
    let first = host(addr("192.168.0.2:1000"));
    let second = host(addr("192.168.0.2:1001"));
    let (first_id, second_id) = (first.id().to_owned(), second.id().to_owned());
    a.add_unconveyed_local_candidate(first).unwrap();
    a.add_unconveyed_local_candidate(second).unwrap();
    assert!(a.local_candidate_conveyed(&second_id));
    let pairs = a.get_candidate_pairs();
    assert_eq!(pairs.len(), 1);
    assert_eq!(pairs[0].0.port(), 1001);
    assert!(a.local_candidate_conveyed(&first_id));
    let ports: Vec<u16> = a.get_candidate_pairs().iter().map(|p| p.0.port()).collect();
    assert_eq!(ports, vec![1001, 1000]);
}

// --- RFC 8445 Section 5.2: a lite agent's local preferences ---

fn lite_with(now: Instant, network_types: Vec<NetworkType>) -> Agent {
    let cfg = AgentConfig {
        lite: true,
        candidate_types: vec![CandidateType::Host],
        network_types,
        ..config(false)
    };
    Agent::new(now, Arc::new(cfg), provider()).unwrap()
}

/// Section 5.2: "If an ICE lite agent is dual-stack or IPv6-only, the local preference SHOULD
/// be set to the precedence value for IP addresses described in [RFC 6724]": a global IPv6
/// address (40) before IPv4 (35) before a unique-local one (3), whatever the order they are
/// added in, and every priority unique. An IPv4-only lite agent keeps 65535.
#[test]
fn test_dual_stack_lite_agent_takes_local_preference_from_rfc6724_precedence() {
    let now = Instant::now();
    let mut a = lite_with(now, vec![NetworkType::Udp4, NetworkType::Udp6]);
    for address in [
        "[fd00::1]:1000",
        "192.168.0.2:1000",
        "[2a01:4f8::1]:1000",
        "[2a01:4f8::2]:1000",
    ] {
        assert!(a.add_local_candidate(host(addr(address))).unwrap());
    }
    let priority = |ip: &str| {
        a.get_local_candidates()
            .iter()
            .find(|c| c.addr().ip().to_string() == ip)
            .unwrap()
            .priority()
    };
    let local_preference = |p: u32| (p >> 8) & 0xffff;
    assert_eq!(local_preference(priority("2a01:4f8::1")) >> 8, 40);
    assert_eq!(local_preference(priority("192.168.0.2")) >> 8, 35);
    assert_eq!(local_preference(priority("fd00::1")) >> 8, 3);
    assert!(priority("2a01:4f8::1") > priority("192.168.0.2"));
    assert!(priority("192.168.0.2") > priority("fd00::1"));
    assert_ne!(priority("2a01:4f8::1"), priority("2a01:4f8::2"));

    let mut v4 = lite_with(now, vec![NetworkType::Udp4]);
    v4.add_local_candidate(host(addr("192.168.0.2:1000")))
        .unwrap();
    assert_eq!(
        local_preference(v4.get_local_candidates()[0].priority()),
        65535
    );
}

/// Section 5.2 with RFC 6544 section 4.2: a dual-stack lite agent's TCP candidates keep the
/// direction-pref of their local preference ("(2^13) * direction-pref + other-pref"), the
/// precedence going into other-pref. Engine-gathered TCP candidates come without a priority
/// (the agent ranks them): an active and a passive one on one address get different
/// priorities, the active one above (6 against 4), and of two passive ones the global IPv6
/// address (precedence 40) is above the IPv4 one (35). Two lite agents pick their pair by
/// these priorities (Section 8.2); equal ones made the controlling agent pick a pair whose
/// connection it could not open.
#[test]
fn test_dual_stack_lite_agent_keeps_the_tcp_direction_preference() {
    use crate::candidate::candidate_host::CandidateHostConfig;
    use crate::tcp_type::TcpType;
    let now = Instant::now();
    let mut a = lite_with(
        now,
        vec![
            NetworkType::Udp4,
            NetworkType::Udp6,
            NetworkType::Tcp4,
            NetworkType::Tcp6,
        ],
    );
    let tcp = |ip: &str, port: u16, tcp_type: TcpType| {
        CandidateHostConfig {
            base_config: CandidateConfig {
                network: "tcp".to_owned(),
                address: ip.to_owned(),
                port,
                component: 1,
                ..Default::default()
            },
            tcp_type,
        }
        .new_candidate_host()
        .unwrap()
    };
    // The IPv6 candidate first: the host is dual stack from the start (Section 5.2).
    assert!(
        a.add_local_candidate(tcp("2a01:4f8::1", 5001, TcpType::Passive))
            .unwrap()
    );
    assert!(
        a.add_local_candidate(tcp("10.0.0.1", 9, TcpType::Active))
            .unwrap()
    );
    assert!(
        a.add_local_candidate(tcp("10.0.0.1", 5001, TcpType::Passive))
            .unwrap()
    );
    let priority = |ip: &str, tcp_type: TcpType| {
        a.get_local_candidates()
            .iter()
            .find(|c| c.addr().ip().to_string() == ip && c.tcp_type() == tcp_type)
            .unwrap()
            .priority()
    };
    let local_preference = |p: u32| (p >> 8) & 0xffff;
    let active = priority("10.0.0.1", TcpType::Active);
    let passive = priority("10.0.0.1", TcpType::Passive);
    let passive6 = priority("2a01:4f8::1", TcpType::Passive);
    assert_eq!(
        local_preference(active) >> 13,
        6,
        "direction-pref of active"
    );
    assert_eq!(
        local_preference(passive) >> 13,
        4,
        "direction-pref of passive"
    );
    assert!(active > passive && active > passive6);
    assert!(
        passive6 > passive,
        "precedence 40 above 35 within a direction"
    );
}

/// Section 5.2: "If a host is IPv4 only, the local preference value SHOULD be set to 65535",
/// judged from the host's candidates, not the configured network types: with the default
/// network types (IPv6 among them), a lite agent whose candidates are IPv4 keeps 65535 for UDP
/// (and RFC 6544's form, other-pref 8191, for TCP). An IPv6 candidate that comes later makes the
/// host dual stack from then on: it takes the precedence form, the IPv4 candidates already
/// signalled keep their priority, and every priority stays unique.
#[test]
fn test_ipv4_only_lite_agent_keeps_65535_with_the_default_network_types() {
    use crate::candidate::candidate_host::CandidateHostConfig;
    use crate::tcp_type::TcpType;
    let now = Instant::now();
    let mut a = lite_with(now, crate::network_type::supported_network_types());
    assert!(a.network_types.iter().any(|t| t.is_ipv6()), "IPv6 allowed");
    assert!(
        a.add_local_candidate(host(addr("192.168.0.2:1000")))
            .unwrap()
    );
    let tcp = CandidateHostConfig {
        base_config: CandidateConfig {
            network: "tcp".to_owned(),
            address: "192.168.0.2".to_owned(),
            port: 5001,
            component: 1,
            ..Default::default()
        },
        tcp_type: TcpType::Passive,
    }
    .new_candidate_host()
    .unwrap();
    assert!(a.add_local_candidate(tcp).unwrap());
    let local_preference = |p: u32| (p >> 8) & 0xffff;
    let priorities = |a: &Agent| -> Vec<u32> {
        a.get_local_candidates()
            .iter()
            .map(|c| c.priority())
            .collect()
    };
    let before = priorities(&a);
    assert_eq!(local_preference(before[0]), 65535, "IPv4-only UDP");
    assert_eq!(
        local_preference(before[1]),
        4 * 8192 + 8191,
        "IPv4-only TCP passive: direction-pref 4, other-pref 8191"
    );

    // An IPv6 candidate later: the host is dual stack now.
    assert!(
        a.add_local_candidate(host(addr("[2a01:4f8::1]:1000")))
            .unwrap()
    );
    let after = priorities(&a);
    assert_eq!(after[..2], before[..], "signalled priorities do not change");
    assert_eq!(
        local_preference(after[2]) >> 8,
        40,
        "the precedence of a global IPv6 address"
    );
    let mut unique = after.clone();
    unique.sort_unstable();
    unique.dedup();
    assert_eq!(unique.len(), after.len(), "unique priorities: {after:?}");
}

/// Section 14: an agent "MAY wait for [higher-priority] candidates before nominating", and the
/// end-of-candidates indication ends the wait. With a ten-second wait for host pairs, the
/// controlling agent does not nominate its valid pair in the first second; once both sides
/// have ended their candidates it nominates at once.
#[test]
fn test_end_of_candidates_on_both_sides_ends_the_wait_before_nominating() {
    let now = Instant::now();
    let cfg = AgentConfig {
        host_acceptance_min_wait: Some(Duration::from_secs(10)),
        ..config(true)
    };
    let mut a = started_agent(now, cfg, &[REMOTE_A]);
    let nominations = |out: &[(Message, SocketAddr)]| {
        out.iter()
            .filter(|(m, _)| m.typ == BINDING_REQUEST && m.contains(ATTR_USE_CANDIDATE))
            .count()
    };
    let second = now + Duration::from_secs(1);
    let out = run_answering(&mut a, now, second, |_, _| true);
    assert_eq!(nominations(&out), 0, "nominated within the wait");
    a.set_remote_end_of_candidates();
    a.set_local_gathering_complete();
    let out = run_answering(
        &mut a,
        second,
        second + Duration::from_millis(500),
        |_, _| true,
    );
    assert!(
        nominations(&out) > 0,
        "the wait goes on after end-of-candidates"
    );
    assert!(a.get_selected_candidate_pair().is_some());
}

/// RFC 8445 Section 6.1.4.2: "an agent MAY terminate ICE processing for a checklist at any
/// time by local policy": `close` ends the checks; nothing more is sent.
#[test]
fn test_closing_the_agent_stops_its_checks() {
    let now = Instant::now();
    let mut a = started_agent(now, config(true), &[REMOTE_A, REMOTE_B]);
    let first = run(&mut a, now, now + Duration::from_millis(60));
    assert!(!requests(&first).is_empty(), "checks before");
    a.close().unwrap();
    let _ = a.handle_timeout(now + Duration::from_secs(1));
    assert!(sent(&mut a).is_empty(), "a check after close");
    assert!(a.poll_timeout().is_none());
}

/// RFC 8839 Section 5.3: with `ice-mismatch` for its stream "ICE procedures MUST NOT be used":
/// `stop_for_ice_mismatch` ends the checks and leaves the agent `Failed`, with no candidates.
#[test]
fn test_ice_mismatch_stops_ice_for_the_stream() {
    let now = Instant::now();
    let mut a = started_agent(now, config(true), &[REMOTE_A]);
    assert!(!requests(&run(&mut a, now, now + Duration::from_millis(60))).is_empty());
    let later = now + Duration::from_millis(100);
    assert!(a.stop_for_ice_mismatch(later));
    assert!(!a.stop_for_ice_mismatch(later), "once");
    assert_eq!(a.state(), ConnectionState::Failed);
    assert!(a.get_candidate_pairs().is_empty());
    let out = run(&mut a, later, later + Duration::from_secs(5));
    assert!(requests(&out).is_empty(), "a check after ice-mismatch");
}