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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! Token lifecycle — storage, rotation and cross-process single-flight refresh.
//!
//! This module never touches the network. The actual refresh POST is the job of a
//! [`TokenRefresher`] implementation, which subproject A3 (HTTP transport) provides.
pub use ;
// A3 Task 9: the request pipeline (`crate::client::Client::send`) is the
// first non-test caller of these — `jwt` itself stays a private submodule
// (its internals are not part of this crate's public API), but `send` is a
// sibling of `auth`, not a descendant, so it needs a crate-visible path in.
// Crate-private, not `pub`: `UnverifiedScopeObservation`/`observe_scopes`
// are advisory-precheck internals, never meant to leak past this crate's own
// transport layer (design §10).
pub use ;
use crate;
use crateError;
use PathBuf;
use Arc;
use Duration;
use ;
// Fix round 1 (Minor 1, A3 Task 6 review): re-exported (not just `use`d) so
// `crate::test_support` — a sibling module of `auth`, not a descendant — can
// name it too. Before this, `test_support::write_token` hardcoded the
// literal `"tokens.json"` while this module's own `token_path()` test helper
// derived it from `TokenStore`, the exact split-source-of-truth split A2's
// own comments warned about avoiding. `#[cfg(test)]`-gated: its only current
// consumer is `test_support` (test-only), so an unguarded `pub(crate) use`
// here is `unused_imports` in a non-test build.
pub use TOKEN_FILE;
/// Upper bound on the length of an error `message`. The child module ([`refresh`]) uses it as
/// is — it lives in one place so that one layer's message budget does not split into two values.
const MSG_MAX: usize = 512;
/// Upper bound on the lifetime accepted for a single token.
///
/// [`Refreshed::expires_in_secs`] is a **server-supplied value**. If an absurdly large value
/// arrives, `now + expires_in` overflows `u64`, and then the `unwrap_or(now)` fallback below
/// records "already expired" — from then on **every call fires one refresh POST and rotates the
/// chain once**. That is bounded per call but unbounded in the number of calls, and what it runs
/// up against is Tesla's auth rate limit.
///
/// So the lifetime is **cut down** here (why clamp rather than reject: the refresh POST has
/// already succeeded and the rotated token must be preserved). The cut always goes toward the
/// **shorter side**, so it is safe — it only refreshes earlier than necessary and never sends a
/// dead token. 30 days is 90 times Tesla's actual access token lifetime (around 8 hours), so it
/// never touches a normal value, yet it is small enough to stop a rotation storm.
///
/// # There is no lower bound on the other side — and **one must not be added**
///
/// **A hole symmetric to the one above is open on the low side.** [`TokenSet::is_fresh`] is
/// `expires_at > now + EXPIRY_SKEW` (60 seconds), so if the server gives `expires_in_secs <= 60`
/// the new token is **already stale the moment it is written**. Every later
/// [`TokenManager::access_token`] call then fires a refresh POST and rotates the chain once —
/// **literally the same damage** the upper bound above was meant to stop, against the same Tesla
/// auth rate limit, and reached without any clock failure. `expires_in: 0` is a value the server
/// can produce just as freely as `u64::MAX`.
///
/// **Yet the floor must not be propped up with `max`.** `min` is safe because that direction
/// **only ever shortens** — it only refreshes earlier than necessary and never sends a dead
/// token. `max` is the exact opposite: if the server genuinely said "30 seconds" and we insist
/// on 120 seconds, we keep sending an already dead access token for more than 60 seconds. That
/// trades avoiding a rotation storm (cost, rate limit) for **authentication failure (loss of
/// function)**, which is not an even exchange.
///
/// **This argument still holds.** The storm having been closed below does **not** make a lower
/// bound safe — it was closed precisely because the way it was closed was not value manipulation.
/// If someone later reads this as "there is an interval now, so surely `max` is fine", that is a
/// sign the paragraph above needs to be read again. The two mechanisms are not substitutes for
/// each other.
///
/// # The storm was closed by A3 Task 5 — by **frequency**, not by value
///
/// The safe solution was not to manipulate the value but to **put a minimum interval on rotation
/// itself**, and that is [`MIN_REFRESH_INTERVAL`](crate::MIN_REFRESH_INTERVAL) (= 60 seconds, the
/// same as `EXPIRY_SKEW`). The server-supplied lifetime is **still recorded as is** — there is no
/// lower bound even now, and none will be added. The only thing that changed is that the next
/// rotation is **refused** if 60 seconds have not passed since the previous one (the cache is not
/// returned either — that would be sending a dead token, the same failure as the `max` rejected
/// above).
///
/// The boundary and what happens below it remain pinned by
/// `a_reported_lifetime_inside_the_skew_window_is_stale_on_arrival`. That test's
/// `expires_at == now + expires_in` assertion is the evidence that "the value was not touched",
/// so it must not be removed.
///
/// The other half — **raising** `expires_in_secs <= EXPIRY_SKEW` **to a diagnosable condition**
/// (response parser, logging) — is still unimplemented. The storm is blocked, but there is not
/// yet a path that **tells** a person about that server behaviour.
const MAX_TOKEN_LIFETIME: Duration = from_secs;
/// The **generation** of a cached token set.
///
/// It increases by 1 **every time** the token [`TokenManager`] holds in memory **is replaced** —
/// equally when we rotated it ourselves and when we adopted from disk one that a sibling process
/// rotated. The generation is an identifier of "what is in the cache right now", not a counter
/// of "how many times we refreshed".
///
/// # What it is for
///
/// 401 recovery uses it to decide "may I invalidate the token **I used**". Get the generation
/// and the token together from [`TokenManager::access_token_with_generation`], and when a 401
/// arrives hand that generation back to [`TokenManager::invalidate_generation`]. Without this
/// pairing, concurrent 401s kill a token that was just refreshed: the 401 for a request A sent
/// with generation N makes it discard the N+1 that B has already produced.
///
/// # Do not change this into a "refresh count"
///
/// That this value also rises on **disk adoption** (the path that takes over a token a sibling
/// process rotated) is not a mistake. The question the generation answers is "is the token I
/// was given still current", and **adoption replaces that token too**.
///
/// Changing it to "bump only on refresh" makes the generation lie about the question it has to
/// answer: if B adopts a sibling's rotation after A sent a request with generation N and the
/// generation stays N, A's late-arriving 401 matches the generation and discards **the perfectly
/// good token that was just adopted** — the very accident the generation exists to prevent would
/// be left in place on the adoption path alone.
/// (Pinned by `generation_increases_when_a_siblings_rotation_is_adopted`.)
///
/// Conversely, the time of the last **rotation** (the reference point of
/// `MIN_REFRESH_INTERVAL`) is **not** advanced on adoption — that one asks "how often did we
/// send a POST". The two fields answer different questions, so their update conditions differ
/// too.
pub type Generation = u64;
/// Minimum interval kept between rotations (= refresh POSTs).
///
/// It is the **same value** as `EXPIRY_SKEW` (crate-internal). The logic closes in one sentence:
/// **"a lifetime that cannot be considered fresh cannot be rotated either."** If the two values
/// diverge that sentence breaks, so `the_min_refresh_interval_is_the_expiry_skew` pins the
/// equality.
///
/// # What it prevents
///
/// **The same damage** as the rotation storm that `MAX_TOKEN_LIFETIME` blocks on the high side
/// was open on the low side as well: if the server gives `expires_in_secs <= 60`, the new token
/// is already stale the moment it is recorded, so **every** later call fires a refresh POST and
/// rotates the chain once. A2 did not fix this hole; it documented it and handed it to A3 (see
/// "There is no lower bound on the other side" on `MAX_TOKEN_LIFETIME`). This is that handover.
///
/// It is **not** a `max` lower bound that inflates the value. That direction ignores a short
/// lifetime the server genuinely stated and sends a dead access token — a trade that buys
/// authentication failure to avoid a rotation storm. Instead it limits **the frequency of
/// rotation itself**. The lifetime value is recorded exactly as the server gave it.
///
/// # A repeated request inside the interval is an **error**, not the cache
///
/// Simply returning the cached (but already stale) token would send a dead token, which is
/// **literally the same failure** as the `max` lower bound rejected above. So it stops with
/// [`Error::Auth`]`{ pricing: None }`, naming the cause. `pricing` is `None` because no endpoint
/// was reached — [`Error::billing`] must count it as [`crate::Billing::NotBilled`].
///
/// # It is process-local
///
/// The time of the last rotation is kept only in process memory (adding a field to the token
/// file would change A2's storage format contract). A new process can refresh immediately
/// without knowing this interval, and that is the **intended** behaviour — the purpose of this
/// mechanism is to suppress a storm within one process, not to be a global rate limiter. The
/// cross-process guarantee is provided by A2's flock single-flight.
pub const MIN_REFRESH_INTERVAL: Duration = from_secs;
/// A new token set returned by a refresh round trip.
///
/// Because it is `#[non_exhaustive]`, external crates cannot construct it with a literal.
/// [`Refreshed::new`] exists instead — without it the public [`TokenRefresher`] **could not be
/// implemented** outside the crate, and we would ship a public trait nobody can implement.
///
/// # `Debug` is written by hand (REQ-18)
///
/// This type carries **both** the access token and the refresh token, is re-exported from the
/// crate root, and is created right after the transport layer (A3) parses the refresh response
/// — exactly the spot where one `tracing::debug!(?refreshed)` line would stamp a live refresh
/// token into the logs. So it does not use `#[derive(Debug)]` and is written by hand in the
/// **same shape** as `TokenSet` (crate-internal): it destructures `Self` so that an added field
/// breaks with `E0027` instead of being silently left out, and the marker is the
/// `redaction::REDACTED` constant of the crate's single redaction layer.
/// An implementation of the refresh round trip.
///
/// A2 **only calls** this trait — the actual HTTP POST implementation comes from subproject A3.
/// That is why all of A2 is tested without a network.
///
/// The method is synchronous (stage 1 of removing tokio). It is kept dyn-safe so that it can be
/// held as `Arc<dyn TokenRefresher>`.
/// The mutable state of [`TokenManager`].
///
/// The cache and the "refresh forbidden" flag are guarded by the **same** mutex. Kept apart, a
/// persist failure and the cache replacement would happen in different critical sections, and a
/// task caught between them could fire one more rotation without seeing the forbidden flag.
///
/// The [`Generation`] and the last rotation time, added later, are **under the same mutex**
/// too. The generation in particular must be one with the cache — if the critical section that
/// changed the cache and the one that bumped the generation were separate, a caller caught
/// between them would receive a generation that does not match its token and would invalidate a
/// token it never used. Placing the two fields side by side is not a convenience; it is that
/// invariant.
/// The reason this manager no longer rotates.
/// A copy taken from the state when a refresh starts (read by steps 3–9, outside the lock).
/// The outcome when the steps outside the lock succeeded.
/// The outcome when the steps outside the lock failed. Only a persist failure changes the state
/// (`refresh_forbidden`).
/// The token lifecycle manager.
///
/// It collapses refreshes into a single flight with [`cell::StateCell`] (Condvar + `refreshing`
/// flag) inside the process and with a fixed-inode file lock across processes (REQ-15). Every
/// method is synchronous and needs no runtime.
/// The error for when the wait on the in-process mutex exceeded `state_deadline`.
///
/// [`TokenManager::access_token`] and [`TokenManager::invalidate_generation`] wait on the
/// **same** seam, so there must be a single wording too — a bug report usually carries only this
/// one line, and if the two places diverged it would be impossible to tell which one it came
/// from. The prefix is **different** from the file lock's (`token lock:`) (REQ-15 AC3).