monosecret 0.4.4

Declarative secrets, every environment, any provider
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
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
//! Cache-entry encoding, ownership, and freshness policy.
//!
//! Provider I/O, auditing, warning output, and remediation remain in
//! [`crate::secrets`]. This module owns the provider-independent envelope
//! format and the decisions that can be made from a stored value alone.

use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use data_encoding::BASE64;
use monosecret_rpc::Revision;
use secrecy::zeroize::Zeroizing;

use crate::ProviderValue;
use crate::SecretBytes;

/// Marker every cache entry starts with, identifying the value as Monosecret's
/// own and naming the format version — without parsing it.
///
/// Ownership has to be decidable even when the payload is not readable. A
/// truncated write leaves something only Monosecret could have put there, which
/// is safe to replace; a value with no marker belongs to someone else and must
/// never be touched.
pub(crate) const CACHE_ENVELOPE_MARKER: &str = "monosecret-cache-v4:";

/// The previous envelope stored plaintext as a JSON string. Read it as UTF-8
/// bytes during migration, but never write it again.
const V3_CACHE_ENVELOPE_MARKER: &str = "monosecret-cache-v3:";

/// The 0.17 envelope recorded when an entry was written rather than when it
/// expires. Keep recognizing it so an upgrade can replace its own entries
/// without mistaking another project or profile's entry for ours.
const LEGACY_CACHE_ENVELOPE_MARKER: &str = "monosecret-cache-v2:";

/// Value stored inside the configured cache provider. The provider remains
/// responsible for encryption; the envelope adds freshness, route invalidation,
/// and ownership metadata.
#[derive(serde::Serialize, serde::Deserialize)]
struct CacheEnvelope {
	project: String,
	profile: String,
	expires_at: u64,
	max_age_secs: u64,
	route_fingerprint: String,
	#[serde(default)]
	secret_expires_at_unix_ms: Option<u64>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	revision: Option<Revision>,
	/// Strict padded base64 is the cache envelope's byte serialization. It is
	/// independent of a declaration's manifest `encoding`.
	#[serde(with = "zeroizing_string")]
	value_base64: Zeroizing<String>,
}

#[derive(serde::Deserialize)]
struct V3CacheEnvelope {
	project: String,
	profile: String,
	expires_at: u64,
	max_age_secs: u64,
	route_fingerprint: String,
	#[serde(default)]
	secret_expires_at_unix_ms: Option<u64>,
	#[serde(with = "zeroizing_string")]
	value: Zeroizing<String>,
}

/// The 0.17 envelope can still serve its owner while it remains fresh under the
/// active route's policy. Another owner cannot infer its expiry because v2 did
/// not store the `max_age` that created it, so foreign v2 entries remain
/// untouched.
#[derive(serde::Deserialize)]
struct LegacyCacheEnvelope {
	project: String,
	profile: String,
	cached_at: u64,
	route_fingerprint: String,
	#[serde(with = "zeroizing_string")]
	value: Zeroizing<String>,
}

enum DecodedEnvelope {
	Current(CacheEnvelope),
	V3(V3CacheEnvelope),
	Legacy(LegacyCacheEnvelope),
}

/// Serde for the envelope's plaintext, keeping it in a zeroizing buffer in both
/// directions. Deserialization moves serde's `String` directly into the buffer.
mod zeroizing_string {
	use secrecy::zeroize::Zeroizing;
	use serde::Deserialize;
	use serde::Deserializer;
	use serde::Serializer;

	pub(super) fn serialize<S: Serializer>(
		value: &Zeroizing<String>,
		serializer: S,
	) -> Result<S::Ok, S::Error> {
		serializer.serialize_str(value)
	}

	pub(super) fn deserialize<'de, D: Deserializer<'de>>(
		deserializer: D,
	) -> Result<Zeroizing<String>, D::Error> {
		String::deserialize(deserializer).map(Zeroizing::new)
	}
}

/// Whether the caller may change the value sitting at a cache address.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum CacheOwnership {
	/// This project and profile wrote a readable entry.
	Ours,
	/// A readable Monosecret entry whose declared lifetime has ended. Its
	/// original owner no longer has an interest in preserving it.
	Expired,
	/// Another project or profile wrote the entry.
	Foreign { project: String, profile: String },
	/// The ownership marker is ours, but the payload is damaged or incompatible.
	OursUnreadable,
	/// No Monosecret ownership marker is present.
	Unrecognized,
}

/// What a stored cache entry can do for the read that found it.
pub(crate) enum CacheEntryStatus {
	/// Fresh, and written for the expected authoritative route.
	Fresh {
		value: SecretBytes,
		refresh_at_unix_ms: Option<u64>,
		expires_at_unix_ms: Option<u64>,
		revision: Option<Revision>,
	},
	/// Expired (regardless of owner), or ours but no longer usable because its
	/// authoritative route or freshness policy changed.
	Stale,
	/// Marked as ours but not readable as this envelope version.
	OursUnreadable,
	/// Owned by another project or profile.
	Foreign { project: String, profile: String },
	/// Not a Monosecret cache entry.
	Unrecognized,
}

/// Errors that can prevent encoding a cache entry.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CacheEncodeError {
	#[error(transparent)]
	Clock(#[from] std::time::SystemTimeError),
	#[error("cache expiration timestamp is too large")]
	ExpirationOverflow,
	#[error("the secret has already expired")]
	SecretExpired,
	#[error(transparent)]
	Serialize(#[from] serde_json::Error),
}

fn decode(stored: &SecretBytes) -> Option<Result<DecodedEnvelope, String>> {
	fn text(payload: &[u8]) -> Result<&str, String> {
		std::str::from_utf8(payload).map_err(|_| "cache envelope is not UTF-8".to_string())
	}
	let stored = stored.expose_secret();

	if let Some(payload) = stored.strip_prefix(CACHE_ENVELOPE_MARKER.as_bytes()) {
		return Some(text(payload).and_then(|payload| {
			serde_json::from_str(payload)
				.map(DecodedEnvelope::Current)
				.map_err(|error| error.to_string())
		}));
	}

	if let Some(payload) = stored.strip_prefix(V3_CACHE_ENVELOPE_MARKER.as_bytes()) {
		return Some(text(payload).and_then(|payload| {
			serde_json::from_str(payload)
				.map(DecodedEnvelope::V3)
				.map_err(|error| error.to_string())
		}));
	}

	stored
		.strip_prefix(LEGACY_CACHE_ENVELOPE_MARKER.as_bytes())
		.map(|payload| {
			text(payload).and_then(|payload| {
				serde_json::from_str(payload)
					.map(DecodedEnvelope::Legacy)
					.map_err(|error| error.to_string())
			})
		})
}

fn unix_timestamp() -> Result<u64, std::time::SystemTimeError> {
	SystemTime::now()
		.duration_since(UNIX_EPOCH)
		.map(|duration| duration.as_secs())
}

/// Classify cache ownership without trusting the provider address.
pub(crate) fn ownership(stored: &SecretBytes, project: &str, profile: &str) -> CacheOwnership {
	ownership_at(stored, project, profile, unix_timestamp().ok())
}

fn ownership_at(
	stored: &SecretBytes,
	project: &str,
	profile: &str,
	now: Option<u64>,
) -> CacheOwnership {
	match decode(stored) {
		None => CacheOwnership::Unrecognized,
		Some(Err(_)) => CacheOwnership::OursUnreadable,
		Some(Ok(DecodedEnvelope::Current(envelope))) => {
			if now.is_some_and(|now| now >= envelope.expires_at) {
				CacheOwnership::Expired
			} else if envelope.project == project && envelope.profile == profile {
				CacheOwnership::Ours
			} else {
				CacheOwnership::Foreign {
					project: envelope.project,
					profile: envelope.profile,
				}
			}
		}
		Some(Ok(DecodedEnvelope::V3(envelope))) => {
			if now.is_some_and(|now| now >= envelope.expires_at) {
				CacheOwnership::Expired
			} else if envelope.project == project && envelope.profile == profile {
				CacheOwnership::Ours
			} else {
				CacheOwnership::Foreign {
					project: envelope.project,
					profile: envelope.profile,
				}
			}
		}
		Some(Ok(DecodedEnvelope::Legacy(envelope)))
			if envelope.project == project && envelope.profile == profile =>
		{
			CacheOwnership::Ours
		}
		Some(Ok(DecodedEnvelope::Legacy(envelope))) => {
			CacheOwnership::Foreign {
				project: envelope.project,
				profile: envelope.profile,
			}
		}
	}
}

/// Inspect an entry using the current wall clock.
///
/// Clock errors are returned separately so the caller can preserve the
/// fail-open cache policy while deciding how to report the failure.
pub(crate) fn inspect_entry(
	stored: &SecretBytes,
	project: &str,
	profile: &str,
	route_fingerprint: &str,
	max_age_secs: u64,
) -> Result<CacheEntryStatus, std::time::SystemTimeError> {
	inspect_entry_with_clock(
		stored,
		project,
		profile,
		route_fingerprint,
		max_age_secs,
		unix_timestamp,
	)
}

fn inspect_entry_with_clock<E>(
	stored: &SecretBytes,
	project: &str,
	profile: &str,
	route_fingerprint: &str,
	max_age_secs: u64,
	clock: impl FnOnce() -> Result<u64, E>,
) -> Result<CacheEntryStatus, E> {
	let Some(decoded) = decode(stored) else {
		return Ok(CacheEntryStatus::Unrecognized);
	};
	let (
		project_owner,
		profile_owner,
		expires_at,
		envelope_max_age,
		route,
		value,
		secret_expiry,
		revision,
	) = match decoded {
		Ok(DecodedEnvelope::Current(envelope)) => {
			let value = BASE64
				.decode(envelope.value_base64.as_bytes())
				.map(SecretBytes::from_vec)
				.map_err(|_| ())
				.ok();
			(
				envelope.project,
				envelope.profile,
				envelope.expires_at,
				envelope.max_age_secs,
				envelope.route_fingerprint,
				value,
				envelope.secret_expires_at_unix_ms,
				envelope.revision,
			)
		}
		Ok(DecodedEnvelope::V3(envelope)) => {
			(
				envelope.project,
				envelope.profile,
				envelope.expires_at,
				envelope.max_age_secs,
				envelope.route_fingerprint,
				Some(SecretBytes::from_utf8(envelope.value.as_str())),
				envelope.secret_expires_at_unix_ms,
				None,
			)
		}
		Ok(DecodedEnvelope::Legacy(envelope)) => {
			if envelope.project != project || envelope.profile != profile {
				return Ok(CacheEntryStatus::Foreign {
					project: envelope.project,
					profile: envelope.profile,
				});
			}
			if envelope.route_fingerprint != route_fingerprint {
				return Ok(CacheEntryStatus::Stale);
			}

			let now = clock()?;
			if envelope.cached_at > now || now.saturating_sub(envelope.cached_at) > max_age_secs {
				return Ok(CacheEntryStatus::Stale);
			}
			return Ok(CacheEntryStatus::Fresh {
				value: SecretBytes::from_utf8(envelope.value.as_str()),
				refresh_at_unix_ms: envelope
					.cached_at
					.checked_add(max_age_secs)
					.and_then(|expires_at| expires_at.checked_mul(1000)),
				expires_at_unix_ms: None,
				revision: None,
			});
		}
		Err(_) => return Ok(CacheEntryStatus::OursUnreadable),
	};

	let now = clock()?;

	if now >= expires_at || secret_expiry.is_some_and(|expiry| now.saturating_mul(1000) >= expiry) {
		// Expiration is intrinsic to v3 and v4 entries, so whoever encounters it can
		// discard it even when its project/profile no longer has a manifest.
		return Ok(CacheEntryStatus::Stale);
	}

	if project_owner != project || profile_owner != profile {
		return Ok(CacheEntryStatus::Foreign {
			project: project_owner,
			profile: profile_owner,
		});
	}

	// Reconstructing the write time from the self-contained v3/v4 policy preserves
	// clock-rollback detection without retaining `cached_at` in the envelope.
	let Some(cached_at) = expires_at.checked_sub(envelope_max_age) else {
		return Ok(CacheEntryStatus::Stale);
	};

	if cached_at > now || envelope_max_age != max_age_secs {
		return Ok(CacheEntryStatus::Stale);
	}

	if route != route_fingerprint {
		return Ok(CacheEntryStatus::Stale);
	}
	Ok(match value {
		Some(value) => {
			CacheEntryStatus::Fresh {
				value,
				refresh_at_unix_ms: expires_at.checked_mul(1000),
				expires_at_unix_ms: secret_expiry,
				revision,
			}
		}
		None => CacheEntryStatus::OursUnreadable,
	})
}

#[cfg(test)]
fn inspect_entry_at(
	stored: &SecretBytes,
	project: &str,
	profile: &str,
	route_fingerprint: &str,
	max_age_secs: u64,
	now: u64,
) -> CacheEntryStatus {
	inspect_entry_with_clock(
		stored,
		project,
		profile,
		route_fingerprint,
		max_age_secs,
		|| Ok::<u64, std::convert::Infallible>(now),
	)
	.expect("an infallible test clock cannot fail")
}

/// Encode an entry using the current wall clock.
pub(crate) fn encode_entry(
	project: &str,
	profile: &str,
	max_age_secs: u64,
	route_fingerprint: String,
	value: &ProviderValue,
) -> Result<SecretBytes, CacheEncodeError> {
	encode_provider_entry_at(
		project,
		profile,
		unix_timestamp()?,
		max_age_secs,
		route_fingerprint,
		value,
	)
}

fn encode_provider_entry_at(
	project: &str,
	profile: &str,
	now: u64,
	max_age_secs: u64,
	route_fingerprint: String,
	value: &ProviderValue,
) -> Result<SecretBytes, CacheEncodeError> {
	let cache_expires_at = now
		.checked_add(max_age_secs)
		.ok_or(CacheEncodeError::ExpirationOverflow)?;

	let expires_at = match value.expires_at_unix_ms {
		Some(secret_expiry) => {
			let secret_expiry_secs = secret_expiry / 1000;
			if secret_expiry_secs <= now {
				return Err(CacheEncodeError::SecretExpired);
			}

			cache_expires_at.min(secret_expiry_secs)
		}
		None => cache_expires_at,
	};

	let envelope = CacheEnvelope {
		project: project.to_string(),
		profile: profile.to_string(),
		expires_at,
		max_age_secs,
		route_fingerprint,
		value_base64: Zeroizing::new(BASE64.encode(value.value.expose_secret())),
		secret_expires_at_unix_ms: value.expires_at_unix_ms,
		revision: value.revision.clone(),
	};
	// Both plaintext renderings of the envelope are held in buffers that
	// zeroize on drop.
	let json = Zeroizing::new(serde_json::to_string(&envelope)?);
	let serialized = Zeroizing::new(format!("{CACHE_ENVELOPE_MARKER}{}", json.as_str()));
	Ok(SecretBytes::from_utf8(serialized.as_str()))
}

#[cfg(test)]
fn encode_entry_at(
	project: &str,
	profile: &str,
	now: u64,
	max_age_secs: u64,
	route_fingerprint: String,
	value: &SecretBytes,
	expiry: Option<u64>,
) -> Result<SecretBytes, CacheEncodeError> {
	encode_provider_entry_at(
		project,
		profile,
		now,
		max_age_secs,
		route_fingerprint,
		&ProviderValue::new(value.clone(), expiry),
	)
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn revision_cache_envelopes_preserve_pairs_and_accept_older_entries() {
		let value = ProviderValue::new(SecretBytes::from_utf8("old-value"), Some(1_055_000))
			.with_revision(Some(
				Revision::new("provider:old-generation".into()).unwrap(),
			));
		let encoded = encode_provider_entry_at(
			PROJECT,
			PROFILE,
			WRITTEN_AT,
			MAX_AGE,
			FINGERPRINT.into(),
			&value,
		)
		.unwrap();
		let CacheEntryStatus::Fresh {
			value: cached,
			revision,
			expires_at_unix_ms,
			refresh_at_unix_ms,
		} = inspect_entry_at(
			&encoded,
			PROJECT,
			PROFILE,
			FINGERPRINT,
			MAX_AGE,
			WRITTEN_AT + 1,
		)
		else {
			panic!()
		};
		assert_eq!(cached.expose_secret(), b"old-value");
		assert_eq!(revision, value.revision);
		assert_eq!(expires_at_unix_ms, Some(1_055_000));

		assert_eq!(refresh_at_unix_ms, Some(1_055_000));
		let mut envelope: serde_json::Value = serde_json::from_str(
			encoded
				.try_as_utf8()
				.unwrap()
				.strip_prefix(CACHE_ENVELOPE_MARKER)
				.unwrap(),
		)
		.unwrap();
		envelope.as_object_mut().unwrap().remove("revision");
		let old = SecretBytes::from_utf8(format!("{CACHE_ENVELOPE_MARKER}{envelope}"));
		let CacheEntryStatus::Fresh {
			revision, value, ..
		} = inspect_entry_at(&old, PROJECT, PROFILE, FINGERPRINT, MAX_AGE, WRITTEN_AT + 1)
		else {
			panic!()
		};
		assert!(revision.is_none());
		assert_eq!(value.expose_secret(), b"old-value");
	}

	const PROJECT: &str = "project";
	const PROFILE: &str = "default";
	const FINGERPRINT: &str = "route-v1";
	const WRITTEN_AT: u64 = 1_000;
	const MAX_AGE: u64 = 60;
	const EXPIRES_AT: u64 = 1_060;

	fn entry() -> SecretBytes {
		encode_entry_at(
			PROJECT,
			PROFILE,
			WRITTEN_AT,
			MAX_AGE,
			FINGERPRINT.to_string(),
			&SecretBytes::from_utf8("sensitive"),
			None,
		)
		.expect("cache envelope serializes")
	}

	#[test]
	fn encoded_entry_round_trips_before_expiration() {
		let decoded = decode(&entry())
			.expect("marker present")
			.expect("valid envelope");
		let DecodedEnvelope::Current(envelope) = decoded else {
			panic!("new entries use the current envelope");
		};
		let status = inspect_entry_at(
			&entry(),
			PROJECT,
			PROFILE,
			FINGERPRINT,
			MAX_AGE,
			EXPIRES_AT - 1,
		);
		let CacheEntryStatus::Fresh {
			value,
			refresh_at_unix_ms,
			expires_at_unix_ms,
			..
		} = status
		else {
			panic!("an entry is fresh before its expiration timestamp");
		};
		assert_eq!(envelope.expires_at, EXPIRES_AT);

		assert_eq!(envelope.max_age_secs, MAX_AGE);
		assert_eq!(value.expose_secret(), b"sensitive");
		assert_eq!(refresh_at_unix_ms, Some(EXPIRES_AT * 1000));
		assert_eq!(expires_at_unix_ms, None);
	}

	#[test]
	fn v4_round_trips_arbitrary_bytes_with_padded_base64() {
		let expected = [0x00, 0xff, 0x80, 0x0a];
		let entry = encode_entry_at(
			PROJECT,
			PROFILE,
			WRITTEN_AT,
			MAX_AGE,
			FINGERPRINT.to_string(),
			&SecretBytes::from_slice(&expected),
			None,
		)
		.unwrap();
		let payload = entry
			.expose_secret()
			.strip_prefix(CACHE_ENVELOPE_MARKER.as_bytes())
			.unwrap();
		let envelope: serde_json::Value = serde_json::from_slice(payload).unwrap();
		assert_eq!(
			envelope
				.get("value_base64")
				.and_then(serde_json::Value::as_str),
			Some("AP+ACg==")
		);
		assert!(envelope.get("value").is_none());

		let CacheEntryStatus::Fresh { value, .. } = inspect_entry_at(
			&entry,
			PROJECT,
			PROFILE,
			FINGERPRINT,
			MAX_AGE,
			EXPIRES_AT - 1,
		) else {
			panic!("v4 entry should be fresh");
		};
		assert_eq!(value.expose_secret(), expected);
	}

	#[test]
	fn v3_text_entries_remain_readable_as_utf8_bytes() {
		let entry = SecretBytes::from_utf8(format!(
			"{V3_CACHE_ENVELOPE_MARKER}{}",
			serde_json::json!({
				"project": PROJECT,
				"profile": PROFILE,
				"expires_at": EXPIRES_AT,
				"max_age_secs": MAX_AGE,
				"route_fingerprint": FINGERPRINT,
				"value": "legacy text",
			})
		));
		let CacheEntryStatus::Fresh { value, .. } = inspect_entry_at(
			&entry,
			PROJECT,
			PROFILE,
			FINGERPRINT,
			MAX_AGE,
			EXPIRES_AT - 1,
		) else {
			panic!("v3 entry should remain fresh");
		};
		assert_eq!(value.expose_secret(), b"legacy text");
	}

	#[test]
	fn entry_is_stale_at_its_expiration() {
		assert!(matches!(
			inspect_entry_at(&entry(), PROJECT, PROFILE, FINGERPRINT, MAX_AGE, EXPIRES_AT),
			CacheEntryStatus::Stale
		));
	}

	#[test]
	fn secret_expiry_is_preserved_and_caps_cache_freshness() {
		let secret_expiry_ms = (WRITTEN_AT + 20) * 1000 + 500;
		let entry = encode_entry_at(
			PROJECT,
			PROFILE,
			WRITTEN_AT,
			MAX_AGE,
			FINGERPRINT.to_string(),
			&SecretBytes::from_utf8("sensitive"),
			Some(secret_expiry_ms),
		)
		.expect("unexpired secret can be cached");

		let CacheEntryStatus::Fresh {
			refresh_at_unix_ms,
			expires_at_unix_ms,
			..
		} = inspect_entry_at(
			&entry,
			PROJECT,
			PROFILE,
			FINGERPRINT,
			MAX_AGE,
			WRITTEN_AT + 19,
		)
		else {
			panic!("entry is fresh before the capped cache boundary");
		};
		assert_eq!(refresh_at_unix_ms, Some((WRITTEN_AT + 20) * 1000));
		assert_eq!(expires_at_unix_ms, Some(secret_expiry_ms));
		assert!(matches!(
			inspect_entry_at(
				&entry,
				PROJECT,
				PROFILE,
				FINGERPRINT,
				MAX_AGE,
				WRITTEN_AT + 20,
			),
			CacheEntryStatus::Stale
		));
	}

	#[test]
	fn clock_rollback_makes_an_implausibly_distant_expiration_stale() {
		assert!(matches!(
			inspect_entry_at(
				&entry(),
				PROJECT,
				PROFILE,
				FINGERPRINT,
				MAX_AGE,
				WRITTEN_AT - 1
			),
			CacheEntryStatus::Stale
		));
	}

	#[test]
	fn changed_max_age_invalidates_an_unexpired_entry() {
		assert!(matches!(
			inspect_entry_at(
				&entry(),
				PROJECT,
				PROFILE,
				FINGERPRINT,
				MAX_AGE / 2,
				WRITTEN_AT
			),
			CacheEntryStatus::Stale
		));
	}

	#[test]
	fn encoded_entry_stores_expiration_instead_of_write_time() {
		let entry = entry();
		let payload = entry
			.expose_secret()
			.strip_prefix(CACHE_ENVELOPE_MARKER.as_bytes())
			.expect("marker present");
		let envelope: serde_json::Value = serde_json::from_slice(payload).unwrap();
		assert_eq!(
			envelope
				.get("expires_at")
				.and_then(serde_json::Value::as_u64),
			Some(EXPIRES_AT)
		);
		assert_eq!(
			envelope
				.get("max_age_secs")
				.and_then(serde_json::Value::as_u64),
			Some(MAX_AGE)
		);
		assert!(envelope.get("cached_at").is_none());
	}

	#[test]
	fn expiration_timestamp_overflow_refuses_the_cache_entry() {
		assert!(matches!(
			encode_entry_at(
				PROJECT,
				PROFILE,
				u64::MAX,
				MAX_AGE,
				FINGERPRINT.to_string(),
				&SecretBytes::from_utf8("sensitive"),
				None,
			),
			Err(CacheEncodeError::ExpirationOverflow)
		));
	}

	#[test]
	fn ownership_distinguishes_ours_foreign_unreadable_and_unrecognized() {
		assert_eq!(
			ownership_at(&entry(), PROJECT, PROFILE, Some(EXPIRES_AT - 1)),
			CacheOwnership::Ours
		);
		assert_eq!(
			ownership_at(&entry(), "other-project", PROFILE, Some(EXPIRES_AT - 1)),
			CacheOwnership::Foreign {
				project: PROJECT.to_string(),
				profile: PROFILE.to_string(),
			}
		);
		assert_eq!(
			ownership(
				&SecretBytes::from_utf8(format!("{CACHE_ENVELOPE_MARKER}{{truncated")),
				PROJECT,
				PROFILE
			),
			CacheOwnership::OursUnreadable
		);
		assert_eq!(
			ownership(
				&SecretBytes::from_utf8("someone else's value"),
				PROJECT,
				PROFILE
			),
			CacheOwnership::Unrecognized
		);
	}

	#[test]
	fn expired_entry_can_be_removed_by_whichever_project_encounters_it() {
		assert_eq!(
			ownership_at(&entry(), "other-project", "other-profile", Some(EXPIRES_AT)),
			CacheOwnership::Expired
		);
		assert!(matches!(
			inspect_entry_at(
				&entry(),
				"other-project",
				"other-profile",
				"different-route",
				MAX_AGE,
				EXPIRES_AT,
			),
			CacheEntryStatus::Stale
		));
	}

	fn legacy_entry() -> SecretBytes {
		SecretBytes::from_utf8(format!(
			"{LEGACY_CACHE_ENVELOPE_MARKER}{}",
			serde_json::json!({
				"project": PROJECT,
				"profile": PROFILE,
				"cached_at": WRITTEN_AT,
				"route_fingerprint": FINGERPRINT,
				"value": "sensitive",
			})
		))
	}

	#[test]
	fn legacy_entries_preserve_ownership_during_migration() {
		let legacy = legacy_entry();
		assert_eq!(
			ownership_at(&legacy, PROJECT, PROFILE, Some(EXPIRES_AT)),
			CacheOwnership::Ours
		);
		assert_eq!(
			ownership_at(&legacy, "other-project", PROFILE, Some(EXPIRES_AT)),
			CacheOwnership::Foreign {
				project: PROJECT.to_string(),
				profile: PROFILE.to_string(),
			}
		);
	}

	#[test]
	fn fresh_legacy_entry_remains_usable_during_migration() {
		let legacy = legacy_entry();
		let status = inspect_entry_at(&legacy, PROJECT, PROFILE, FINGERPRINT, MAX_AGE, EXPIRES_AT);
		let CacheEntryStatus::Fresh {
			value,
			refresh_at_unix_ms,
			expires_at_unix_ms,
			..
		} = status
		else {
			panic!("v2 preserves its original inclusive freshness boundary");
		};
		assert_eq!(value.expose_secret(), b"sensitive");
		assert_eq!(refresh_at_unix_ms, Some(EXPIRES_AT * 1000));
		assert_eq!(expires_at_unix_ms, None);
	}

	#[test]
	fn expired_legacy_entry_is_stale_for_its_owner() {
		assert!(matches!(
			inspect_entry_at(
				&legacy_entry(),
				PROJECT,
				PROFILE,
				FINGERPRINT,
				MAX_AGE,
				EXPIRES_AT + 1
			),
			CacheEntryStatus::Stale
		));
	}

	#[test]
	fn changed_route_is_stale_even_inside_the_time_window() {
		assert!(matches!(
			inspect_entry_at(
				&entry(),
				PROJECT,
				PROFILE,
				"different-route",
				MAX_AGE,
				EXPIRES_AT - 1
			),
			CacheEntryStatus::Stale
		));
	}
}