rtci-turn 0.5.0

Sans-I/O TURN client (RFC 8656, RFC 6062 TCP allocations) for WebRTC
Documentation
//! RFC 8489 ยง9.2.3.2: once a request to a server has succeeded, the client "SHOULD cache the
//! username, password, realm, and nonce for subsequent communications with the server", and a
//! subsequent request carries them. A later client to the same server with the same login
//! starts its Allocate with the credential an earlier allocation was granted with
//! ([`Client::cached_credential`], [`Client::use_cached_credential`]): no 401 round trip. A 438
//! to it is answered with the new nonce; a 401 to it authenticates anew, as after a first
//! request; the cache is never taken by a client of another server or login.
use super::test_server::*;
use super::*;
use sansio::Protocol;

fn allocate_success(
    server: &TestServer,
    client: &mut Client,
    now: Instant,
    request: &Message,
) -> Result<()> {
    server.answer(
        client,
        now,
        request,
        CLASS_SUCCESS_RESPONSE,
        vec![
            Box::new(RelayedAddress {
                ip: relayed_addr().ip(),
                port: relayed_addr().port(),
            }),
            Box::new(Lifetime(Duration::from_secs(600))),
        ],
        Some(&server.key),
    )
}

fn unauthorized(
    server: &TestServer,
    client: &mut Client,
    now: Instant,
    request: &Message,
    nonce: &str,
) -> Result<()> {
    server.answer(
        client,
        now,
        request,
        CLASS_ERROR_RESPONSE,
        vec![
            Box::new(ErrorCodeAttribute {
                code: stun::error_code::CODE_UNAUTHORIZED,
                reason: b"Unauthorized".to_vec(),
            }),
            Box::new(Nonce::new(ATTR_NONCE, nonce.to_owned())),
            Box::new(Realm::new(ATTR_REALM, REALM.to_owned())),
        ],
        None,
    )
}

fn allocated(client: &mut Client) -> Option<RelayedAddr> {
    std::iter::from_fn(|| client.poll_event()).find_map(|e| match e {
        Event::AllocateResponse(_, addr) => Some(addr),
        _ => None,
    })
}

/// A client whose allocation succeeded caches what it was granted with; a second client to the
/// same server with the same login sends its first Allocate signed, with the cached realm and
/// nonce, and the allocation is made in one round trip.
#[test]
fn a_later_allocate_to_the_same_server_starts_with_the_cached_realm_and_nonce() -> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut first = new_client(TransportProtocol::UDP)?;
    assert!(
        first.cached_credential().is_none(),
        "nothing before a success"
    );
    server.allocate(&mut first, now)?;
    let cached = first
        .cached_credential()
        .expect("the credential the server accepted");
    assert_eq!(cached.server(), server_addr());

    let mut second = new_client(TransportProtocol::UDP)?;
    assert!(second.use_cached_credential(&cached));
    second.allocate(now)?;
    let mut request = server.next_request(&mut second);
    assert_eq!(request.typ.method, METHOD_ALLOCATE);
    assert_eq!(nonce_of(&request), "nonce", "the cached nonce");
    MessageIntegrity::check(&mut request, &server.key, test_crypto_provider().crypto())?;
    allocate_success(&server, &mut second, now, &request)?;
    assert_eq!(
        allocated(&mut second),
        Some(relayed_addr()),
        "one round trip"
    );
    assert!(server.requests(&mut second).is_empty());
    Ok(())
}

/// Without the cache the first Allocate carries no credential (RFC 8489 ยง9.2.3.1).
#[test]
fn without_the_cache_the_first_allocate_carries_no_credential() -> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut client = new_client(TransportProtocol::UDP)?;
    client.allocate(now)?;
    let request = server.next_request(&mut client);
    assert!(!request.contains(ATTR_MESSAGE_INTEGRITY));
    assert!(!request.contains(ATTR_NONCE));
    Ok(())
}

/// RFC 8489 ยง9.2.5: a 438 (Stale Nonce) to the Allocate that carried the cached nonce is
/// answered with the new nonce, and the allocation is made.
#[test]
fn a_stale_cached_nonce_is_replaced_by_the_438s() -> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut first = new_client(TransportProtocol::UDP)?;
    server.allocate(&mut first, now)?;
    let cached = first.cached_credential().expect("cached");
    let mut second = new_client(TransportProtocol::UDP)?;
    assert!(second.use_cached_credential(&cached));
    second.allocate(now)?;
    let request = server.next_request(&mut second);
    server.stale_nonce(&mut second, now, &request, "fresh", REALM)?;
    let mut retry = server.next_request(&mut second);
    assert_eq!(nonce_of(&retry), "fresh");
    MessageIntegrity::check(&mut retry, &server.key, test_crypto_provider().crypto())?;
    allocate_success(&server, &mut second, now, &retry)?;
    assert_eq!(allocated(&mut second), Some(relayed_addr()));
    let renewed = second.cached_credential().expect("cached again");
    let mut third = new_client(TransportProtocol::UDP)?;
    assert!(third.use_cached_credential(&renewed));
    third.allocate(now)?;
    assert_eq!(
        nonce_of(&server.next_request(&mut third)),
        "fresh",
        "the latest nonce is the one cached"
    );
    Ok(())
}

/// A 401 to the Allocate that carried the cached credential (the server lost its state, say)
/// is not taken for a refusal of the credential: the request is made again from the 401, as
/// after a first request, and the allocation is made.
#[test]
fn a_401_to_the_cached_credential_authenticates_anew() -> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut first = new_client(TransportProtocol::UDP)?;
    server.allocate(&mut first, now)?;
    let cached = first.cached_credential().expect("cached");
    let mut second = new_client(TransportProtocol::UDP)?;
    assert!(second.use_cached_credential(&cached));
    second.allocate(now)?;
    let request = server.next_request(&mut second);
    unauthorized(&server, &mut second, now, &request, "other")?;
    let mut retry = server.next_request(&mut second);
    assert_eq!(nonce_of(&retry), "other");
    MessageIntegrity::check(&mut retry, &server.key, test_crypto_provider().crypto())?;
    allocate_success(&server, &mut second, now, &retry)?;
    assert_eq!(allocated(&mut second), Some(relayed_addr()));
    Ok(())
}

/// The cache is never used across servers or logins: a client of another server address, or
/// with another user name or password, does not take it, and its first Allocate goes without
/// a credential.
#[test]
fn the_cache_is_not_taken_by_another_server_or_login() -> Result<()> {
    let now = Instant::now();
    let server = TestServer::new()?;
    let mut first = new_client(TransportProtocol::UDP)?;
    server.allocate(&mut first, now)?;
    let cached = first.cached_credential().expect("cached");
    let other = |turn: &str, user: &str, pass: &str| {
        Client::new(
            ClientConfig {
                turn_serv_addr: turn.to_owned(),
                local_addr: local_addr(),
                transport_protocol: TransportProtocol::UDP,
                username: user.to_owned(),
                password: pass.to_owned(),
                ..Default::default()
            },
            test_crypto_provider(),
        )
    };
    for (turn, user, pass) in [
        ("127.0.0.1:3479", USERNAME, PASSWORD),
        ("127.0.0.1:3478", "someone-else", PASSWORD),
        ("127.0.0.1:3478", USERNAME, "another-password"),
    ] {
        let mut client = other(turn, user, pass)?;
        assert!(
            !client.use_cached_credential(&cached),
            "{turn} {user} {pass}"
        );
        client.allocate(now)?;
        let request = server.next_request(&mut client);
        assert!(
            !request.contains(ATTR_MESSAGE_INTEGRITY),
            "{turn} {user} {pass}: a first request"
        );
    }
    Ok(())
}