tandem-server 0.7.1

HTTP server for Tandem engine APIs
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
// Copyright (c) 2026 Frumu LTD
// Licensed under the Business Source License 1.1

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::json;
use tandem_channels::channel_registry::{command_tier_for_profile, CommandTier};
use tandem_channels::config::ChannelSecurityProfile;
use tandem_types::EngineEvent;
use uuid::Uuid;

use crate::app::state::AppState;

const DEFAULT_ENROLLMENT_TTL_MS: u64 = 10 * 60 * 1000;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChannelUserCapabilityRecord {
    pub channel: String,
    pub user_id: String,
    pub max_tier: StoredCommandTier,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enrolled_at_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enrolled_by: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pinned_workspace_id: Option<String>,
    /// TAN-765: org units (departments) this enrollment established
    /// memberships in, recorded for audit/display. The authoritative
    /// membership rows live in the enterprise org-unit store.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub org_units: Vec<String>,
    /// Tenant this capability is scoped to (copied from the pairing code).
    /// A tenant-scoped grant only counts on connections bound to the SAME
    /// tenant — a code issued for tenant A must not confer the Approve tier
    /// on tenant B's channels just because the Slack principal string
    /// matches. Absent on legacy records, which stay channel-global.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_org_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_workspace_id: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum StoredCommandTier {
    Read,
    Act,
    Approve,
    Reconfigure,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChannelEnrollmentCodeRecord {
    pub code: String,
    pub channel: String,
    pub user_id: String,
    pub max_tier: StoredCommandTier,
    pub issued_at_ms: u64,
    pub expires_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issued_by: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pinned_workspace_id: Option<String>,
    /// TAN-765: org units (departments) to bind on redemption. Entries match
    /// a unit's bare id (`engineering`) or principal id
    /// (`department/engineering`); redeeming establishes active org-unit
    /// memberships for the enrolled identity, not just an approval tier.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub org_units: Vec<String>,
    /// Tenant the `org_units` refs resolve in. Set together; when present,
    /// redemption only matches units bound to this tenant, so a shared unit
    /// name in another tenant can never satisfy this code's binding.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_org_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_workspace_id: Option<String>,
}

impl From<CommandTier> for StoredCommandTier {
    fn from(value: CommandTier) -> Self {
        match value {
            CommandTier::Read => Self::Read,
            CommandTier::Act => Self::Act,
            CommandTier::Approve => Self::Approve,
            CommandTier::Reconfigure => Self::Reconfigure,
        }
    }
}

impl From<StoredCommandTier> for CommandTier {
    fn from(value: StoredCommandTier) -> Self {
        match value {
            StoredCommandTier::Read => Self::Read,
            StoredCommandTier::Act => Self::Act,
            StoredCommandTier::Approve => Self::Approve,
            StoredCommandTier::Reconfigure => Self::Reconfigure,
        }
    }
}

impl AppState {
    #[allow(clippy::too_many_arguments)]
    pub async fn issue_channel_enrollment_code(
        &self,
        channel: impl Into<String>,
        user_id: impl Into<String>,
        max_tier: StoredCommandTier,
        ttl_ms: Option<u64>,
        issued_by: Option<String>,
        pinned_workspace_id: Option<String>,
        org_units: Vec<String>,
        tenant: Option<(String, String)>,
    ) -> anyhow::Result<ChannelEnrollmentCodeRecord> {
        let org_units = normalize_org_unit_refs(org_units);
        // Fail fast on typos: every referenced unit must exist at issue time
        // — within the enrollment's tenant when one is given, and rejecting
        // cross-tenant-ambiguous refs otherwise — so the operator learns
        // immediately rather than the redeeming user hitting a dead code.
        self.resolve_org_unit_refs(
            &org_units,
            tenant
                .as_ref()
                .map(|(org_id, workspace_id)| (org_id.as_str(), workspace_id.as_str())),
        )
        .await?;
        let issued_at_ms = crate::now_ms();
        let expires_at_ms =
            issued_at_ms.saturating_add(ttl_ms.unwrap_or(DEFAULT_ENROLLMENT_TTL_MS));
        let code = Uuid::new_v4()
            .simple()
            .to_string()
            .chars()
            .take(8)
            .collect::<String>()
            .to_ascii_uppercase();
        let record = ChannelEnrollmentCodeRecord {
            code: code.clone(),
            channel: channel.into(),
            user_id: user_id.into(),
            max_tier,
            issued_at_ms,
            expires_at_ms,
            issued_by,
            pinned_workspace_id,
            org_units,
            tenant_org_id: tenant.as_ref().map(|(org_id, _)| org_id.clone()),
            tenant_workspace_id: tenant.map(|(_, workspace_id)| workspace_id),
        };
        self.channel_enrollment_codes
            .write()
            .await
            .insert(code, record.clone());
        Ok(record)
    }

    pub async fn confirm_channel_enrollment_code(
        &self,
        code: &str,
        enrolled_by: Option<String>,
    ) -> anyhow::Result<ChannelUserCapabilityRecord> {
        let key = normalize_enrollment_code(code);
        let pending = {
            let mut guard = self.channel_enrollment_codes.write().await;
            guard.remove(&key)
        }
        .ok_or_else(|| anyhow::anyhow!("pairing code not found"))?;

        if pending.expires_at_ms < crate::now_ms() {
            return Err(anyhow::anyhow!("pairing code expired"));
        }

        // TAN-765: establish the department memberships BEFORE the capability
        // grant so a failure here leaves no partial authority. The code is
        // already consumed either way — a failed binding needs a fresh code.
        if !pending.org_units.is_empty() {
            let tenant = match (&pending.tenant_org_id, &pending.tenant_workspace_id) {
                (Some(org_id), Some(workspace_id)) => {
                    Some((org_id.as_str(), workspace_id.as_str()))
                }
                _ => None,
            };
            self.grant_org_unit_memberships_for_principal(
                &pending.user_id,
                &pending.org_units,
                tenant,
            )
            .await?;
        }

        let record = ChannelUserCapabilityRecord {
            channel: pending.channel,
            user_id: pending.user_id,
            max_tier: pending.max_tier,
            enrolled_at_ms: Some(crate::now_ms()),
            enrolled_by: enrolled_by.or(pending.issued_by),
            pinned_workspace_id: pending.pinned_workspace_id,
            org_units: pending.org_units,
            tenant_org_id: pending.tenant_org_id,
            tenant_workspace_id: pending.tenant_workspace_id,
        };
        self.upsert_channel_user_capability(record.clone()).await?;
        Ok(record)
    }

    /// Resolve org-unit references (bare unit id or `taxonomy/unit_id`
    /// principal id) against the enterprise org-unit store. Errors on any
    /// unknown reference. Ambiguity is always REJECTED, never resolved to an
    /// arbitrary unit: without a `tenant` scope, a ref matching units in
    /// more than one tenant fails (enrolling a sender must never grant
    /// authority in a different tenant); and even inside one tenant a bare
    /// unit id matching several taxonomies (`department/sales` vs
    /// `region/sales`) fails until the caller uses the taxonomy-qualified
    /// principal id.
    pub async fn resolve_org_unit_refs(
        &self,
        refs: &[String],
        tenant: Option<(&str, &str)>,
    ) -> anyhow::Result<Vec<tandem_enterprise_contract::OrganizationUnit>> {
        let units = self.enterprise.org_units.read().await;
        refs.iter()
            .map(|entry| {
                let wanted = entry.trim();
                let matches = units
                    .values()
                    .filter(|unit| unit.unit_id == wanted || unit.principal_ref().id == wanted)
                    .filter(|unit| {
                        tenant.is_none_or(|(org_id, workspace_id)| {
                            unit.tenant_context.org_id == org_id
                                && unit.tenant_context.workspace_id == workspace_id
                        })
                    })
                    .collect::<Vec<_>>();
                let mut identities = matches
                    .iter()
                    .map(|unit| {
                        (
                            unit.tenant_context.org_id.as_str(),
                            unit.tenant_context.workspace_id.as_str(),
                            unit.principal_ref().id,
                        )
                    })
                    .collect::<Vec<_>>();
                identities.sort();
                identities.dedup();
                match identities.as_slice() {
                    [] => Err(anyhow::anyhow!("unknown org unit: {wanted}")),
                    [_] => Ok(matches[0].clone()),
                    many => {
                        let mut tenants = many
                            .iter()
                            .map(|(org_id, workspace_id, _)| (*org_id, *workspace_id))
                            .collect::<Vec<_>>();
                        tenants.sort();
                        tenants.dedup();
                        if tenants.len() > 1 {
                            Err(anyhow::anyhow!(
                                "org unit ref {wanted} is ambiguous across tenants; scope the enrollment to a tenant"
                            ))
                        } else {
                            let candidates = many
                                .iter()
                                .map(|(_, _, principal_id)| principal_id.clone())
                                .collect::<Vec<_>>()
                                .join(", ");
                            Err(anyhow::anyhow!(
                                "org unit ref {wanted} is ambiguous within the tenant (matches: {candidates}); use the taxonomy-qualified id"
                            ))
                        }
                    }
                }
            })
            .collect()
    }

    /// TAN-765: establish active org-unit memberships for a principal (e.g. a
    /// Slack identity `channel:slack:{team}:{app}:{user}`). Existing active
    /// memberships are kept as-is; new rows persist through the governance
    /// store. Returns the membership ids now in effect for the references.
    pub async fn grant_org_unit_memberships_for_principal(
        &self,
        member_id: &str,
        unit_refs: &[String],
        tenant: Option<(&str, &str)>,
    ) -> anyhow::Result<Vec<String>> {
        use tandem_types::{OrganizationUnitMembership, OrganizationUnitMembershipSource};

        let member_id = member_id.trim();
        anyhow::ensure!(!member_id.is_empty(), "member id must not be empty");
        let units = self.resolve_org_unit_refs(unit_refs, tenant).await?;
        let member = tandem_types::PrincipalRef::human_user(member_id);
        let now_ms = crate::now_ms();

        let mut effective_ids = Vec::new();
        {
            let mut registry = self.enterprise.org_unit_memberships.write().await;
            for unit in units {
                let unit_principal = unit.principal_ref();
                if let Some(existing) = registry.values().find(|membership| {
                    membership.state.is_active()
                        && membership.unit.id == unit_principal.id
                        && membership.member.id == member.id
                        && membership.tenant_context.org_id == unit.tenant_context.org_id
                        && membership.tenant_context.workspace_id
                            == unit.tenant_context.workspace_id
                }) {
                    effective_ids.push(existing.membership_id.clone());
                    continue;
                }
                let membership_id = format!(
                    "enrollment-{}-{}",
                    unit.unit_id,
                    Uuid::new_v4()
                        .simple()
                        .to_string()
                        .chars()
                        .take(8)
                        .collect::<String>()
                );
                let membership = OrganizationUnitMembership::active(
                    membership_id.clone(),
                    unit.tenant_context.clone(),
                    unit_principal,
                    member.clone(),
                    OrganizationUnitMembershipSource::Direct,
                    now_ms,
                );
                registry.insert(membership.membership_id.clone(), membership);
                effective_ids.push(membership_id);
            }
            self.persist_enterprise_org_unit_memberships_locked(&registry)
                .await?;
        }
        Ok(effective_ids)
    }

    /// Persist the org-unit membership registry through the governance store
    /// (encryption-aware), mirroring how the store is loaded at startup.
    async fn persist_enterprise_org_unit_memberships_locked(
        &self,
        registry: &HashMap<String, tandem_enterprise_contract::OrganizationUnitMembership>,
    ) -> anyhow::Result<()> {
        let records = registry
            .iter()
            .map(|(key, row)| {
                crate::governance_store::GovernanceStoreFile::OrgUnitMemberships.json_record(
                    key,
                    row,
                    &row.tenant_context,
                    Some(&row.unit.id),
                )
            })
            .collect::<anyhow::Result<Vec<_>>>()?;
        crate::governance_store::for_state(self)
            .write_json_records(
                crate::governance_store::GovernanceStoreFile::OrgUnitMemberships,
                &records,
            )
            .await
    }

    pub async fn load_channel_user_capabilities(&self) -> anyhow::Result<()> {
        if !self.channel_user_capabilities_path.exists() {
            return Ok(());
        }
        let raw = tokio::fs::read_to_string(&self.channel_user_capabilities_path).await?;
        let parsed = serde_json::from_str::<HashMap<String, ChannelUserCapabilityRecord>>(&raw)
            .unwrap_or_default();
        *self.channel_user_capabilities.write().await = parsed;
        Ok(())
    }

    pub async fn persist_channel_user_capabilities(&self) -> anyhow::Result<()> {
        let payload = {
            let guard = self.channel_user_capabilities.read().await;
            serde_json::to_string_pretty(&*guard)?
        };
        if let Some(parent) = self.channel_user_capabilities_path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(&self.channel_user_capabilities_path, payload).await?;
        Ok(())
    }

    pub async fn upsert_channel_user_capability(
        &self,
        record: ChannelUserCapabilityRecord,
    ) -> anyhow::Result<()> {
        // Tenant-scoped grants live under a tenant-aware key so the same
        // Slack principal can hold separate grants in several tenants —
        // enrolling for tenant B must never clobber tenant A's grant.
        // Untenanted (legacy/global) grants keep the legacy key.
        let key = capability_storage_key(&record);
        self.channel_user_capabilities
            .write()
            .await
            .insert(key, record.clone());
        if let Some(runtime) = self.runtime.get() {
            runtime.event_bus.publish(EngineEvent::new(
                "channel.capability.changed",
                json!({
                    "channel": record.channel,
                    "user_id": record.user_id,
                    "max_tier": record.max_tier,
                    "actor_id": record.enrolled_by,
                    "executed_as": "channel_enrollment",
                    "workspace": record.pinned_workspace_id,
                }),
            ));
        }
        self.persist_channel_user_capabilities().await
    }

    pub async fn channel_user_capability_tier(
        &self,
        channel: &str,
        user_id: &str,
        fallback_profile: ChannelSecurityProfile,
    ) -> CommandTier {
        let key = channel_user_capability_key(channel, user_id);
        self.channel_user_capabilities
            .read()
            .await
            .get(&key)
            .map(|record| CommandTier::from(record.max_tier))
            .unwrap_or_else(|| command_tier_for_profile(fallback_profile))
    }

    pub async fn channel_user_can_approve(
        &self,
        channel: &str,
        user_id: &str,
        fallback_profile: ChannelSecurityProfile,
        is_open_channel: bool,
        channel_tenant: Option<(&str, &str)>,
    ) -> bool {
        // An explicit per-identity capability grant is authoritative — including a
        // deliberate downgrade below `Approve`. A tenant-scoped grant applies
        // ONLY on connections bound to the same tenant: a code issued for
        // tenant A must not confer approval authority in tenant B's channels,
        // and separate tenants' grants coexist under tenant-aware keys. A
        // grant that does not apply here is treated as absent (the fallback
        // logic below still runs); untenanted grants stay channel-global.
        let capabilities = self.channel_user_capabilities.read().await;
        if let Some((org_id, workspace_id)) = channel_tenant {
            if let Some(record) = capabilities.get(&tenant_scoped_capability_key(
                channel,
                user_id,
                org_id,
                workspace_id,
            )) {
                return CommandTier::from(record.max_tier) >= CommandTier::Approve;
            }
        }
        if let Some(record) = capabilities.get(&channel_user_capability_key(channel, user_id)) {
            // Records written before tenant-aware keys may carry a tenant
            // under the legacy key: honor their scope without assuming the
            // storage location.
            let record_tenant = record
                .tenant_org_id
                .as_deref()
                .zip(record.tenant_workspace_id.as_deref());
            if record_tenant.is_none() || record_tenant == channel_tenant {
                return CommandTier::from(record.max_tier) >= CommandTier::Approve;
            }
        }
        drop(capabilities);
        // GOV-B5a: with no explicit grant, fall back to the channel security profile
        // ONLY on a non-open channel, where the hand-picked `allowed_users` list is a
        // deliberate identity-trust decision by the operator. On a wildcard-open (`*`)
        // channel, "allowed to talk" must not imply "allowed to approve" — approval
        // there requires an explicit per-identity grant. This closes the
        // approve-by-default hole without disturbing solo/hand-picked-allowlist setups.
        if is_open_channel {
            return false;
        }
        command_tier_for_profile(fallback_profile) >= CommandTier::Approve
    }

    /// GOV-B5b: issue a per-identity step-up valid for `ttl_ms`, returning the
    /// expiry timestamp. Replaces any prior grant for the same channel+user
    /// (+tenant, when the issuer scopes the grant).
    pub async fn grant_channel_step_up(
        &self,
        channel: &str,
        user_id: &str,
        ttl_ms: u64,
        tenant: Option<(&str, &str)>,
    ) -> u64 {
        let expires_at_ms = crate::now_ms().saturating_add(ttl_ms);
        let key = match tenant {
            Some((org_id, workspace_id)) => {
                tenant_scoped_capability_key(channel, user_id, org_id, workspace_id)
            }
            None => channel_user_capability_key(channel, user_id),
        };
        self.channel_step_up_grants
            .write()
            .await
            .insert(key, expires_at_ms);
        expires_at_ms
    }

    /// GOV-B5b: true if the identity currently holds an unexpired step-up grant.
    /// Expired grants are pruned on read. This is the per-user replacement for the
    /// legacy global `TANDEM_CHANNEL_STEP_UP_PIN`, and (unlike the slash-only PIN)
    /// is checkable on the button/interaction path.
    ///
    /// Tenancy mirrors `channel_user_can_approve`: a tenant-scoped grant only
    /// satisfies connections bound to that tenant, so a step-up earned while
    /// approving in tenant A cannot carry over to the same principal's
    /// approvals in tenant B. An unscoped grant (legacy issuance) satisfies
    /// any connection.
    pub async fn channel_step_up_active(
        &self,
        channel: &str,
        user_id: &str,
        channel_tenant: Option<(&str, &str)>,
    ) -> bool {
        let mut keys = Vec::with_capacity(2);
        if let Some((org_id, workspace_id)) = channel_tenant {
            keys.push(tenant_scoped_capability_key(
                channel,
                user_id,
                org_id,
                workspace_id,
            ));
        }
        keys.push(channel_user_capability_key(channel, user_id));
        let now = crate::now_ms();
        let mut guard = self.channel_step_up_grants.write().await;
        for key in keys {
            match guard.get(&key).copied() {
                Some(expires_at_ms) if expires_at_ms > now => return true,
                Some(_) => {
                    guard.remove(&key);
                }
                None => {}
            }
        }
        false
    }
}

pub fn channel_security_profile_from_config(
    effective_config: &serde_json::Value,
    channel: &str,
) -> ChannelSecurityProfile {
    effective_config
        .pointer(&format!("/channels/{channel}/security_profile"))
        .cloned()
        .and_then(|value| serde_json::from_value::<ChannelSecurityProfile>(value).ok())
        .unwrap_or_default()
}

pub fn channel_user_capability_key(channel: &str, user_id: &str) -> String {
    format!(
        "{}:{}",
        channel.trim().to_ascii_lowercase(),
        user_id.trim().to_ascii_lowercase()
    )
}

/// Storage key for a tenant-scoped capability: distinct per tenant so the
/// same principal's grants in different tenants coexist instead of the
/// latest enrollment overwriting the previous tenant's grant.
fn tenant_scoped_capability_key(
    channel: &str,
    user_id: &str,
    org_id: &str,
    workspace_id: &str,
) -> String {
    format!(
        "{}@{}/{}",
        channel_user_capability_key(channel, user_id),
        org_id.trim(),
        workspace_id.trim(),
    )
}

/// Where a capability record is stored: tenant-aware for tenant-scoped
/// grants, the legacy `channel:user` key otherwise.
fn capability_storage_key(record: &ChannelUserCapabilityRecord) -> String {
    match (
        record.tenant_org_id.as_deref(),
        record.tenant_workspace_id.as_deref(),
    ) {
        (Some(org_id), Some(workspace_id)) => {
            tenant_scoped_capability_key(&record.channel, &record.user_id, org_id, workspace_id)
        }
        _ => channel_user_capability_key(&record.channel, &record.user_id),
    }
}

/// GOV-B5b: whether a channel requires an active per-identity step-up before an
/// approval/interaction is honored. Opt-in per channel via
/// `/channels/{channel}/require_approval_step_up` (default `false`), so existing
/// flows are unchanged unless an operator deliberately raises the bar.
pub fn channel_requires_approval_step_up(
    effective_config: &serde_json::Value,
    channel: &str,
) -> bool {
    effective_config
        .pointer(&format!("/channels/{channel}/require_approval_step_up"))
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

fn normalize_enrollment_code(code: &str) -> String {
    code.trim().to_ascii_uppercase()
}

fn normalize_org_unit_refs(raw: Vec<String>) -> Vec<String> {
    let mut out = Vec::new();
    for entry in raw {
        let normalized = entry.trim().to_string();
        if normalized.is_empty() || out.contains(&normalized) {
            continue;
        }
        out.push(normalized);
    }
    out
}

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

    #[tokio::test]
    async fn persists_and_loads_channel_user_capabilities() {
        let dir = tempfile::tempdir().unwrap();
        let mut state = AppState::new_starting("test".to_string(), true);
        state.channel_user_capabilities_path = dir.path().join("channel_user_capabilities.json");
        state
            .upsert_channel_user_capability(ChannelUserCapabilityRecord {
                channel: "slack".to_string(),
                user_id: "U123".to_string(),
                max_tier: StoredCommandTier::Approve,
                enrolled_at_ms: Some(7),
                enrolled_by: Some("admin".to_string()),
                pinned_workspace_id: None,
                org_units: Vec::new(),
                tenant_org_id: None,
                tenant_workspace_id: None,
            })
            .await
            .unwrap();

        let mut loaded = AppState::new_starting("test".to_string(), true);
        loaded.channel_user_capabilities_path = state.channel_user_capabilities_path.clone();
        loaded.load_channel_user_capabilities().await.unwrap();
        assert_eq!(
            loaded
                .channel_user_capability_tier("slack", "U123", ChannelSecurityProfile::PublicDemo)
                .await,
            CommandTier::Approve
        );
    }

    #[tokio::test]
    async fn tenant_scoped_capability_only_counts_in_its_tenant() {
        let dir = tempfile::tempdir().unwrap();
        let mut state = AppState::new_starting("test".to_string(), true);
        state.channel_user_capabilities_path = dir.path().join("caps.json");
        state
            .upsert_channel_user_capability(ChannelUserCapabilityRecord {
                channel: "slack".to_string(),
                user_id: "U-tenant-a".to_string(),
                max_tier: StoredCommandTier::Approve,
                enrolled_at_ms: Some(1),
                enrolled_by: Some("admin".to_string()),
                pinned_workspace_id: None,
                org_units: Vec::new(),
                tenant_org_id: Some("acme".to_string()),
                tenant_workspace_id: Some("hq".to_string()),
            })
            .await
            .unwrap();

        // The grant applies on a connection bound to the SAME tenant.
        assert!(
            state
                .channel_user_can_approve(
                    "slack",
                    "U-tenant-a",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    Some(("acme", "hq")),
                )
                .await
        );
        // Another tenant's channel: the grant is absent there, and the
        // open-channel fallback denies.
        assert!(
            !state
                .channel_user_can_approve(
                    "slack",
                    "U-tenant-a",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    Some(("other", "ops")),
                )
                .await,
            "a code issued for tenant A must not confer approval in tenant B"
        );
        // An unbound connection doesn't satisfy a tenant-scoped grant either.
        assert!(
            !state
                .channel_user_can_approve(
                    "slack",
                    "U-tenant-a",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    None,
                )
                .await
        );

        // A second enrollment for another tenant COEXISTS with the first —
        // it must not overwrite tenant A's grant.
        state
            .upsert_channel_user_capability(ChannelUserCapabilityRecord {
                channel: "slack".to_string(),
                user_id: "U-tenant-a".to_string(),
                max_tier: StoredCommandTier::Approve,
                enrolled_at_ms: Some(2),
                enrolled_by: Some("admin".to_string()),
                pinned_workspace_id: None,
                org_units: Vec::new(),
                tenant_org_id: Some("other".to_string()),
                tenant_workspace_id: Some("ops".to_string()),
            })
            .await
            .unwrap();
        assert!(
            state
                .channel_user_can_approve(
                    "slack",
                    "U-tenant-a",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    Some(("acme", "hq")),
                )
                .await,
            "enrolling for tenant B must not clobber tenant A's grant"
        );
        assert!(
            state
                .channel_user_can_approve(
                    "slack",
                    "U-tenant-a",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    Some(("other", "ops")),
                )
                .await
        );
        assert!(
            !state
                .channel_user_can_approve(
                    "slack",
                    "U-tenant-a",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    Some(("third", "hq")),
                )
                .await
        );
    }

    #[tokio::test]
    async fn missing_user_falls_back_to_channel_profile_tier() {
        let state = AppState::new_starting("test".to_string(), true);
        assert_eq!(
            state
                .channel_user_capability_tier(
                    "telegram",
                    "alice",
                    ChannelSecurityProfile::PublicDemo
                )
                .await,
            CommandTier::Read
        );
    }

    #[tokio::test]
    async fn enrollment_code_binds_fake_telegram_user_to_approve_tier() {
        let dir = tempfile::tempdir().unwrap();
        let mut state = AppState::new_starting("test".to_string(), true);
        state.channel_user_capabilities_path = dir.path().join("channel_user_capabilities.json");

        let issued = state
            .issue_channel_enrollment_code(
                "telegram",
                "fake-telegram-user",
                StoredCommandTier::Approve,
                None,
                Some("operator".to_string()),
                Some("/workspace/acme".to_string()),
                Vec::new(),
                None,
            )
            .await
            .expect("issue enrollment code");
        let record = state
            .confirm_channel_enrollment_code(&issued.code.to_ascii_lowercase(), None)
            .await
            .unwrap();

        assert_eq!(record.channel, "telegram");
        assert_eq!(record.user_id, "fake-telegram-user");
        assert_eq!(
            record.pinned_workspace_id.as_deref(),
            Some("/workspace/acme")
        );
        assert!(
            state
                .channel_user_can_approve(
                    "telegram",
                    "fake-telegram-user",
                    ChannelSecurityProfile::PublicDemo,
                    false,
                    None,
                )
                .await
        );
    }

    #[tokio::test]
    async fn open_channel_denies_approval_without_explicit_grant() {
        // GOV-B5a: on a wildcard-open channel, the Operator profile must NOT confer
        // approval to an ungranted user — "allowed to talk" is not "allowed to approve".
        let state = AppState::new_starting("test".to_string(), true);
        assert!(
            !state
                .channel_user_can_approve(
                    "slack",
                    "U-open",
                    ChannelSecurityProfile::Operator,
                    true,
                    None
                )
                .await,
            "open channel must not auto-confer approval"
        );
        // On a hand-picked (non-open) channel, the deliberate Operator profile still
        // confers approval — preserving solo/trusted-allowlist setups.
        assert!(
            state
                .channel_user_can_approve(
                    "slack",
                    "U-open",
                    ChannelSecurityProfile::Operator,
                    false,
                    None
                )
                .await,
            "non-open Operator channel preserves approval"
        );
    }

    #[tokio::test]
    async fn explicit_grant_approves_even_on_open_channel() {
        let dir = tempfile::tempdir().unwrap();
        let mut state = AppState::new_starting("test".to_string(), true);
        state.channel_user_capabilities_path = dir.path().join("caps.json");
        state
            .upsert_channel_user_capability(ChannelUserCapabilityRecord {
                channel: "slack".to_string(),
                user_id: "U-granted".to_string(),
                max_tier: StoredCommandTier::Approve,
                enrolled_at_ms: Some(1),
                enrolled_by: Some("admin".to_string()),
                pinned_workspace_id: None,
                org_units: Vec::new(),
                tenant_org_id: None,
                tenant_workspace_id: None,
            })
            .await
            .unwrap();
        // An explicit per-identity grant >= Approve wins even on an open channel.
        assert!(
            state
                .channel_user_can_approve(
                    "slack",
                    "U-granted",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    None
                )
                .await
        );
        // A different, ungranted user on the same open channel still cannot approve.
        assert!(
            !state
                .channel_user_can_approve(
                    "slack",
                    "U-nogrant",
                    ChannelSecurityProfile::PublicDemo,
                    true,
                    None
                )
                .await
        );
    }

    #[tokio::test]
    async fn step_up_grant_is_active_until_expiry() {
        // GOV-B5b: a per-identity step-up is active while unexpired and absent
        // otherwise (a zero-TTL grant is immediately expired).
        let state = AppState::new_starting("test".to_string(), true);
        assert!(!state.channel_step_up_active("slack", "U-step", None).await);
        state
            .grant_channel_step_up("slack", "U-step", 60_000, None)
            .await;
        assert!(state.channel_step_up_active("slack", "U-step", None).await);
        state
            .grant_channel_step_up("slack", "U-step", 0, None)
            .await;
        assert!(!state.channel_step_up_active("slack", "U-step", None).await);
    }

    #[tokio::test]
    async fn step_up_grants_are_tenant_scoped() {
        // A step-up issued for tenant A must not satisfy the same principal's
        // approvals on a connection bound to tenant B; an unscoped grant
        // (legacy issuance) satisfies any connection.
        let state = AppState::new_starting("test".to_string(), true);
        let tenant_a = Some(("acme", "hq"));
        let tenant_b = Some(("other", "ops"));
        state
            .grant_channel_step_up("slack", "U-step", 60_000, tenant_a)
            .await;
        assert!(
            state
                .channel_step_up_active("slack", "U-step", tenant_a)
                .await
        );
        assert!(
            !state
                .channel_step_up_active("slack", "U-step", tenant_b)
                .await
        );
        assert!(!state.channel_step_up_active("slack", "U-step", None).await);

        state
            .grant_channel_step_up("slack", "U-open", 60_000, None)
            .await;
        assert!(
            state
                .channel_step_up_active("slack", "U-open", tenant_a)
                .await
        );
        assert!(state.channel_step_up_active("slack", "U-open", None).await);
    }

    #[test]
    fn require_approval_step_up_config_defaults_off() {
        // GOV-B5b: step-up is opt-in per channel; absent config means off.
        let cfg = serde_json::json!({
            "channels": { "slack": { "require_approval_step_up": true }, "discord": {} }
        });
        assert!(channel_requires_approval_step_up(&cfg, "slack"));
        assert!(!channel_requires_approval_step_up(&cfg, "discord"));
        assert!(!channel_requires_approval_step_up(&cfg, "telegram"));
    }
}