rsipstack 0.8.5

SIP Stack Rust library for building SIP applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! A UAC INVITE challenged with 401/407 (RFC 3261 §22.2 / §22.3).
//!
//! With a credential configured the UAC retries once with Authorization /
//! Proxy-Authorization. Without one it cannot retry, so the challenge is the
//! final response and must be returned to the caller, not dropped.
use crate::dialog::{
    authenticate::Credential,
    client_dialog::ClientInviteDialog,
    dialog::{DialogState, TerminatedReason},
    dialog_layer::DialogLayer,
    invitation::InviteOption,
};
use crate::sip::{headers::*, Header, HeadersExt, Method, Response, StatusCode, Uri};
use crate::transaction::TransactionReceiver;
use crate::transport::{udp::UdpConnection, TransportLayer};
use crate::EndpointBuilder;
use std::time::Duration;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver};
use tokio_util::sync::CancellationToken;

/// Upper bound for the INVITE to complete; well below Timer B/D (32 s), so a
/// response held until the transaction times out fails the test too.
const PROMPT: Duration = Duration::from_secs(5);

const CHALLENGE: &str =
    r#"Digest realm="example.com", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", algorithm=MD5"#;

struct Peers {
    token: CancellationToken,
    uac_layer: DialogLayer,
    uas_port: u16,
    uac_port: u16,
}

async fn udp_endpoint(
    token: &CancellationToken,
    ua: &str,
) -> crate::Result<(crate::transaction::endpoint::Endpoint, u16)> {
    let tl = TransportLayer::new(token.child_token());
    let udp = UdpConnection::create_connection(
        "127.0.0.1:0".parse().unwrap(),
        None,
        Some(token.child_token()),
    )
    .await?;
    let port = udp.get_addr().addr.port.map(u16::from).unwrap_or(0);
    tl.add_transport(udp.into());
    let endpoint = EndpointBuilder::new()
        .with_user_agent(ua)
        .with_transport_layer(tl)
        .with_cancel_token(token.child_token())
        .build();
    let inner = endpoint.inner.clone();
    tokio::spawn(async move {
        let _ = inner.serve().await;
    });
    Ok((endpoint, port))
}

/// Returns the peers and the UAS's incoming transactions.
async fn peers() -> crate::Result<(Peers, TransactionReceiver)> {
    let token = CancellationToken::new();
    let (uas, uas_port) = udp_endpoint(&token, "rsipstack-uas").await?;
    let (uac, uac_port) = udp_endpoint(&token, "rsipstack-uac").await?;
    let uas_incoming = uas.incoming_transactions()?;
    let peers = Peers {
        token,
        uac_layer: DialogLayer::new(uac.inner.clone()),
        uas_port,
        uac_port,
    };
    Ok((peers, uas_incoming))
}

fn invite_option(p: &Peers, credential: Option<Credential>) -> InviteOption {
    InviteOption {
        caller: Uri::try_from("sip:alice@example.com").unwrap(),
        callee: Uri::try_from(format!("sip:bob@127.0.0.1:{};transport=udp", p.uas_port)).unwrap(),
        contact: Uri::try_from(format!("sip:alice@127.0.0.1:{}", p.uac_port)).unwrap(),
        credential,
        ..Default::default()
    }
}

fn challenge_header(status: &StatusCode) -> Header {
    match status {
        StatusCode::ProxyAuthenticationRequired => ProxyAuthenticate::new(CHALLENGE).into(),
        _ => WwwAuthenticate::new(CHALLENGE).into(),
    }
}

/// Whether the INVITE answers a `status` challenge with the matching header:
/// Authorization for 401 (§22.3), Proxy-Authorization for 407 (§22.3).
fn answers_challenge(status: &StatusCode, headers: &Headers) -> bool {
    headers.iter().any(|h| match status {
        StatusCode::ProxyAuthenticationRequired => matches!(h, Header::ProxyAuthorization(_)),
        _ => matches!(h, Header::Authorization(_)),
    })
}

/// UAS: challenge every INVITE with `status`, except that one answering the
/// challenge gets 200 OK when `accept_credentials`. Reports, per INVITE,
/// whether it answered the challenge.
fn spawn_uas(
    mut incoming: TransactionReceiver,
    status: StatusCode,
    uas_port: u16,
    accept_credentials: bool,
) -> UnboundedReceiver<bool> {
    let (seen_tx, seen_rx) = unbounded_channel();
    tokio::spawn(async move {
        while let Some(mut tx) = incoming.recv().await {
            if tx.original.method != Method::Invite {
                continue;
            }
            let authed = answers_challenge(&status, &tx.original.headers);
            let _ = seen_tx.send(authed);
            let status = status.clone();
            tokio::spawn(async move {
                if authed && accept_credentials {
                    let contact = Contact::new(format!("<sip:bob@127.0.0.1:{}>", uas_port));
                    tx.reply_with(StatusCode::OK, vec![contact.into()], None)
                        .await
                        .expect("reply 200");
                } else {
                    tx.reply_with(status.clone(), vec![challenge_header(&status)], None)
                        .await
                        .expect("reply challenge");
                }
                // Keep the server transaction alive to absorb the ACK.
                while tx.receive().await.is_some() {}
            });
        }
    });
    seen_rx
}

/// No further INVITE reaches the UAS. Any retry is sent before the INVITE
/// completes, so on loopback it would arrive well within this window.
async fn assert_no_more_invites(seen: &mut UnboundedReceiver<bool>) {
    let next = tokio::time::timeout(Duration::from_millis(300), seen.recv()).await;
    assert!(next.is_err(), "unexpected further INVITE: {next:?}");
}

fn credential() -> Credential {
    Credential {
        username: "alice".to_string(),
        password: "secret".to_string(),
        realm: None,
        auth_username: None,
    }
}

/// An authentication failure for one in-dialog request must leave the
/// established session intact and return that request's final response.
async fn assert_in_dialog_auth(
    status: StatusCode,
    with_credential: bool,
    accept_credentials: bool,
) -> crate::Result<()> {
    for method in [
        Method::Invite,
        Method::Update,
        Method::Info,
        Method::Options,
    ] {
        let (p, mut incoming) = peers().await?;
        let (seen_tx, mut seen) = unbounded_channel();
        let challenged = status.clone();
        let port = p.uas_port;
        let server_method = method.clone();
        tokio::spawn(async move {
            while let Some(mut tx) = incoming.recv().await {
                let initial = tx.original.to_header().unwrap().tag().unwrap().is_none();
                let authed = answers_challenge(&challenged, &tx.original.headers);
                let is_test_request = !initial && tx.original.method == server_method;
                let requires_auth = is_test_request || tx.original.method == Method::Bye;
                if is_test_request {
                    seen_tx.send(authed).unwrap();
                }
                let status = challenged.clone();
                tokio::spawn(async move {
                    if requires_auth && !(authed && accept_credentials) {
                        tx.reply_with(status.clone(), vec![challenge_header(&status)], None)
                            .await
                            .unwrap();
                    } else {
                        tx.reply_with(
                            StatusCode::OK,
                            vec![Contact::new(format!("<sip:bob@127.0.0.1:{port}>")).into()],
                            None,
                        )
                        .await
                        .unwrap();
                    }
                    while tx.receive().await.is_some() {}
                });
            }
        });
        let (states, mut events) = unbounded_channel();
        let (dialog, response) = tokio::time::timeout(
            PROMPT,
            p.uac_layer
                .do_invite(invite_option(&p, with_credential.then(credential)), states),
        )
        .await
        .expect("initial INVITE did not complete")?;
        assert_eq!(response.unwrap().status_code, StatusCode::OK);
        while events.try_recv().is_ok() {}
        let before = dialog.snapshot();

        let response = tokio::time::timeout(PROMPT, async {
            match method {
                Method::Invite => dialog.reinvite(None, None).await,
                Method::Update => dialog.update(None, None).await,
                Method::Info => dialog.info(None, None).await,
                Method::Options => dialog.options(None).await,
                _ => unreachable!(),
            }
        })
        .await
        .expect("in-dialog auth result must return promptly")?
        .expect("the final response must be returned");
        let expected = if with_credential && accept_credentials {
            StatusCode::OK
        } else {
            status.clone()
        };
        assert_eq!(response.status_code, expected, "{method}");
        assert!(dialog.state().is_confirmed(), "{method} ended the call");
        let after = dialog.snapshot();
        assert_eq!(after.id, before.id);
        assert_eq!(after.remote_uri, before.remote_uri);
        assert!(!seen.try_recv().unwrap());
        if with_credential {
            assert!(seen.try_recv().unwrap());
        }
        assert!(seen.try_recv().is_err(), "unexpected extra auth retry");
        while let Ok(event) = events.try_recv() {
            assert!(!matches!(event, DialogState::Terminated(..)));
        }
        // A failed modification must still permit call teardown, including
        // when BYE itself receives a final authentication failure.
        tokio::time::timeout(PROMPT, dialog.bye())
            .await
            .expect("BYE did not complete")?;
        assert!(dialog.state().is_terminated());
        p.token.cancel();
    }
    Ok(())
}

#[tokio::test]
async fn in_dialog_auth_without_credentials_preserves_session() -> crate::Result<()> {
    for status in [
        StatusCode::Unauthorized,
        StatusCode::ProxyAuthenticationRequired,
    ] {
        assert_in_dialog_auth(status, false, false).await?;
    }
    Ok(())
}

#[tokio::test]
async fn in_dialog_auth_rejected_credentials_preserves_session() -> crate::Result<()> {
    for status in [
        StatusCode::Unauthorized,
        StatusCode::ProxyAuthenticationRequired,
    ] {
        assert_in_dialog_auth(status, true, false).await?;
    }
    Ok(())
}

#[tokio::test]
async fn in_dialog_auth_successful_retry_preserves_session() -> crate::Result<()> {
    for status in [
        StatusCode::Unauthorized,
        StatusCode::ProxyAuthenticationRequired,
    ] {
        assert_in_dialog_auth(status, true, true).await?;
    }
    Ok(())
}

fn is_auth_terminated(state: &DialogState) -> bool {
    matches!(
        state,
        DialogState::Terminated(_, TerminatedReason::ProxyAuthRequired)
    )
}

async fn assert_challenge_returned_without_credential(status: StatusCode) -> crate::Result<()> {
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_uas(uas_incoming, status.clone(), p.uas_port, true);
    let (state_tx, mut state_rx) = unbounded_channel();

    let opt = invite_option(&p, None);
    let (dialog, resp) = tokio::time::timeout(PROMPT, p.uac_layer.do_invite(opt, state_tx))
        .await
        .unwrap_or_else(|_| panic!("do_invite did not return the {status} challenge promptly"))?;

    let resp = resp.unwrap_or_else(|| panic!("the {status} challenge must be the final response"));
    assert_eq!(resp.status_code, status);
    assert!(is_auth_terminated(&dialog.state()));
    let mut terminated = false;
    while let Ok(state) = state_rx.try_recv() {
        terminated |= is_auth_terminated(&state);
    }
    assert!(terminated, "ProxyAuthRequired termination must be emitted");
    assert_eq!(seen.recv().await, Some(false));
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

#[tokio::test]
async fn test_invite_401_without_credential_is_final_response() -> crate::Result<()> {
    assert_challenge_returned_without_credential(StatusCode::Unauthorized).await
}

#[tokio::test]
async fn test_invite_407_without_credential_is_final_response() -> crate::Result<()> {
    assert_challenge_returned_without_credential(StatusCode::ProxyAuthenticationRequired).await
}

/// The deprecated `ClientInviteDialog::process_invite` has the same contract.
#[tokio::test]
async fn test_legacy_client_dialog_401_without_credential_is_final_response() -> crate::Result<()> {
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_uas(uas_incoming, StatusCode::Unauthorized, p.uas_port, true);
    let (state_tx, _state_rx) = unbounded_channel();
    let opt = invite_option(&p, None);
    let (dialog, mut tx) = p.uac_layer.create_client_invite_dialog(opt, state_tx)?;
    let legacy = ClientInviteDialog::try_from(dialog)?;

    let (_, resp) = tokio::time::timeout(PROMPT, legacy.process_invite(&mut tx))
        .await
        .expect("process_invite did not return the 401 promptly")?;

    let resp = resp.expect("the 401 must be the final response");
    assert_eq!(resp.status_code, StatusCode::Unauthorized);
    assert!(is_auth_terminated(&legacy.state()));
    assert_eq!(seen.recv().await, Some(false));
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

/// With a credential the challenge is still answered by one authenticated
/// retry, and the retry's response is what the caller gets.
async fn assert_challenge_retried_with_credential(status: StatusCode) -> crate::Result<()> {
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_uas(uas_incoming, status.clone(), p.uas_port, true);
    let (state_tx, _state_rx) = unbounded_channel();
    let opt = invite_option(&p, Some(credential()));

    let (dialog, resp) = tokio::time::timeout(PROMPT, p.uac_layer.do_invite(opt, state_tx))
        .await
        .expect("authenticated INVITE did not complete")?;

    let resp: Response = resp.expect("final response after the authenticated retry");
    assert_eq!(resp.status_code, StatusCode::OK);
    assert!(dialog.inner.is_confirmed());
    assert_eq!(
        seen.recv().await,
        Some(false),
        "first INVITE is unauthenticated"
    );
    assert_eq!(seen.recv().await, Some(true), "retry answers the challenge");
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

#[tokio::test]
async fn test_invite_401_with_credential_retries() -> crate::Result<()> {
    assert_challenge_retried_with_credential(StatusCode::Unauthorized).await
}

#[tokio::test]
async fn test_invite_407_with_credential_retries() -> crate::Result<()> {
    assert_challenge_retried_with_credential(StatusCode::ProxyAuthenticationRequired).await
}

/// A qop-bearing challenge — quoted, unquoted, or a multi-option list
/// (RFC 2617 §3.2.2) — must be answered by one retry whose Authorization
/// carries the RFC 3261 §25.1 token form `qop=auth` (never `qop="auth"`)
/// and whose digest the server can verify.
#[tokio::test]
async fn test_invite_qop_challenge_retries_with_verifiable_credentials() -> crate::Result<()> {
    use crate::dialog::authenticate::verify_digest;

    for challenge_qop in [r#"qop="auth""#, r#"qop="auth,auth-int""#, "qop=auth"] {
        let (p, mut incoming) = peers().await?;
        let (seen_tx, mut seen) = unbounded_channel();
        let challenge = format!(
            r#"Digest realm="example.com", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", algorithm=MD5, {}"#,
            challenge_qop
        );
        let port = p.uas_port;
        tokio::spawn(async move {
            while let Some(mut tx) = incoming.recv().await {
                if tx.original.method != Method::Invite {
                    continue;
                }
                let raw = tx.original.headers.iter().find_map(|header| match header {
                    Header::Authorization(value) => Some(value.value().to_string()),
                    _ => None,
                });
                let valid = raw.as_ref().is_some_and(|raw| {
                    // The response qop must be the unquoted token form.
                    let wire_ok = !raw.contains("qop=\"") && raw.contains("qop=auth, nc=");
                    wire_ok
                        && crate::sip::typed::Authorization::parse(raw)
                            .is_ok_and(|auth| verify_digest(&auth, "secret", &Method::Invite, raw))
                });
                seen_tx.send(raw.clone()).unwrap();
                let challenge = challenge.clone();
                let contact = Contact::new(format!("<sip:bob@127.0.0.1:{}>", port));
                tokio::spawn(async move {
                    if valid {
                        tx.reply_with(StatusCode::OK, vec![contact.into()], None)
                            .await
                            .unwrap();
                    } else {
                        tx.reply_with(
                            StatusCode::Unauthorized,
                            vec![WwwAuthenticate::new(challenge).into()],
                            None,
                        )
                        .await
                        .unwrap();
                    }
                    // Keep the server transaction alive to absorb the ACK.
                    while tx.receive().await.is_some() {}
                });
            }
        });

        let (state_tx, _state_rx) = unbounded_channel();
        let (dialog, resp) = tokio::time::timeout(
            PROMPT,
            p.uac_layer
                .do_invite(invite_option(&p, Some(credential())), state_tx),
        )
        .await
        .expect("qop-challenged INVITE did not complete")?;
        let resp: Response = resp.expect("final response after the authenticated retry");
        assert_eq!(resp.status_code, StatusCode::OK, "{challenge_qop}");
        assert!(dialog.inner.is_confirmed(), "{challenge_qop}");

        let first = seen.recv().await.unwrap();
        assert!(first.is_none(), "first INVITE must be unauthenticated");
        let retry = seen.recv().await.unwrap().expect("authenticated retry");
        assert!(!retry.contains("qop=\""), "{retry}");
        assert!(retry.contains("qop=auth, nc="), "{retry}");
        assert!(seen.try_recv().is_err(), "unexpected further INVITE");

        p.token.cancel();
    }
    Ok(())
}

/// A challenge to the authenticated retry is final: no second retry.
#[tokio::test]
async fn test_invite_challenge_after_authenticated_retry_is_final_response() -> crate::Result<()> {
    let status = StatusCode::Unauthorized;
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_uas(uas_incoming, status.clone(), p.uas_port, false);
    let (state_tx, _state_rx) = unbounded_channel();
    let opt = invite_option(&p, Some(credential()));

    let (dialog, resp) = tokio::time::timeout(PROMPT, p.uac_layer.do_invite(opt, state_tx))
        .await
        .expect("challenged retry did not complete")?;

    let resp = resp.expect("the second challenge must be the final response");
    assert_eq!(resp.status_code, status);
    assert!(is_auth_terminated(&dialog.state()));
    assert_eq!(
        seen.recv().await,
        Some(false),
        "first INVITE is unauthenticated"
    );
    assert_eq!(seen.recv().await, Some(true), "retry answers the challenge");
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

/// `cancel()` before the challenge: a cancelled INVITE is not resent with
/// credentials, the challenge is its final response.
#[tokio::test]
async fn test_cancelled_invite_is_not_retried_with_credential() -> crate::Result<()> {
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_uas(uas_incoming, StatusCode::Unauthorized, p.uas_port, true);
    let (state_tx, _state_rx) = unbounded_channel();
    let opt = invite_option(&p, Some(credential()));
    let layer = std::sync::Arc::new(p.uac_layer);
    let (dialog, join) = layer.do_invite_async(opt, state_tx)?;
    dialog.cancel().await?;

    let (_, resp) = tokio::time::timeout(PROMPT, join)
        .await
        .expect("cancelled INVITE did not complete")
        .expect("invite task")?;
    assert_eq!(resp.map(|r| r.status_code), Some(StatusCode::Unauthorized));
    assert!(dialog.state().is_terminated());
    assert_eq!(seen.recv().await, Some(false));
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

const STALE_CHALLENGE: &str =
    r#"Digest realm="example.com", nonce="0f9e8d7c6b5a", stale=true, algorithm=MD5"#;

/// UAS: challenges the unauthenticated INVITE, answers the first
/// `stale_rounds` authenticated ones with `stale=true` (as a load-balanced
/// registrar does when another node issued the nonce), then accepts.
/// Reports, per INVITE, whether it answered the challenge.
fn spawn_stale_uas(
    mut incoming: TransactionReceiver,
    uas_port: u16,
    stale_rounds: usize,
) -> UnboundedReceiver<bool> {
    let (seen_tx, seen_rx) = unbounded_channel();
    tokio::spawn(async move {
        let mut authed_count = 0;
        while let Some(mut tx) = incoming.recv().await {
            if tx.original.method != Method::Invite {
                continue;
            }
            let authed = answers_challenge(&StatusCode::Unauthorized, &tx.original.headers);
            let _ = seen_tx.send(authed);
            let reply = if !authed {
                Some(WwwAuthenticate::new(CHALLENGE))
            } else {
                authed_count += 1;
                (authed_count <= stale_rounds).then(|| WwwAuthenticate::new(STALE_CHALLENGE))
            };
            tokio::spawn(async move {
                match reply {
                    Some(challenge) => tx
                        .reply_with(StatusCode::Unauthorized, vec![challenge.into()], None)
                        .await
                        .expect("reply challenge"),
                    None => {
                        let contact = Contact::new(format!("<sip:bob@127.0.0.1:{}>", uas_port));
                        tx.reply_with(StatusCode::OK, vec![contact.into()], None)
                            .await
                            .expect("reply 200")
                    }
                }
                while tx.receive().await.is_some() {}
            });
        }
    });
    seen_rx
}

/// `401 ... stale=true` to the authenticated retry means only the nonce was
/// rejected (RFC 2617 §3.2.1): the UAC retries with the fresh nonce instead
/// of failing the call.
#[tokio::test]
async fn test_invite_stale_nonce_is_retried() -> crate::Result<()> {
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_stale_uas(uas_incoming, p.uas_port, 1);
    let (state_tx, _state_rx) = unbounded_channel();
    let opt = invite_option(&p, Some(credential()));

    let (dialog, resp) = tokio::time::timeout(PROMPT, p.uac_layer.do_invite(opt, state_tx))
        .await
        .expect("stale-nonce retry did not complete")?;

    assert_eq!(resp.map(|r| r.status_code), Some(StatusCode::OK));
    assert!(dialog.inner.is_confirmed());
    assert_eq!(
        seen.recv().await,
        Some(false),
        "first INVITE is unauthenticated"
    );
    assert_eq!(seen.recv().await, Some(true), "authenticated retry");
    assert_eq!(seen.recv().await, Some(true), "retry with the fresh nonce");
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

/// A server that keeps answering `stale=true` cannot loop the UAC: after the
/// bounded number of stale retries the challenge is the final response.
#[tokio::test]
async fn test_invite_stale_nonce_retries_are_bounded() -> crate::Result<()> {
    let (p, uas_incoming) = peers().await?;
    let mut seen = spawn_stale_uas(uas_incoming, p.uas_port, usize::MAX);
    let (state_tx, _state_rx) = unbounded_channel();
    let opt = invite_option(&p, Some(credential()));

    let (dialog, resp) = tokio::time::timeout(PROMPT, p.uac_layer.do_invite(opt, state_tx))
        .await
        .expect("bounded stale retries did not complete")?;

    assert_eq!(resp.map(|r| r.status_code), Some(StatusCode::Unauthorized));
    assert!(is_auth_terminated(&dialog.state()));
    assert_eq!(
        seen.recv().await,
        Some(false),
        "first INVITE is unauthenticated"
    );
    for _ in 0..3 {
        assert_eq!(seen.recv().await, Some(true));
    }
    assert_no_more_invites(&mut seen).await;

    p.token.cancel();
    Ok(())
}

mod restored_dialogs {
    use super::*;
    use crate::dialog::authenticate::verify_digest;
    use crate::dialog::dialog::{Dialog, DialogInner, DialogSnapshot, DialogSnapshotState};
    use crate::dialog::tests::test_dialog_states::create_invite_request;
    use crate::dialog::DialogId;
    use crate::sip::{prelude::HeadersExt, Request};
    use crate::transaction::key::TransactionRole;
    use std::sync::Arc;

    fn snapshot(p: &Peers, role: TransactionRole) -> crate::Result<DialogSnapshot> {
        let request = create_invite_request("alice-tag", "bob-tag", "restore-auth");
        let id = DialogId::try_from((&request, role))?;
        let (states, _) = unbounded_channel();
        let (transactions, _) = unbounded_channel();
        let inner = DialogInner::new(
            role,
            id,
            request,
            p.uac_layer.endpoint.clone(),
            states,
            Some(Credential {
                password: "old-secret".into(),
                ..credential()
            }),
            Some(Uri::try_from(format!(
                "sip:local@127.0.0.1:{}",
                p.uac_port
            ))?),
            transactions,
        )?;
        let mut snapshot = inner.snapshot();
        snapshot.state = DialogSnapshotState::Confirmed;
        snapshot.local_cseq = 42;
        snapshot.remote_cseq = 17;
        snapshot.remote_uri = Uri::try_from(format!("sip:peer@127.0.0.1:{}", p.uas_port))?;
        snapshot.remote_contact = Some(Contact::new(format!("<{}>", snapshot.remote_uri)));
        Ok(snapshot)
    }

    fn restored(p: &Peers, id: &DialogId) -> crate::dialog::invite_dialog::InviteDialog {
        match p.uac_layer.get_dialog(id) {
            Some(Dialog::Invite(dialog)) => dialog,
            _ => panic!("restored INVITE dialog missing"),
        }
    }

    fn digest(request: &Request, status: &StatusCode) -> Option<String> {
        request
            .headers
            .iter()
            .find_map(|header| match (status, header) {
                (StatusCode::Unauthorized, Header::Authorization(value)) => {
                    Some(value.value().to_string())
                }
                (StatusCode::ProxyAuthenticationRequired, Header::ProxyAuthorization(value)) => {
                    Some(value.value().to_string())
                }
                _ => None,
            })
    }

    async fn assert_restored_request_authenticates(method: Method) -> crate::Result<()> {
        for role in [TransactionRole::Client, TransactionRole::Server] {
            for status in [
                StatusCode::Unauthorized,
                StatusCode::ProxyAuthenticationRequired,
            ] {
                let (p, mut incoming) = peers().await?;
                let snapshot = snapshot(&p, role)?;
                let (states, _) = unbounded_channel();
                let cred = Credential {
                    auth_username: Some("trunk-auth".into()),
                    ..credential()
                };
                assert!(p.uac_layer.restore_from_snapshot_with_credential(
                    snapshot.clone(),
                    states,
                    Some(cred.clone()),
                )?);
                let dialog = restored(&p, &snapshot.id);
                let (seen_tx, mut seen) = unbounded_channel();
                let challenged = status.clone();
                let contact = Contact::new(format!("<{}>", snapshot.remote_uri));
                let server_cred = cred.clone();
                let server_method = method.clone();
                tokio::spawn(async move {
                    while let Some(mut tx) = incoming.recv().await {
                        if tx.original.method != server_method {
                            continue;
                        }
                        let raw = digest(&tx.original, &challenged);
                        let valid = raw.as_ref().is_some_and(|raw| {
                            let auth = crate::sip::typed::Authorization::parse(raw).unwrap();
                            auth.username == server_cred.digest_username()
                                && verify_digest(&auth, &server_cred.password, &server_method, raw)
                        });
                        seen_tx.send(tx.original.clone()).unwrap();
                        let challenged = challenged.clone();
                        let contact = contact.clone();
                        tokio::spawn(async move {
                            if valid {
                                tx.reply_with(StatusCode::OK, vec![contact.into()], None)
                                    .await
                                    .unwrap();
                            } else {
                                tx.reply_with(
                                    challenged.clone(),
                                    vec![challenge_header(&challenged)],
                                    None,
                                )
                                .await
                                .unwrap();
                            }
                            while tx.receive().await.is_some() {}
                        });
                    }
                });

                let response = tokio::time::timeout(PROMPT, async {
                    match method {
                        Method::Invite => dialog.reinvite(None, None).await,
                        // options() is intentionally a no-op for the UAS role;
                        // the generic API can send OPTIONS for either role.
                        Method::Options => dialog.request(Method::Options, None, None).await,
                        Method::Bye => dialog.bye().await.map(|_| None),
                        _ => unreachable!(),
                    }
                })
                .await
                .expect("restored request did not complete")?;
                if method == Method::Bye {
                    assert!(dialog.state().is_terminated());
                } else {
                    assert_eq!(response.map(|r| r.status_code), Some(StatusCode::OK));
                    assert!(dialog.state().is_confirmed());
                }
                let first = seen.try_recv().expect("first request");
                let retry = seen.try_recv().expect("authenticated retry");
                assert!(digest(&first, &status).is_none());
                let raw = digest(&retry, &status).expect("matching authentication header");
                let auth = crate::sip::typed::Authorization::parse(&raw)?;
                assert_eq!(auth.username, cred.digest_username());
                assert!(verify_digest(&auth, &cred.password, &method, &raw));
                assert_eq!(first.cseq_header()?.seq()?, 43);
                assert_eq!(retry.cseq_header()?.seq()?, 44);
                assert_eq!(retry.uri, snapshot.remote_uri);
                assert_eq!(dialog.id(), snapshot.id);
                assert_eq!(dialog.snapshot().local_cseq, 44);
                assert_eq!(dialog.snapshot().remote_cseq, snapshot.remote_cseq);
                assert!(seen.try_recv().is_err(), "unexpected further retry");
                p.token.cancel();
            }
        }
        Ok(())
    }

    #[tokio::test]
    async fn restored_options_authenticates_for_both_roles() -> crate::Result<()> {
        assert_restored_request_authenticates(Method::Options).await
    }

    #[tokio::test]
    async fn restored_reinvite_authenticates_for_both_roles() -> crate::Result<()> {
        assert_restored_request_authenticates(Method::Invite).await
    }

    #[tokio::test]
    async fn restored_bye_authenticates_for_both_roles() -> crate::Result<()> {
        assert_restored_request_authenticates(Method::Bye).await
    }

    #[tokio::test]
    async fn legacy_and_none_restore_leave_credentials_unset() -> crate::Result<()> {
        for role in [TransactionRole::Client, TransactionRole::Server] {
            let (p, _) = peers().await?;
            let snapshot = snapshot(&p, role)?;
            let (states, _) = unbounded_channel();
            assert!(p
                .uac_layer
                .restore_from_snapshot(snapshot.clone(), states.clone())?);
            assert!(restored(&p, &snapshot.id).inner.credential.is_none());
            p.uac_layer.remove_dialog(&snapshot.id);
            assert!(p.uac_layer.restore_from_snapshot_with_credential(
                snapshot.clone(),
                states,
                None,
            )?);
            assert!(restored(&p, &snapshot.id).inner.credential.is_none());
            p.token.cancel();
        }
        Ok(())
    }

    #[tokio::test]
    async fn skipped_restore_keeps_existing_credentials_and_state() -> crate::Result<()> {
        for role in [TransactionRole::Client, TransactionRole::Server] {
            let (p, _) = peers().await?;
            let mut snapshot = snapshot(&p, role)?;
            let (states, _) = unbounded_channel();
            snapshot.state = DialogSnapshotState::Early;
            assert!(!p.uac_layer.restore_from_snapshot_with_credential(
                snapshot.clone(),
                states.clone(),
                Some(credential()),
            )?);
            assert!(p.uac_layer.is_empty());
            snapshot.state = DialogSnapshotState::Confirmed;
            assert!(p.uac_layer.restore_from_snapshot_with_credential(
                snapshot.clone(),
                states.clone(),
                Some(credential()),
            )?);
            let live = restored(&p, &snapshot.id);
            let seq = live.inner.increment_local_seq();
            assert!(!p.uac_layer.restore_from_snapshot_with_credential(
                snapshot.clone(),
                states.clone(),
                Some(Credential {
                    password: "replacement".into(),
                    ..credential()
                }),
            )?);
            let retained = restored(&p, &snapshot.id);
            assert!(Arc::ptr_eq(&live.inner, &retained.inner));
            assert_eq!(
                retained.inner.credential.as_ref().unwrap().password,
                "secret"
            );
            assert_eq!(retained.snapshot().local_cseq, seq);

            // Taking another snapshot does not serialize runtime credentials.
            let next_snapshot = retained.snapshot();
            p.uac_layer.remove_dialog(&snapshot.id);
            assert!(p.uac_layer.restore_from_snapshot(next_snapshot, states)?);
            assert!(restored(&p, &snapshot.id).inner.credential.is_none());
            p.token.cancel();
        }
        Ok(())
    }
}