rtci-turn 0.5.0

Sans-I/O TURN client (RFC 8656, RFC 6062 TCP allocations) for WebRTC
Documentation
//! What the client refuses to believe: a success nothing signs when it holds a credential
//! (RFC 8489 §9.2.5, RFC 8656 §21.1.5).
use super::test_server::*;
use super::*;
use sansio::Protocol;

/// An Allocate success naming [`relayed_addr`] with a 600 s lifetime.
fn allocation() -> Vec<Box<dyn Setter>> {
    vec![relayed(relayed_addr()), lifetime(600)]
}

/// A client of [`server_addr`] over UDP without a credential.
fn client_without_credential() -> Result<Client> {
    Client::new(
        ClientConfig {
            turn_serv_addr: server_addr().to_string(),
            local_addr: local_addr(),
            transport_protocol: TransportProtocol::UDP,
            ..Default::default()
        },
        test_crypto_provider(),
    )
}

/// RFC 8489 §9.2.5: "If all the responses received are discarded, then instead of signaling a
/// timeout after ending the transaction, the layer MUST signal that the integrity protection
/// was violated." A first Allocate answered by nothing but an unsigned success, from a client
/// with a credential, is retransmitted and then fails as an integrity violation, under the id
/// `allocate` returned.
#[test]
fn test_a_first_allocate_answered_only_by_unsigned_successes_fails_as_an_integrity_violation()
-> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut client = new_client(TransportProtocol::UDP)?;
    let tid = client.allocate(now)?;
    let first = server.next_request(&mut client);
    server.answer(
        &mut client,
        now,
        &first,
        CLASS_SUCCESS_RESPONSE,
        allocation(),
        None,
    )?;
    assert!(client.poll_event().is_none());

    let (requests, events) = drive_until(&server, &mut client, now + Duration::from_secs(60))?;
    assert!(
        !requests.is_empty()
            && requests
                .iter()
                .all(|r| r.transaction_id == first.transaction_id),
        "the same Allocate is retransmitted after the discarded success: {requests:?}"
    );
    assert!(
        matches!(
            events.as_slice(),
            [Event::AllocateError(
                id,
                RequestError::Failed(Error::ErrIntegrityMismatch)
            )] if *id == tid
        ),
        "expected the integrity violation alone, got {events:?}"
    );
    assert!(client.relay(relayed_addr()).is_err());
    client.close()
}

/// RFC 8489 §9.2.5: over a reliable transport the response "MUST be discarded, and the layer
/// MUST immediately end the transaction and signal that the integrity protection was
/// violated".
#[test]
fn test_over_tcp_an_unsigned_success_to_the_first_allocate_ends_it_as_an_integrity_violation()
-> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut client = new_client(TransportProtocol::TCP)?;
    let tid = client.allocate(now)?;
    let first = server.next_request(&mut client);
    server.answer(
        &mut client,
        now,
        &first,
        CLASS_SUCCESS_RESPONSE,
        allocation(),
        None,
    )?;
    assert!(
        matches!(
            client.poll_event(),
            Some(Event::AllocateError(
                id,
                RequestError::Failed(Error::ErrIntegrityMismatch)
            )) if id == tid
        ),
        "the violation is reported at once"
    );
    assert!(!client.has_transaction(&first.transaction_id));
    assert!(client.relay(relayed_addr()).is_err());
    client.close()
}

/// RFC 8656 §7.2 step 1: a server "MAY allow an unauthenticated request". A client without a
/// credential has no key to check a response with and takes the unsigned success; a client
/// with one takes it when the application set `set_unauthenticated_allocations`.
#[test]
fn test_an_unsigned_success_to_the_first_allocate_is_an_allocation_without_a_credential_or_by_setting()
-> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut lax = new_client(TransportProtocol::UDP)?;
    lax.set_unauthenticated_allocations(true);
    for (name, mut client) in [
        ("no credential", client_without_credential()?),
        ("the setting", lax),
    ] {
        let tid = client.allocate(now)?;
        let first = server.next_request(&mut client);
        assert!(!first.contains(ATTR_MESSAGE_INTEGRITY));
        server.answer(
            &mut client,
            now,
            &first,
            CLASS_SUCCESS_RESPONSE,
            allocation(),
            None,
        )?;
        match client.poll_event() {
            Some(Event::AllocateResponse(id, addr)) => {
                assert_eq!(id, tid, "{name}");
                assert_eq!(addr, relayed_addr(), "{name}");
            }
            other => panic!("{name}: expected AllocateResponse, got {other:?}"),
        }
        assert!(client.relay(relayed_addr()).is_ok(), "{name}");
        client.close()?;
    }
    Ok(())
}

/// RFC 8656 §7.3: the relayed transport address is where peers send. An XOR-RELAYED-ADDRESS
/// with port 0, the unspecified address (with a port: the all-zero one is coturn's filler,
/// passed over), a multicast or the broadcast address is an allocation the client cannot use:
/// the caller is told under its id and the allocation is deleted with a Refresh of LIFETIME 0.
#[test]
fn test_a_relayed_address_no_peer_can_send_to_is_refused_and_the_allocation_deleted() -> Result<()>
{
    for unusable in [
        "192.0.2.15:0",
        "0.0.0.0:50000",
        "224.0.0.1:50000",
        "255.255.255.255:50000",
    ] {
        let unusable: SocketAddr = unusable.parse().unwrap();
        let now = Instant::now();
        let server = TestServer::new()?;
        let mut client = new_client(TransportProtocol::UDP)?;
        let (tid, _) = server.allocate_with(
            &mut client,
            now,
            AllocateOptions::default(),
            vec![relayed(unusable), lifetime(600)],
        )?;
        match client.poll_event() {
            Some(Event::AllocateError(id, RequestError::Failed(_))) => {
                assert_eq!(id, tid, "{unusable}")
            }
            other => panic!("{unusable}: expected AllocateError, got {other:?}"),
        }
        assert!(client.relay(unusable).is_err(), "{unusable}");
        let release = server.next_request(&mut client);
        assert_eq!(release.typ.method, METHOD_REFRESH, "{unusable}");
        let mut granted = Lifetime::default();
        granted.get_from(&release)?;
        assert_eq!(granted.0, Duration::ZERO, "{unusable}: deleted");
        client.close()?;
    }
    Ok(())
}

/// RFC 8656 §7.3: the XOR-MAPPED-ADDRESS of an Allocate success is the client's
/// server-reflexive address, for ICE. One that is no transport address (unspecified,
/// multicast, port 0) is not passed on; the allocation itself stands.
#[test]
fn test_a_mapped_address_that_is_no_transport_address_is_not_passed_on() -> Result<()> {
    for unusable in ["0.0.0.0:7000", "224.0.0.1:7000", "192.0.2.1:0"] {
        let unusable: SocketAddr = unusable.parse().unwrap();
        let now = Instant::now();
        let server = TestServer::new()?;
        let mut client = new_client(TransportProtocol::UDP)?;
        let (tid, _) = server.allocate_with(
            &mut client,
            now,
            AllocateOptions::default(),
            vec![
                relayed(relayed_addr()),
                lifetime(600),
                Box::new(XorMappedAddress {
                    ip: unusable.ip(),
                    port: unusable.port(),
                }),
            ],
        )?;
        assert!(
            matches!(client.poll_event(), Some(Event::AllocateResponse(id, _)) if id == tid),
            "{unusable}: the allocation stands"
        );
        assert_eq!(
            client.relay(relayed_addr())?.mapped_addr(),
            None,
            "{unusable} was passed on as the mapped address"
        );
        client.close()?;
    }
    // A usable one is passed on.
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut client = new_client(TransportProtocol::UDP)?;
    let mapped: SocketAddr = "192.0.2.1:7000".parse().unwrap();
    server.allocate_with(
        &mut client,
        now,
        AllocateOptions::default(),
        vec![
            relayed(relayed_addr()),
            lifetime(600),
            Box::new(XorMappedAddress {
                ip: mapped.ip(),
                port: mapped.port(),
            }),
        ],
    )?;
    assert_eq!(client.relay(relayed_addr())?.mapped_addr(), Some(mapped));
    client.close()
}

/// RFC 8489 §14.2: XOR-MAPPED-ADDRESS is the address the server saw the request come from. A
/// Binding success naming port 0, the unspecified or a multicast address is a Binding error,
/// not a server-reflexive address.
#[test]
fn test_a_binding_success_without_a_transport_address_is_an_error() -> Result<()> {
    for unusable in ["0.0.0.0:7000", "[::]:7000", "224.0.0.1:7000", "192.0.2.1:0"] {
        let unusable: SocketAddr = unusable.parse().unwrap();
        let now = Instant::now();
        let server = TestServer::new()?;
        let mut client = new_client(TransportProtocol::UDP)?;
        let tid = client.send_binding_request_to(now, server_addr())?;
        let request = server.next_request(&mut client);
        server.answer(
            &mut client,
            now,
            &request,
            CLASS_SUCCESS_RESPONSE,
            vec![Box::new(XorMappedAddress {
                ip: unusable.ip(),
                port: unusable.port(),
            })],
            None,
        )?;
        assert!(
            matches!(client.poll_event(), Some(Event::BindingError(id, _)) if id == tid),
            "{unusable} was taken for a server-reflexive address"
        );
        client.close()?;
    }
    Ok(())
}

/// RFC 8489 §6.3 with RFC 8656 §21.1.5: only the server the request went to answers it. A
/// signed Allocate success with the right transaction id from any other address is discarded
/// and the transaction goes on; the server's own answer is then taken.
#[test]
fn test_a_response_from_an_address_other_than_the_servers_is_discarded() -> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut client = new_client(TransportProtocol::UDP)?;
    let (tid, _, authenticated) =
        server.begin_allocate(&mut client, now, AllocateOptions::default())?;
    let success = server.reply(
        &authenticated,
        CLASS_SUCCESS_RESPONSE,
        allocation(),
        Some(&server.key),
    )?;
    let deliver = |client: &mut Client, from: SocketAddr| {
        client.handle_read(TransportMessage {
            now,
            transport: TransportContext {
                local_addr: local_addr(),
                peer_addr: from,
                transport_protocol: TransportProtocol::UDP,
                ecn: None,
            },
            message: BytesMut::from(&success[..]),
        })
    };
    let elsewhere: SocketAddr = "198.51.100.9:3478".parse().unwrap();
    deliver(&mut client, elsewhere)?;
    let other_port = SocketAddr::new(server_addr().ip(), server_addr().port() + 1);
    deliver(&mut client, other_port)?;
    assert!(client.poll_event().is_none(), "a stray response was taken");
    assert!(client.relay(relayed_addr()).is_err());
    assert!(client.has_transaction(&authenticated.transaction_id));

    deliver(&mut client, server_addr())?;
    assert!(
        matches!(client.poll_event(), Some(Event::AllocateResponse(id, addr))
            if id == tid && addr == relayed_addr()),
        "the server's own answer is taken"
    );
    client.close()
}