rtci-ice 0.5.0

Sans-I/O ICE agent (RFC 8445) with trickle ICE, ICE-TCP and consent freshness, for WebRTC
Documentation
//! An ICE restart into the "relay" ICE transport policy (`set_candidate_types` with relayed
//! candidates only), read from what the agent puts on the wire in virtual time.
//!
//! W3C webrtc-pc `RTCIceTransportPolicy` "relay": "The ICE Agent uses only media relay
//! candidates such as candidates passing through a TURN server". "Set the configuration": "if
//! the new ICE transports setting changes the existing setting, no action will be taken until
//! the next gathering phase. If a script wants this to happen immediately, it should do an ICE
//! restart". RFC 8445 Section 9 lets data "continue to be sent using existing data sessions"
//! during a restart: a permission, which a path the policy now rules out does not get.

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

use sansio::Protocol;

use super::agent_rfc8445_test::*;
use super::*;
use crate::candidate::candidate_relay::CandidateRelayConfig;

/// The relayed transport address the TURN server allocated (what the agent's relayed
/// candidate is, and the base its packets leave from).
const RELAY: &str = "203.0.113.9:6000";
/// The server-reflexive address the allocation was made from (the relayed candidate's related
/// address).
const MAPPED: &str = "198.51.100.7:4000";

fn relay(at: &str) -> Candidate {
    let at = addr(at);
    let mapped = addr(MAPPED);
    CandidateRelayConfig {
        base_config: CandidateConfig {
            network: "udp".to_owned(),
            address: at.ip().to_string(),
            port: at.port(),
            component: 1,
            ..Default::default()
        },
        rel_addr: mapped.ip().to_string(),
        rel_port: mapped.port(),
        url: None,
    }
    .new_candidate_relay()
    .unwrap()
}

/// One datagram the agent wrote: its local address (the socket or relayed address it leaves
/// from), its destination, and the STUN message.
struct Out {
    local: SocketAddr,
    to: SocketAddr,
    message: Message,
}

/// Runs the agent's timer from `from` to `until`, as a peer that answers every Binding request
/// with a success response (signed with the peer's password, mapped address `mapped` or, by
/// default, the request's source), received on the address the request left from. Returns
/// everything the agent wrote.
fn run_peer(a: &mut Agent, from: Instant, until: Instant, mapped: Option<SocketAddr>) -> Vec<Out> {
    let mut out = vec![];
    let mut now = from;
    loop {
        a.handle_timeout(now).unwrap();
        loop {
            let mut batch = vec![];
            while let Some(t) = a.poll_write() {
                let mut m = Message {
                    raw: t.message.to_vec(),
                    ..Message::default()
                };
                m.decode().unwrap();
                batch.push(Out {
                    local: t.transport.local_addr,
                    to: t.transport.peer_addr,
                    message: m,
                });
            }
            if batch.is_empty() {
                break;
            }
            for o in &batch {
                if o.message.typ != BINDING_REQUEST {
                    continue;
                }
                let response = peer_response(
                    BINDING_SUCCESS,
                    o.message.transaction_id,
                    mapped.unwrap_or(o.local),
                    None,
                );
                let _ = a.handle_read(TaggedBytesMut {
                    now,
                    transport: TransportContext {
                        local_addr: o.local,
                        peer_addr: o.to,
                        ecn: None,
                        transport_protocol: TransportProtocol::UDP,
                    },
                    message: BytesMut::from(&response.raw[..]),
                });
            }
            out.extend(batch);
        }
        match a.poll_timeout() {
            Some(next) if next <= until => now = next.max(now + Duration::from_micros(1)),
            _ => return out,
        }
    }
}

fn states(a: &mut Agent) -> Vec<ConnectionState> {
    let mut states = vec![];
    while let Some(e) = a.poll_event() {
        if let Event::ConnectionStateChange(s) = e.event {
            states.push(s);
        }
    }
    states
}

fn selected_local_type(a: &Agent) -> Option<CandidateType> {
    a.get_selected_candidate_pair()
        .map(|(local, _)| local.candidate_type())
}

fn from_peer(local: &str) -> TransportContext {
    TransportContext {
        local_addr: addr(local),
        peer_addr: addr(REMOTE_A),
        ecn: None,
        transport_protocol: TransportProtocol::UDP,
    }
}

/// A controlling agent with the default candidate types, a host candidate (`LOCAL`) and a
/// relayed one (`RELAY`), connected to the peer's host candidate over the host pair (the
/// highest priority). Returns it with the instant it is at.
fn connected_over_host() -> (Agent, Instant) {
    let start = Instant::now();
    let mut a = bare_agent(start, config(true));
    assert!(a.add_local_candidate(relay(RELAY)).unwrap());
    a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
    a.start_connectivity_checks(start, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
        .unwrap();
    let now = start + Duration::from_secs(2);
    run_peer(&mut a, start, now, None);
    assert_eq!(a.state(), ConnectionState::Connected);
    assert_eq!(
        selected_local_type(&a),
        Some(CandidateType::Host),
        "the precondition: the host pair is selected"
    );
    assert_eq!(
        a.media_path().map(|p| p.local_addr),
        Some(addr(LOCAL)),
        "the precondition: data runs on the host pair"
    );
    assert!(a.accepts_data(from_peer(LOCAL)));
    states(&mut a);
    (a, now)
}

/// The peer's description of the new generation: its credentials and its host candidate.
fn new_generation_from_peer(a: &mut Agent) {
    a.set_remote_credentials(REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
        .unwrap();
    a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
}

/// After `set_candidate_types([Relay])` and an ICE restart, nothing leaves on the host pair:
/// no data path (`media_path`), no consent request of the old generation, no check of the new
/// one (the host candidate is not the new generation's); data on it is not taken; the agent is
/// checking until the relayed pair is selected, then connected over it.
#[test]
fn test_a_restart_into_the_relay_policy_does_not_keep_a_host_path() {
    for keep_local_candidates in [true, false] {
        let (mut a, now) = connected_over_host();

        a.set_candidate_types(vec![CandidateType::Relay]);
        a.restart(now, String::new(), String::new(), keep_local_candidates)
            .unwrap();
        assert_eq!(
            a.media_path(),
            None,
            "keep={keep_local_candidates}: the host path is not kept across the restart"
        );
        assert!(!a.accepts_data(from_peer(LOCAL)));
        assert_eq!(a.state(), ConnectionState::Checking);
        assert_eq!(states(&mut a), vec![ConnectionState::Checking]);
        assert!(
            a.local_candidates
                .iter()
                .all(|c| c.candidate_type() == CandidateType::Relay),
            "keep={keep_local_candidates}: the new generation has relayed candidates only"
        );

        // The peer's description is slow to arrive: nothing goes out on the host pair
        // meanwhile (before the change, the old generation's consent checks did, every 4 to 6
        // seconds, and data with them).
        let waiting = run_peer(&mut a, now, now + Duration::from_secs(10), None);
        assert!(
            waiting.iter().all(|o| o.local != addr(LOCAL)),
            "keep={keep_local_candidates}: {} datagrams left on the host base while waiting",
            waiting.iter().filter(|o| o.local == addr(LOCAL)).count()
        );
        assert_eq!(a.media_path(), None);

        // The new generation: only the relayed candidate is kept (with `keep`), so it alone
        // is paired and selected.
        if !keep_local_candidates {
            assert!(a.add_local_candidate(relay(RELAY)).unwrap());
        }
        assert!(
            !a.add_local_candidate(host(addr(LOCAL))).unwrap(),
            "a host candidate is refused under the relay policy"
        );
        new_generation_from_peer(&mut a);
        let t = now + Duration::from_secs(10);
        let after = run_peer(&mut a, t, t + Duration::from_secs(5), None);
        assert!(
            after.iter().all(|o| o.local != addr(LOCAL)),
            "keep={keep_local_candidates}: nothing leaves on the host base after the restart"
        );
        assert!(
            after.iter().any(|o| o.local == addr(RELAY)),
            "the precondition: the relayed pair was checked"
        );
        assert_eq!(a.state(), ConnectionState::Connected);
        assert_eq!(selected_local_type(&a), Some(CandidateType::Relay));
        assert_eq!(a.media_path().map(|p| p.local_addr), Some(addr(RELAY)));
        assert_eq!(a.retired_media_path(), None, "nor is the host path retired");
        assert!(!a.accepts_data(from_peer(LOCAL)));
        assert!(a.accepts_data(from_peer(RELAY)));
        assert_eq!(states(&mut a), vec![ConnectionState::Connected]);
    }
}

/// The path a first restart kept (the candidate types then allowed it) is not kept by a second
/// restart, made before the first selected a pair, under candidate types that rule it out.
#[test]
fn test_a_second_restart_into_the_relay_policy_drops_the_path_the_first_kept() {
    let (mut a, now) = connected_over_host();
    a.restart(now, String::new(), String::new(), true).unwrap();
    assert_eq!(
        a.media_path().map(|p| p.local_addr),
        Some(addr(LOCAL)),
        "the precondition: the first restart keeps the host path (RFC 8445 Section 9)"
    );
    assert_eq!(a.state(), ConnectionState::Connected);

    a.set_candidate_types(vec![CandidateType::Relay]);
    a.restart(now, String::new(), String::new(), true).unwrap();
    assert_eq!(a.media_path(), None);
    assert_eq!(a.state(), ConnectionState::Checking);
    let out = run_peer(&mut a, now, now + Duration::from_secs(10), None);
    assert!(out.iter().all(|o| o.local != addr(LOCAL)));
}

/// `set_candidate_types` alone, without a restart, changes nothing in the session (W3C "set
/// the configuration": "no action will be taken until the next gathering phase"): the host
/// pair stays selected, data and consent go on on it, and the host candidate stays.
#[test]
fn test_a_new_candidate_policy_without_a_restart_keeps_the_pair_in_use() {
    let (mut a, now) = connected_over_host();
    a.set_candidate_types(vec![CandidateType::Relay]);
    let out = run_peer(&mut a, now, now + Duration::from_secs(20), None);
    assert_eq!(a.state(), ConnectionState::Connected);
    assert_eq!(selected_local_type(&a), Some(CandidateType::Host));
    assert_eq!(a.media_path().map(|p| p.local_addr), Some(addr(LOCAL)));
    assert!(a.accepts_data(from_peer(LOCAL)));
    assert!(
        out.iter()
            .filter(|o| o.local == addr(LOCAL) && o.message.typ == BINDING_REQUEST)
            .count()
            >= 3,
        "consent checks go on on the host pair"
    );
    assert!(
        a.local_candidates
            .iter()
            .any(|c| c.candidate_type() == CandidateType::Host)
    );
}

/// A restart under candidate types that still allow the path keeps it (RFC 8445 Section 9),
/// whether they changed or not.
#[test]
fn test_a_restart_keeps_a_path_the_candidate_types_still_allow() {
    for types in [
        vec![],
        vec![CandidateType::Host, CandidateType::Relay],
        vec![CandidateType::Host],
    ] {
        let (mut a, now) = connected_over_host();
        a.set_candidate_types(types.clone());
        a.restart(now, String::new(), String::new(), true).unwrap();
        assert_eq!(
            a.media_path().map(|p| p.local_addr),
            Some(addr(LOCAL)),
            "{types:?}"
        );
        assert_eq!(a.state(), ConnectionState::Connected, "{types:?}");
        assert!(a.accepts_data(from_peer(LOCAL)), "{types:?}");
    }
}

/// Under the relay policy, a relayed path whose local candidate the agent learned from a
/// response's mapped address (peer-reflexive, its base the relayed candidate's) is a relayed
/// path: the restart keeps it.
#[test]
fn test_a_relayed_path_through_a_learned_candidate_is_kept_across_the_restart() {
    let start = Instant::now();
    let mut a = Agent::new(
        start,
        Arc::new(AgentConfig {
            candidate_types: vec![CandidateType::Relay],
            ..config(true)
        }),
        provider(),
    )
    .unwrap();
    assert!(a.add_local_candidate(relay(RELAY)).unwrap());
    a.add_remote_candidate(host(addr(REMOTE_A))).unwrap();
    a.start_connectivity_checks(start, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
        .unwrap();
    // Past the relayed and peer-reflexive acceptance waits (2 s and 1 s by default, RFC 8838
    // Section 14: a nomination waits strictly longer than them), so the pair is nominated.
    let now = start + Duration::from_secs(5);
    // The peer sees the relayed packets from another address than the relayed candidate's.
    run_peer(&mut a, start, now, Some(addr("198.51.100.99:7777")));
    assert_eq!(
        a.state(),
        ConnectionState::Connected,
        "the precondition: connected before the restart"
    );
    assert_eq!(
        selected_local_type(&a),
        Some(CandidateType::PeerReflexive),
        "the precondition: the selected pair's local candidate is a learned one"
    );
    assert_eq!(a.media_path().map(|p| p.local_addr), Some(addr(RELAY)));

    a.restart(now, String::new(), String::new(), true).unwrap();
    assert_eq!(
        a.media_path().map(|p| p.local_addr),
        Some(addr(RELAY)),
        "a relayed path is kept across the restart"
    );
    assert_eq!(a.state(), ConnectionState::Connected);
}