tamga 0.3.2

Official Rust SDK for Tamga. Integrate license activation, offline verification, and machine management into your Rust 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
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
//! `Policy` and its enums — the policy-derived behavior reference an SDK
//! needs to interpret a license, not just its `ValidationCode`.
//!
//! Contents:
//!
//! - `LicenseScheme`: `ED25519_SIGN`, `RSA_2048_PKCS1_SIGN`,
//!   `RSA_2048_PKCS1_PSS_SIGN`, `ECDSA_P256_SIGN`, `RSA_2048_JWT_RS256`, plus
//!   `None`/unset (legacy plain key string, unsigned).
//! - `OverageStrategy`: `NO_OVERAGE`, `ALLOW_1_25X_OVERAGE`,
//!   `ALLOW_1_5X_OVERAGE`, `ALLOW_2X_OVERAGE`, `ALWAYS_ALLOW_OVERAGE`.
//!   Multiplies the relevant `max_*` limit before comparing; applies to
//!   machines/cores/memory/disk/processes — **not** to `uses` (always
//!   strict `>=` regardless of strategy).
//! - `HeartbeatCullStrategy`: `DEACTIVATE_DEAD` (row deleted), `KEEP_DEAD`
//!   (row kept).
//! - `HeartbeatResurrectionStrategy`: `NO_REVIVE`, `1_MINUTE_REVIVE`,
//!   `2_MINUTE_REVIVE`, `5_MINUTE_REVIVE`, `10_MINUTE_REVIVE`,
//!   `15_MINUTE_REVIVE`, `ALWAYS_REVIVE`.
//! - `check_in_interval`: lowercase wire values — inconsistent casing vs. the
//!   `SCREAMING_SNAKE_CASE` used elsewhere, and there are **two** lowercase
//!   spellings in play. The column's `CHECK` constraint stores only
//!   `"daily"`/`"weekly"`/`"monthly"`/`"yearly"`, which is what a `GET`
//!   returns; the server's own overdue calculation matches the unstorable
//!   `"day"`/`"week"`/`"month"`/`"year"`. `CheckInInterval` decodes both.
//! - Free-text, branch-on-literal fields — model as open string newtypes
//!   with named associated constants, **not** closed enums (the server
//!   branches on literal string match; treat any unrecognized value as
//!   "deny/default"):
//!   - `expiration_strategy`: `"RESTRICT_ACCESS"` (default),
//!     `"MAINTAIN_ACCESS"`, `"ALLOW_ACCESS"`, `"REVOKE_ACCESS"`. The last
//!     one is the only value under which an expired licence stops
//!     authenticating at all (`401 LICENSE_EXPIRED`); under the other three
//!     it authenticates and the expiry surfaces as a validation outcome.
//!   - `renewal_basis`: `"FROM_EXPIRY"` (default), `"FROM_NOW"`.
//!   - `authentication_strategy`: `"TOKEN"` (default), `"LICENSE"`,
//!     `"MIXED"`, `"NONE"`. **Licence-key auth is off by default**: only
//!     `LICENSE` and `MIXED` accept a licence key as a credential.
//!     `"NONE"` behaves like `"TOKEN"` at this gate — both refuse with
//!     `401 LICENSE_NOT_ALLOWED`, which is a provisioning precondition, not
//!     a retryable error (see [`crate::error::LicenseAuthCode`]).
//! - ⚠️ Policy-create defaults reference **non-existent** enum variants:
//!   new policies default `overage_strategy` to `"DENY_ACCESS"` (not a real
//!   `OverageStrategy` variant — silently behaves as `NO_OVERAGE`) and
//!   `heartbeat_resurrection_strategy` to `"NO_RESURRECTION"` (not a real
//!   variant — silently behaves as `NO_REVIVE`). Do not trust a freshly
//!   created policy's declared default string; treat unrecognized values as
//!   the "no restriction" variant to match actual server behavior.
//! - `Policy` full field set: `max_machines`, `max_cores`, `max_memory`,
//!   `max_disk`, `max_processes`, `max_uses`, `overage_strategy`,
//!   `heartbeat_cull_strategy`, `heartbeat_resurrection_strategy`,
//!   `heartbeat_duration`, `require_check_in`, `check_in_interval`,
//!   `expiration_strategy`, `renewal_basis`, `authentication_strategy`,
//!   `scheme`. The `GET` response **omits `max_memory` and `max_disk`** even
//!   though both are enforced during validation — model both as
//!   `Option<i64>` and expect `None` from the server today; the SDK cannot
//!   introspect these two limits client-side, only observe
//!   `TOO_MUCH_MEMORY`/`TOO_MUCH_DISK` on a failed validation.

/// The machine heartbeat window the server applies when
/// `policy.heartbeat_duration` is null: **600 seconds**.
///
/// This is a fallback, not the window. `Policy::effective_heartbeat_duration_secs`
/// (`tamga-api/src/features/policies/model.rs:262-264`) returns the policy's
/// value whenever it is set, and the cull job's claim query selects on
/// `COALESCE(p.heartbeat_duration, 600)`. A client that hardcodes this number
/// under a policy asking for less pings too slowly and its machines go
/// [`crate::models::machine::HeartbeatStatus::Dead`] on schedule.
///
/// Read the real window with
/// [`crate::Client::effective_heartbeat_window`] rather than assuming this.
pub const DEFAULT_HEARTBEAT_WINDOW_SECS: u64 = 600;

/// How many pings the recommended interval fits inside one heartbeat window:
/// **3**.
///
/// Three is the fleet-wide convention, and the margin is the point — two
/// consecutive lost pings (a throttled `429` and its retry, a network blip)
/// still leave one inside the window. At a divisor of 1 every single dropped
/// ping is a missed deadline.
pub const HEARTBEAT_INTERVAL_DIVISOR: u32 = 3;

/// Signing scheme used for license/machine checkout files and (always,
/// regardless of this value) machine offline proofs.
///
/// The wire field (`license.scheme`/`policy.scheme`) is `Option<String>` —
/// `None` or `""` means "legacy plain/unsigned key" and has **no**
/// corresponding variant here. When generating a **machine** file the
/// server defaults an unset scheme to [`LicenseScheme::Ed25519Sign`] on
/// machine check-out; callers of
/// [`crate::checkout::machine_file::verify_machine_file`] whose license
/// has no `scheme` set must pass `Ed25519Sign` to match, not skip
/// verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LicenseScheme {
    /// Ed25519 signature. The machine-file default when a license has no
    /// `scheme` set.
    Ed25519Sign,
    /// RSA-2048 PKCS#1 v1.5 / SHA-256.
    Rsa2048Pkcs1Sign,
    /// RSA-2048 PSS / SHA-256.
    Rsa2048Pkcs1PssSign,
    /// ECDSA P-256 / SHA-256 (ASN.1 DER signature).
    EcdsaP256Sign,
    /// RS256-signed JWT. **Not supported for machine file checkout** — the
    /// server returns `422 SCHEME_NOT_SUPPORTED`; a verifier must reject
    /// this scheme up front rather than attempt JWT parsing.
    Rsa2048JwtRs256,
}

impl LicenseScheme {
    /// Parses the wire string (`license.scheme`/`policy.scheme`, when
    /// `Some`). Returns `None` for an unrecognized string, mirroring the
    /// server's own `LicenseScheme::from_str` — this crate has no
    /// `Unknown` fallback variant for a scheme, since an unrecognized
    /// signing algorithm can't be dispatched to any verifier.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "ED25519_SIGN" => Some(LicenseScheme::Ed25519Sign),
            "RSA_2048_PKCS1_SIGN" => Some(LicenseScheme::Rsa2048Pkcs1Sign),
            "RSA_2048_PKCS1_PSS_SIGN" => Some(LicenseScheme::Rsa2048Pkcs1PssSign),
            "ECDSA_P256_SIGN" => Some(LicenseScheme::EcdsaP256Sign),
            "RSA_2048_JWT_RS256" => Some(LicenseScheme::Rsa2048JwtRs256),
            _ => None,
        }
    }
}

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

    #[test]
    fn parses_all_5_known_wire_strings() {
        assert_eq!(
            LicenseScheme::parse("ED25519_SIGN"),
            Some(LicenseScheme::Ed25519Sign)
        );
        assert_eq!(
            LicenseScheme::parse("RSA_2048_PKCS1_SIGN"),
            Some(LicenseScheme::Rsa2048Pkcs1Sign)
        );
        assert_eq!(
            LicenseScheme::parse("RSA_2048_PKCS1_PSS_SIGN"),
            Some(LicenseScheme::Rsa2048Pkcs1PssSign)
        );
        assert_eq!(
            LicenseScheme::parse("ECDSA_P256_SIGN"),
            Some(LicenseScheme::EcdsaP256Sign)
        );
        assert_eq!(
            LicenseScheme::parse("RSA_2048_JWT_RS256"),
            Some(LicenseScheme::Rsa2048JwtRs256)
        );
    }

    #[test]
    fn rejects_unrecognized_scheme_string() {
        assert_eq!(LicenseScheme::parse("BOGUS"), None);
        assert_eq!(LicenseScheme::parse(""), None);
    }
}

/// Overage handling for machine/core/memory/disk/process limits — how far
/// over `policy.max_*` a count is still permitted before validation fails
/// with the corresponding `TooMany*`/`TooMuch*`
/// [`crate::models::validation::ValidationCode`].
///
/// Multiplies the relevant limit before comparing; applies to
/// machines/cores/memory/disk/processes — **not** to `uses` (server always
/// enforces strict `count >= max_uses` for uses, regardless of strategy).
///
/// Deserializes any unrecognized wire value to [`OverageStrategy::NoOverage`]
/// rather than erroring — this mirrors the server's own fallback behavior
/// (`Policy::overage_strategy_parsed()`), which matters because
/// policy-create currently defaults new policies to the **non-existent**
/// string `"DENY_ACCESS"`; the server itself silently treats that as
/// `NoOverage`; an SDK that hard-fails on it would be stricter than the
/// server it's talking to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OverageStrategy {
    /// Enforce the limit strictly — no activations beyond max (`count <=
    /// max`). Also the fallback for any unrecognized wire value.
    NoOverage,
    /// Allow up to 125% of the limit (`count <= max * 1.25`).
    Allow1_25xOverage,
    /// Allow up to 150% of the limit (`count <= max * 1.5`).
    Allow1_5xOverage,
    /// Allow up to 200% of the limit (`count <= max * 2.0`).
    Allow2xOverage,
    /// Skip limit enforcement entirely — always allowed.
    AlwaysAllowOverage,
}

impl OverageStrategy {
    /// Returns whether `count` is permitted under this strategy given a
    /// `max` limit. Mirrors the server's own `OverageStrategy::allows`
    /// exactly (including its `f64` multiplication), so a caller
    /// client-side pre-check reaches the identical verdict.
    pub fn allows(self, count: i64, max: i64) -> bool {
        match self {
            OverageStrategy::NoOverage => count <= max,
            OverageStrategy::Allow1_25xOverage => (count as f64) <= (max as f64) * 1.25,
            OverageStrategy::Allow1_5xOverage => (count as f64) <= (max as f64) * 1.5,
            OverageStrategy::Allow2xOverage => (count as f64) <= (max as f64) * 2.0,
            OverageStrategy::AlwaysAllowOverage => true,
        }
    }
}

impl<'de> serde::Deserialize<'de> for OverageStrategy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(match s.as_str() {
            "NO_OVERAGE" => OverageStrategy::NoOverage,
            "ALLOW_1_25X_OVERAGE" => OverageStrategy::Allow1_25xOverage,
            "ALLOW_1_5X_OVERAGE" => OverageStrategy::Allow1_5xOverage,
            "ALLOW_2X_OVERAGE" => OverageStrategy::Allow2xOverage,
            "ALWAYS_ALLOW_OVERAGE" => OverageStrategy::AlwaysAllowOverage,
            _ => OverageStrategy::NoOverage,
        })
    }
}

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

    #[test]
    fn deserializes_all_5_known_wire_strings() {
        let cases = [
            ("\"NO_OVERAGE\"", OverageStrategy::NoOverage),
            (
                "\"ALLOW_1_25X_OVERAGE\"",
                OverageStrategy::Allow1_25xOverage,
            ),
            ("\"ALLOW_1_5X_OVERAGE\"", OverageStrategy::Allow1_5xOverage),
            ("\"ALLOW_2X_OVERAGE\"", OverageStrategy::Allow2xOverage),
            (
                "\"ALWAYS_ALLOW_OVERAGE\"",
                OverageStrategy::AlwaysAllowOverage,
            ),
        ];
        for (wire, expected) in cases {
            let parsed: OverageStrategy = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, expected, "wire value {wire}");
        }
    }

    #[test]
    fn falls_back_to_no_overage_for_unrecognized_value() {
        // Reproduces the real "DENY_ACCESS" policy-create-default gotcha.
        let parsed: OverageStrategy = serde_json::from_str("\"DENY_ACCESS\"").unwrap();
        assert_eq!(parsed, OverageStrategy::NoOverage);
    }

    #[test]
    fn no_overage_blocks_at_max_plus_one() {
        assert!(!OverageStrategy::NoOverage.allows(11, 10));
        assert!(OverageStrategy::NoOverage.allows(10, 10));
    }

    #[test]
    fn allow_1_25x_permits_within_allowance_and_blocks_excess() {
        assert!(OverageStrategy::Allow1_25xOverage.allows(12, 10));
        assert!(!OverageStrategy::Allow1_25xOverage.allows(13, 10));
    }

    #[test]
    fn allow_1_5x_permits_within_allowance() {
        assert!(OverageStrategy::Allow1_5xOverage.allows(15, 10));
    }

    #[test]
    fn allow_2x_permits_within_allowance() {
        assert!(OverageStrategy::Allow2xOverage.allows(20, 10));
    }

    #[test]
    fn always_allow_permits_any_count() {
        assert!(OverageStrategy::AlwaysAllowOverage.allows(9999, 1));
    }
}

/// What happens to a machine row once its heartbeat window elapses — **but
/// only on a policy that sets [`PolicyAttributes::require_heartbeat`]**.
///
/// ⚠️ That column is `NOT NULL DEFAULT FALSE`, and the cull job both
/// early-returns on `!require_heartbeat` and never claims a machine whose
/// policy has it unset. Under a default policy this enum decides nothing: no
/// row is ever culled, whichever value it carries. Reading `DEACTIVATE_DEAD`
/// off a policy is therefore *not* evidence that a
/// [`crate::models::machine::HeartbeatStatus::Dead`] machine has been or will
/// be removed — check `require_heartbeat` first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum HeartbeatCullStrategy {
    /// The machine row is deleted once dead — if, and only if, the policy
    /// also sets `require_heartbeat`.
    DeactivateDead,
    /// The dead machine row is kept — the license owner can still see it.
    KeepDead,
}

/// How long after heartbeat expiry a dead machine may still be revived by a
/// new ping, before [`HeartbeatCullStrategy`] takes effect.
///
/// Deserializes any unrecognized wire value to
/// [`HeartbeatResurrectionStrategy::NoRevive`] rather than erroring — same
/// rationale as [`OverageStrategy`]'s fallback: freshly-created policies
/// currently default this field to the **non-existent** string
/// `"NO_RESURRECTION"`, which the server itself silently treats as
/// `NoRevive`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeartbeatResurrectionStrategy {
    /// Resurrection never allowed. Also the fallback for any unrecognized
    /// wire value (including the real-world `"NO_RESURRECTION"` default
    /// bug).
    NoRevive,
    /// Revivable within 1 minute of expiry.
    OneMinuteRevive,
    /// Revivable within 2 minutes of expiry.
    TwoMinuteRevive,
    /// Revivable within 5 minutes of expiry.
    FiveMinuteRevive,
    /// Revivable within 10 minutes of expiry.
    TenMinuteRevive,
    /// Revivable within 15 minutes of expiry.
    FifteenMinuteRevive,
    /// Always revivable, regardless of how long dead.
    AlwaysRevive,
}

impl<'de> serde::Deserialize<'de> for HeartbeatResurrectionStrategy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(match s.as_str() {
            "NO_REVIVE" => HeartbeatResurrectionStrategy::NoRevive,
            "1_MINUTE_REVIVE" => HeartbeatResurrectionStrategy::OneMinuteRevive,
            "2_MINUTE_REVIVE" => HeartbeatResurrectionStrategy::TwoMinuteRevive,
            "5_MINUTE_REVIVE" => HeartbeatResurrectionStrategy::FiveMinuteRevive,
            "10_MINUTE_REVIVE" => HeartbeatResurrectionStrategy::TenMinuteRevive,
            "15_MINUTE_REVIVE" => HeartbeatResurrectionStrategy::FifteenMinuteRevive,
            "ALWAYS_REVIVE" => HeartbeatResurrectionStrategy::AlwaysRevive,
            _ => HeartbeatResurrectionStrategy::NoRevive,
        })
    }
}

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

    #[test]
    fn cull_strategy_deserializes_both_known_wire_strings() {
        let deactivate: HeartbeatCullStrategy =
            serde_json::from_str("\"DEACTIVATE_DEAD\"").unwrap();
        assert_eq!(deactivate, HeartbeatCullStrategy::DeactivateDead);
        let keep: HeartbeatCullStrategy = serde_json::from_str("\"KEEP_DEAD\"").unwrap();
        assert_eq!(keep, HeartbeatCullStrategy::KeepDead);
    }

    #[test]
    fn resurrection_strategy_deserializes_all_7_known_wire_strings() {
        let cases = [
            ("\"NO_REVIVE\"", HeartbeatResurrectionStrategy::NoRevive),
            (
                "\"1_MINUTE_REVIVE\"",
                HeartbeatResurrectionStrategy::OneMinuteRevive,
            ),
            (
                "\"2_MINUTE_REVIVE\"",
                HeartbeatResurrectionStrategy::TwoMinuteRevive,
            ),
            (
                "\"5_MINUTE_REVIVE\"",
                HeartbeatResurrectionStrategy::FiveMinuteRevive,
            ),
            (
                "\"10_MINUTE_REVIVE\"",
                HeartbeatResurrectionStrategy::TenMinuteRevive,
            ),
            (
                "\"15_MINUTE_REVIVE\"",
                HeartbeatResurrectionStrategy::FifteenMinuteRevive,
            ),
            (
                "\"ALWAYS_REVIVE\"",
                HeartbeatResurrectionStrategy::AlwaysRevive,
            ),
        ];
        for (wire, expected) in cases {
            let parsed: HeartbeatResurrectionStrategy = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, expected, "wire value {wire}");
        }
    }

    #[test]
    fn resurrection_strategy_falls_back_to_no_revive_for_unrecognized_value() {
        // Reproduces the real "NO_RESURRECTION" policy-create-default gotcha.
        let parsed: HeartbeatResurrectionStrategy =
            serde_json::from_str("\"NO_RESURRECTION\"").unwrap();
        assert_eq!(parsed, HeartbeatResurrectionStrategy::NoRevive);
    }
}

/// Check-in cadence unit. ⚠️ Wire values are **lowercase** — the one casing
/// exception among this crate's `SCREAMING_SNAKE_CASE` enums.
///
/// ⚠️ **Two lowercase spellings exist and only one of them is storable.**
/// The `policies.check_in_interval` column carries a `CHECK` constraint
/// admitting exactly `'daily'`, `'weekly'`, `'monthly'`, `'yearly'`
/// (`migrations/20240101000005_create_products_and_policies.sql:152-155`),
/// and both `create_policy` and `update_policy` validate against the same
/// four via `policies::enums::CHECK_IN_INTERVALS`. **Those adverb forms are
/// what a `GET` returns.** The server's own overdue calculation
/// (`licenses/validate_license.rs:394-400`) nevertheless matches on the bare
/// nouns `"day"`/`"week"`/`"month"`/`"year"`, which the constraint makes
/// unstorable, so every configured interval falls through its `_ => 30`
/// default — reported upstream; the SDK cannot fix it.
///
/// Both spellings therefore deserialize here. Modelling only the nouns (as
/// this crate did before the policy read routes existed) would have made
/// every real policy with a check-in cadence set fail to decode *as a whole
/// resource*, since a closed enum inside `Option<T>` errors rather than
/// yielding `None`.
///
/// A value that is neither spelling still fails. That is the residual gap: it
/// cannot be closed without adding a variant, and this enum is public and
/// exhaustive, so a new variant would be a breaking change. Callers reading a
/// policy from a future server that adds a fifth cadence should be ready for
/// a [`crate::TamgaError::Json`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckInInterval {
    /// `"daily"` (server-storable) or `"day"`.
    Day,
    /// `"weekly"` (server-storable) or `"week"`.
    Week,
    /// `"monthly"` (server-storable) or `"month"`.
    Month,
    /// `"yearly"` (server-storable) or `"year"`.
    Year,
}

impl CheckInInterval {
    /// The spelling the server actually stores and returns: `"daily"`,
    /// `"weekly"`, `"monthly"`, `"yearly"`.
    pub fn as_str(self) -> &'static str {
        match self {
            CheckInInterval::Day => "daily",
            CheckInInterval::Week => "weekly",
            CheckInInterval::Month => "monthly",
            CheckInInterval::Year => "yearly",
        }
    }
}

impl<'de> serde::Deserialize<'de> for CheckInInterval {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "daily" | "day" => Ok(CheckInInterval::Day),
            "weekly" | "week" => Ok(CheckInInterval::Week),
            "monthly" | "month" => Ok(CheckInInterval::Month),
            "yearly" | "year" => Ok(CheckInInterval::Year),
            other => Err(serde::de::Error::custom(format!(
                "unknown check_in_interval {other:?}: expected one of \
                 daily/weekly/monthly/yearly"
            ))),
        }
    }
}

/// A free-text policy field the server branches on via literal string
/// match rather than a closed enum server-side. Modeled as an open string
/// newtype (not a closed enum) with named associated constants for the
/// documented known values — an unrecognized value deserializes fine (it's
/// just a `String`) rather than failing, since the server itself doesn't
/// validate these against a fixed set either.
macro_rules! free_text_policy_field {
    ($name:ident { $($const_name:ident = $wire:literal),+ $(,)? }) => {
        #[doc = concat!("Open string newtype for the `", stringify!($name), "` policy field — see the macro's own doc comment above for the general rationale.")]
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        #[serde(transparent)]
        pub struct $name(
            /// The raw wire string — may be any value, not just the named
            /// associated constants below.
            pub String,
        );

        impl $name {
            $(
                #[doc = concat!("`\"", $wire, "\"`.")]
                pub const $const_name: &'static str = $wire;
            )+

            /// Borrows the wire string form.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }
    };
}

free_text_policy_field!(ExpirationStrategy {
    RESTRICT_ACCESS = "RESTRICT_ACCESS",
    MAINTAIN_ACCESS = "MAINTAIN_ACCESS",
    ALLOW_ACCESS = "ALLOW_ACCESS",
    REVOKE_ACCESS = "REVOKE_ACCESS",
});

free_text_policy_field!(RenewalBasis {
    FROM_EXPIRY = "FROM_EXPIRY",
    FROM_NOW = "FROM_NOW",
});

free_text_policy_field!(AuthenticationStrategy {
    TOKEN = "TOKEN",
    LICENSE = "LICENSE",
    MIXED = "MIXED",
    NONE = "NONE",
});

/// The `policies` JSON:API resource: `{ id, type, attributes }`. Field set
/// matches the Tamga API's actual `PolicyResource`/`PolicyAttributes`
/// serializer exactly — several fields here (`product_id`, `duration`,
/// `expiration_basis`, `machine_uniqueness_strategy`, `use_pool`,
/// `protected`, `check_in_interval_count`, `require_heartbeat`,
/// `max_users`) are omitted from abbreviated summaries of the policy
/// resource, but they are real server fields and were verified against the
/// server's own policy serializer.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Policy {
    /// UUIDv7 policy ID.
    pub id: uuid::Uuid,
    /// Always `"policies"`.
    #[serde(rename = "type")]
    pub resource_type: String,
    /// The resource's attribute bag.
    pub attributes: PolicyAttributes,
}

/// Attributes of a [`Policy`].
///
/// ⚠️ The `GET` response **omits `max_memory` and `max_disk`** even though
/// both are enforced during validation (see
/// [`crate::models::validation::ValidationCode::TooMuchMemory`]/
/// [`crate::models::validation::ValidationCode::TooMuchDisk`]) — confirmed
/// absent from the server's own `PolicyAttributes` struct, not merely
/// `None`-valued. This SDK cannot introspect these two limits client-side
/// at all; only observe the corresponding `ValidationCode` on a failed
/// validation.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PolicyAttributes {
    /// The product this policy belongs to.
    pub product_id: String,
    /// Display name.
    pub name: String,
    /// Default license duration in seconds, if set.
    pub duration: Option<i64>,
    /// Strict mode flag (server-side semantics not yet SDK-relevant).
    pub strict: bool,
    /// Floating license flag (server-side semantics not yet SDK-relevant).
    pub floating: bool,
    /// Signing scheme — see [`LicenseScheme`]. `None`/absent means legacy
    /// plain/unsigned key.
    pub scheme: Option<String>,
    /// Whether checkout files are encrypted by default under this policy.
    pub encrypted: bool,
    /// Use-pool flag (server-side semantics not yet SDK-relevant).
    pub use_pool: bool,
    /// Whether checkout/download of a license's key is protected under
    /// this policy.
    pub protected: bool,
    /// Whether licenses under this policy must periodically check in.
    pub require_check_in: bool,
    /// Check-in cadence unit — see [`CheckInInterval`].
    pub check_in_interval: Option<CheckInInterval>,
    /// Check-in cadence multiplier (e.g. `2` + `Week` = every 2 weeks).
    pub check_in_interval_count: Option<i32>,
    /// Whether machines under this policy must send heartbeats.
    ///
    /// ⚠️ Also the master switch for culling. The server's heartbeat worker
    /// refuses to claim or process a machine whose policy leaves this
    /// `false` — the default — so under such a policy
    /// [`HeartbeatCullStrategy`] is inert and a
    /// [`crate::models::machine::HeartbeatStatus::Dead`] machine keeps its
    /// row and its seat indefinitely.
    pub require_heartbeat: bool,
    /// Heartbeat window in seconds. **This drives the machine heartbeat
    /// window**: the server uses this value when set and falls back to 600s
    /// (10 min) only when it is null — `effective_window_secs` prefers it,
    /// and the cull job's claim query selects on
    /// `COALESCE(p.heartbeat_duration, 600)`.
    ///
    /// Read it directly with [`crate::Client::get_license_policy`], or take
    /// the derived numbers from [`PolicyAttributes::effective_heartbeat_window`]
    /// and [`crate::Client::recommended_heartbeat_interval`]. The licence
    /// resource still carries no policy relationship, so the *licence* id is
    /// the way in — `GET /licenses/{id}/policy`, not `GET /policies/{id}`,
    /// which a licence key lacks the `policy.read` permission for.
    ///
    /// It is also observable indirectly, on any response the server built
    /// from a policy-joined read: `next_heartbeat_at - last_heartbeat_at` via
    /// [`crate::models::machine::MachineAttributes::observed_heartbeat_window`].
    /// The write responses (create, ping-heartbeat, reset-heartbeat) carry
    /// the 600s fallback instead and will not reveal it.
    /// See [`crate::models::machine::HeartbeatStatus`]'s doc comment.
    ///
    /// Processes are unaffected: their window is a separate hardcoded 30s
    /// that this field never touches, and it is inert regardless since no
    /// live code path evaluates a process heartbeat at all (see
    /// [`crate::models::machine::Pid`]).
    pub heartbeat_duration: Option<i32>,
    /// ⚠️ Deserialize with [`HeartbeatCullStrategy`] yourself if needed —
    /// kept as a raw `String` here (matching the server's own
    /// `PolicyAttributes.heartbeat_cull_strategy: String` field type)
    /// rather than the typed enum, since unlike
    /// `heartbeat_resurrection_strategy` this field has no documented
    /// invalid-default gotcha requiring lenient fallback parsing at the
    /// `Policy`-deserialization boundary.
    pub heartbeat_cull_strategy: String,
    /// ⚠️ Freshly-created policies default this to the **non-existent**
    /// string `"NO_RESURRECTION"` — kept as a raw `String` here rather than
    /// the typed [`HeartbeatResurrectionStrategy`] enum so a `Policy`
    /// fetch never fails to deserialize on that known-bogus value; parse it
    /// with `HeartbeatResurrectionStrategy`'s own lenient `Deserialize`
    /// (which already falls back to `NoRevive`) when you need the typed
    /// form.
    pub heartbeat_resurrection_strategy: String,
    /// Whether machine fingerprints must be unique per-license or
    /// per-account (server-side semantics not yet SDK-relevant beyond the
    /// `FINGERPRINT_TAKEN` conflict this SDK already models).
    pub machine_uniqueness_strategy: String,
    /// See [`ExpirationStrategy`]. Default `"RESTRICT_ACCESS"`. Only
    /// `"REVOKE_ACCESS"` stops an expired licence from authenticating at
    /// all.
    pub expiration_strategy: ExpirationStrategy,
    /// What a license's expiry is computed relative to (server-side
    /// semantics not yet SDK-relevant).
    pub expiration_basis: String,
    /// See [`RenewalBasis`]. Default `"FROM_EXPIRY"`.
    pub renewal_basis: RenewalBasis,
    /// See [`AuthenticationStrategy`]. Default `"TOKEN"`, under which
    /// licence-key auth is **refused** — only `"LICENSE"` and `"MIXED"`
    /// accept a licence key. `"NONE"` refuses it too.
    pub authentication_strategy: AuthenticationStrategy,
    /// ⚠️ Freshly-created policies default this to the **non-existent**
    /// string `"DENY_ACCESS"` — same rationale as
    /// `heartbeat_resurrection_strategy` above: kept as a raw `String`,
    /// parse with [`OverageStrategy`]'s own lenient `Deserialize` (falls
    /// back to `NoOverage`) when you need the typed form.
    pub overage_strategy: String,
    /// Machine activation limit, if set.
    pub max_machines: Option<i32>,
    /// Total CPU core limit across machines, if set.
    pub max_cores: Option<i32>,
    /// Use-count limit, if set (compared with strict `>=`, ignoring
    /// `overage_strategy`).
    pub max_uses: Option<i32>,
    /// Total process limit across machines, if set.
    pub max_processes: Option<i32>,
    /// Associated-user limit, if set.
    pub max_users: Option<i32>,
    /// Arbitrary caller-set metadata.
    pub metadata: serde_json::Value,
    /// Creation timestamp.
    pub created: chrono::DateTime<chrono::Utc>,
    /// Last-updated timestamp.
    pub updated: chrono::DateTime<chrono::Utc>,
}

impl PolicyAttributes {
    /// The heartbeat window the server will actually judge this policy's
    /// machines against: `heartbeat_duration` when set, else
    /// [`DEFAULT_HEARTBEAT_WINDOW_SECS`].
    ///
    /// Mirrors `Policy::effective_heartbeat_duration_secs` server-side
    /// (`tamga-api/src/features/policies/model.rs:262-264`) exactly, including
    /// the fallback — this is the only client-side value that agrees with the
    /// cull job's `COALESCE(p.heartbeat_duration, 600)` by construction.
    ///
    /// ⚠️ A window says nothing about whether anything is *enforced*. Culling
    /// is gated on [`Self::require_heartbeat`], which is `NOT NULL DEFAULT
    /// FALSE`, so under a default policy a machine that misses this window
    /// reports `Dead` forever and is never removed.
    pub fn effective_heartbeat_window(&self) -> std::time::Duration {
        let secs = self
            .heartbeat_duration
            .filter(|secs| *secs > 0)
            .map(|secs| secs as u64)
            .unwrap_or(DEFAULT_HEARTBEAT_WINDOW_SECS);
        std::time::Duration::from_secs(secs)
    }

    /// [`Self::effective_heartbeat_window`] divided by
    /// [`HEARTBEAT_INTERVAL_DIVISOR`] — the ping interval to schedule.
    ///
    /// 200s under the 600s fallback. Never zero: a policy configured with a
    /// window shorter than the divisor still yields a 1-second interval
    /// rather than a timer that fires continuously.
    pub fn recommended_heartbeat_interval(&self) -> std::time::Duration {
        let window = self.effective_heartbeat_window();
        std::cmp::max(
            window / HEARTBEAT_INTERVAL_DIVISOR,
            std::time::Duration::from_secs(1),
        )
    }
}

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

    fn representative_policy_json() -> serde_json::Value {
        serde_json::json!({
            "type": "policies",
            "id": "01926b3e-0000-7000-8000-000000000000",
            "attributes": {
                "product_id": "01926b3e-1111-7000-8000-000000000000",
                "name": "Default", "duration": null, "strict": false, "floating": false,
                "scheme": null, "encrypted": false, "use_pool": false, "protected": false,
                "require_check_in": false, "check_in_interval": null,
                "check_in_interval_count": null, "require_heartbeat": false,
                "heartbeat_duration": null,
                "heartbeat_cull_strategy": "DEACTIVATE_DEAD",
                "heartbeat_resurrection_strategy": "NO_RESURRECTION",
                "machine_uniqueness_strategy": "UNIQUE_PER_LICENSE",
                "expiration_strategy": "RESTRICT_ACCESS", "expiration_basis": "FROM_CREATION",
                "renewal_basis": "FROM_EXPIRY", "authentication_strategy": "TOKEN",
                "overage_strategy": "DENY_ACCESS",
                "max_machines": null, "max_cores": null, "max_uses": null,
                "max_processes": null, "max_users": null, "metadata": {},
                "created": "2026-01-01T00:00:00Z", "updated": "2026-01-01T00:00:00Z",
            }
        })
    }

    #[test]
    fn deserializes_a_representative_policy_with_the_real_bogus_defaults() {
        let json = serde_json::json!({
            "type": "policies",
            "id": "01926b3e-0000-7000-8000-000000000000",
            "attributes": {
                "product_id": "01926b3e-1111-7000-8000-000000000000",
                "name": "Default", "duration": null, "strict": false, "floating": false,
                "scheme": null, "encrypted": false, "use_pool": false, "protected": false,
                "require_check_in": false, "check_in_interval": null,
                "check_in_interval_count": null, "require_heartbeat": false,
                "heartbeat_duration": null,
                "heartbeat_cull_strategy": "DEACTIVATE_DEAD",
                "heartbeat_resurrection_strategy": "NO_RESURRECTION",
                "machine_uniqueness_strategy": "UNIQUE_PER_LICENSE",
                "expiration_strategy": "RESTRICT_ACCESS", "expiration_basis": "FROM_CREATION",
                "renewal_basis": "FROM_EXPIRY", "authentication_strategy": "TOKEN",
                "overage_strategy": "DENY_ACCESS",
                "max_machines": null, "max_cores": null, "max_uses": null,
                "max_processes": null, "max_users": null, "metadata": {},
                "created": "2026-01-01T00:00:00Z", "updated": "2026-01-01T00:00:00Z",
            }
        });
        let policy: Policy = serde_json::from_value(json).unwrap();
        // The known-bogus defaults deserialize fine as raw strings...
        assert_eq!(policy.attributes.overage_strategy, "DENY_ACCESS");
        assert_eq!(
            policy.attributes.heartbeat_resurrection_strategy,
            "NO_RESURRECTION"
        );
        // ...and parsing them through the typed enums' own lenient
        // Deserialize falls back to the safe "no restriction" variant.
        let overage: OverageStrategy =
            serde_json::from_str(&format!("\"{}\"", policy.attributes.overage_strategy)).unwrap();
        assert_eq!(overage, OverageStrategy::NoOverage);
    }

    #[test]
    fn check_in_interval_deserializes_lowercase_wire_values() {
        for (wire, expected) in [
            ("\"day\"", CheckInInterval::Day),
            ("\"week\"", CheckInInterval::Week),
            ("\"month\"", CheckInInterval::Month),
            ("\"year\"", CheckInInterval::Year),
        ] {
            let parsed: CheckInInterval = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, expected, "wire value {wire}");
        }
    }

    #[test]
    fn check_in_interval_deserializes_the_adverb_spellings_the_server_stores() {
        // These are the only four the `policies.check_in_interval` CHECK
        // constraint admits, so these are what a GET actually returns. The
        // noun forms above are what the server's own overdue calculation
        // matches on and can never see.
        for (wire, expected) in [
            ("\"daily\"", CheckInInterval::Day),
            ("\"weekly\"", CheckInInterval::Week),
            ("\"monthly\"", CheckInInterval::Month),
            ("\"yearly\"", CheckInInterval::Year),
        ] {
            let parsed: CheckInInterval = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, expected, "wire value {wire}");
            assert_eq!(format!("\"{}\"", expected.as_str()), wire);
        }
    }

    #[test]
    fn a_policy_carrying_a_real_check_in_interval_decodes_as_a_whole_resource() {
        // Regression: modelling only "day"/"week"/… made a closed enum inside
        // `Option<CheckInInterval>` fail the *entire* Policy deserialization
        // for every policy with a check-in cadence configured — the read
        // routes would have been unusable against a real server.
        let mut json = representative_policy_json();
        json["attributes"]["check_in_interval"] = serde_json::json!("weekly");
        json["attributes"]["check_in_interval_count"] = serde_json::json!(2);
        let policy: Policy = serde_json::from_value(json).unwrap();
        assert_eq!(
            policy.attributes.check_in_interval,
            Some(CheckInInterval::Week)
        );
        assert_eq!(policy.attributes.check_in_interval_count, Some(2));
    }

    #[test]
    fn an_unrecognized_check_in_interval_is_reported_not_silently_dropped() {
        let parsed: Result<CheckInInterval, _> = serde_json::from_str("\"fortnightly\"");
        assert!(parsed.is_err());
    }

    #[test]
    fn effective_heartbeat_window_falls_back_to_600s_only_when_unset() {
        let mut json = representative_policy_json();
        let policy: Policy = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(
            policy.attributes.effective_heartbeat_window(),
            std::time::Duration::from_secs(600)
        );
        assert_eq!(
            policy.attributes.recommended_heartbeat_interval(),
            std::time::Duration::from_secs(200)
        );

        json["attributes"]["heartbeat_duration"] = serde_json::json!(90);
        let policy: Policy = serde_json::from_value(json).unwrap();
        assert_eq!(
            policy.attributes.effective_heartbeat_window(),
            std::time::Duration::from_secs(90)
        );
        assert_eq!(
            policy.attributes.recommended_heartbeat_interval(),
            std::time::Duration::from_secs(30)
        );
    }

    #[test]
    fn a_degenerate_heartbeat_duration_never_yields_a_zero_interval() {
        let mut json = representative_policy_json();
        // A timer built from a zero interval spins; a non-positive column
        // value is treated as unset, matching how the crate handles a
        // non-positive interval everywhere else.
        json["attributes"]["heartbeat_duration"] = serde_json::json!(0);
        let policy: Policy = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(
            policy.attributes.effective_heartbeat_window(),
            std::time::Duration::from_secs(600)
        );

        json["attributes"]["heartbeat_duration"] = serde_json::json!(2);
        let policy: Policy = serde_json::from_value(json).unwrap();
        assert_eq!(
            policy.attributes.recommended_heartbeat_interval(),
            std::time::Duration::from_secs(1)
        );
    }

    #[test]
    fn free_text_fields_accept_unrecognized_values_without_erroring() {
        // These are open string newtypes precisely because the server
        // doesn't validate against a fixed set either — an unrecognized
        // value must deserialize successfully, not fail.
        let strategy: ExpirationStrategy = serde_json::from_str("\"SOME_FUTURE_VALUE\"").unwrap();
        assert_eq!(strategy.as_str(), "SOME_FUTURE_VALUE");
    }

    #[test]
    fn free_text_field_constants_match_documented_values() {
        assert_eq!(ExpirationStrategy::RESTRICT_ACCESS, "RESTRICT_ACCESS");
        assert_eq!(ExpirationStrategy::MAINTAIN_ACCESS, "MAINTAIN_ACCESS");
        assert_eq!(ExpirationStrategy::ALLOW_ACCESS, "ALLOW_ACCESS");
        assert_eq!(ExpirationStrategy::REVOKE_ACCESS, "REVOKE_ACCESS");
        assert_eq!(RenewalBasis::FROM_EXPIRY, "FROM_EXPIRY");
        assert_eq!(RenewalBasis::FROM_NOW, "FROM_NOW");
        assert_eq!(AuthenticationStrategy::TOKEN, "TOKEN");
        assert_eq!(AuthenticationStrategy::LICENSE, "LICENSE");
        assert_eq!(AuthenticationStrategy::MIXED, "MIXED");
        assert_eq!(AuthenticationStrategy::NONE, "NONE");
    }
}