pitboard-core 0.17.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
//! What a session here would authenticate as, from the settings files Claude Code reads
//! (`auth_precedence`, `managed_login_pins`, `windows_managed_settings`,
//! `macos_managed_preferences`), which an app started from Finder reads as a shell does.

// A project's `.claude/settings.json` is not read: it is a fact about one folder.

use crate::context::{Context, Environment};
use crate::host::{Administered, Hive, Os};
use crate::provider::claude::paths as claude;
use serde_json::Value;
use std::path::{Path, PathBuf};

/// Set, any of these makes Claude Code authenticate with something other than the login in
/// the credential store, so moving that login changes nothing a session would notice.
pub(crate) const OVERRIDING_ENV: [&str; 10] = [
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_AUTH_TOKEN",
    "CLAUDE_CODE_OAUTH_TOKEN",
    "CLAUDE_CODE_USE_BEDROCK",
    "CLAUDE_CODE_USE_VERTEX",
    "CLAUDE_CODE_USE_FOUNDRY",
    "CLAUDE_CODE_USE_GATEWAY",
    "CLAUDE_CODE_USE_ANTHROPIC_AWS",
    "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
    "CLAUDE_CODE_USE_MANTLE",
];

/// One reason a session would not use the login Pitboard moves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Override {
    /// What said so: a path, or "the environment".
    pub(crate) layer: String,
    /// The setting or variable that did it.
    pub(crate) key: String,
}

impl std::fmt::Display for Override {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} in {}", self.key, self.layer)
    }
}

pub(crate) fn managed_dir(os: Os) -> PathBuf {
    match os {
        Os::MacOs => "/Library/Application Support/ClaudeCode".into(),
        Os::Linux => "/etc/claude-code".into(),
        Os::Windows => r"C:\Program Files\ClaudeCode".into(),
    }
}

// Under `HKLM` and `HKCU` (`windows_managed_settings`).
const POLICIES: &str = r"SOFTWARE\Policies\ClaudeCode";
const POLICY: &str = "Settings";

const PREFERENCES: &str = "com.anthropic.claudecode.plist";

// A configuration profile's on macOS, the person's before the device's
// (`macos_managed_preferences`).
fn preferences(user: Option<String>) -> Vec<PathBuf> {
    let root = Path::new("/Library/Managed Preferences");
    user.map(|user| root.join(user).join(PREFERENCES))
        .into_iter()
        .chain([root.join(PREFERENCES)])
        .collect()
}

// The first of `paths` Claude Code can read, where it holds a policy.
fn plist_taken(ctx: &Context, paths: &[PathBuf]) -> Result<Option<Layer>, String> {
    for path in paths {
        match ctx.host().managed_plist(path) {
            Administered::Set(text) => {
                return Ok(
                    holds_policy(&text).then(|| administered(path.display().to_string(), &text))
                );
            }
            Administered::Unreadable(why) => return Err(format!("{}: {why}", path.display())),
            Administered::Unset => {}
        }
    }
    Ok(None)
}

struct Layer {
    name: String,
    text: String,
}

fn managed_files(ctx: &Context) -> Vec<PathBuf> {
    let dir = managed_dir(ctx.os);
    let mut files = vec![dir.join("managed-settings.json")];
    let mut drop_ins: Vec<PathBuf> = ctx
        .host()
        .administered_folder(&dir.join("managed-settings.d"))
        .into_iter()
        .filter(|p| p.extension().is_some_and(|e| e == "json"))
        .collect();
    drop_ins.sort();
    files.extend(drop_ins);
    files
}

// `HKLM` and the managed preferences win over the folder unless they merge, so reading each
// finds more, never less.
fn managed(ctx: &Context) -> Vec<Layer> {
    let host = ctx.host();
    let mut there = false;
    let mut layers: Vec<Layer> = managed_files(ctx)
        .into_iter()
        .filter_map(|path| match host.administered_file(&path) {
            Administered::Set(text) => {
                there |= holds_policy(&text);
                Some(administered(path.display().to_string(), &text))
            }
            Administered::Unreadable(_) => {
                there = true;
                None
            }
            Administered::Unset => None,
        })
        .collect();
    if ctx.os == Os::MacOs {
        for path in preferences(crate::host::user::login_name()) {
            if let Administered::Set(text) = host.managed_plist(&path) {
                layers.push(administered(path.display().to_string(), &text));
            }
        }
    }
    if ctx.os == Os::Windows {
        for hive in [Hive::Machine, Hive::User] {
            if hive == Hive::User && there {
                break;
            }
            match host.policy(hive, POLICIES, POLICY) {
                Administered::Set(text) => {
                    there |= holds_policy(&text);
                    layers.push(administered(
                        format!(r"{}\{POLICIES}\{POLICY}", hive.name()),
                        &text,
                    ));
                }
                // Claude Code treats a failed HKLM query as absent and still reads HKCU (its
                // `vYn` nulls hklmStdout on a non-zero `reg.exe` exit), so an unreadable
                // machine policy does not keep HKCU out.
                Administered::Unreadable(_) => there |= hive != Hive::Machine,
                Administered::Unset => {}
            }
        }
    }
    layers
}

// The managed sources a session takes, as Claude Code picks them: `HKLM`, or on macOS the
// managed preferences, over the folder unless it merges them, `HKCU` where neither holds a
// policy. Err names one Pitboard cannot read that may be taken.
fn managed_taken(ctx: &Context) -> Result<Vec<Layer>, String> {
    let (mut taken, merged) = managed_tiers(ctx)?;
    taken.extend(merged);
    Ok(taken)
}

// Merged in, the folder keeps no login pin (managed_login_pins).
fn managed_pins(ctx: &Context) -> Result<Vec<Layer>, String> {
    managed_tiers(ctx).map(|(taken, _)| taken)
}

// What a session takes whole, then the folder the first merges in.
fn managed_tiers(ctx: &Context) -> Result<(Vec<Layer>, Vec<Layer>), String> {
    let host = ctx.host();
    let mut folder = Vec::new();
    let mut unread = None;
    for path in managed_files(ctx) {
        match host.administered_file(&path) {
            Administered::Set(text) => {
                folder.push(administered(path.display().to_string(), &text));
            }
            Administered::Unreadable(why) => {
                unread.get_or_insert(format!("{}: {why}", path.display()));
            }
            Administered::Unset => {}
        }
    }
    let folder = || unread.map_or(Ok(folder), Err);
    let policy = |hive: Hive| {
        let name = format!(r"{}\{POLICIES}\{POLICY}", hive.name());
        match host.policy(hive, POLICIES, POLICY) {
            Administered::Set(text) if holds_policy(&text) => Ok(Some(administered(name, &text))),
            Administered::Set(_) | Administered::Unset => Ok(None),
            Administered::Unreadable(why) => Err(format!("{name}: {why}")),
        }
    };
    let first = match ctx.os {
        Os::Windows => policy(Hive::Machine)?,
        Os::MacOs => plist_taken(ctx, &preferences(crate::host::user::login_name()))?,
        Os::Linux => None,
    };
    if let Some(first) = first {
        let merges = serde_json::from_str::<Value>(&first.text)
            .ok()
            .and_then(|json| Some(json.get("managedSourcesBehavior")?.as_str()? == "merge"))
            .unwrap_or(false);
        let merged = if merges { folder()? } else { Vec::new() };
        return Ok((vec![first], merged));
    }
    let folder = folder()?;
    if ctx.os != Os::Windows || folder.iter().any(|layer| holds_policy(&layer.text)) {
        return Ok((folder, Vec::new()));
    }
    Ok((policy(Hive::User)?.into_iter().collect(), Vec::new()))
}

// What keeps `HKCU` out: one Claude Code cannot read, or one that sets more than composition.
fn holds_policy(text: &str) -> bool {
    let text = claude::without_byte_order_mark(text);
    match serde_json::from_str::<Value>(text) {
        Ok(Value::Object(keys)) => keys.keys().any(|key| {
            !matches!(
                key.as_str(),
                "managedSourcesBehavior" | "wslInheritsWindowsSettings"
            )
        }),
        Ok(_) | Err(_) => !text.trim().is_empty(),
    }
}

/// A value Claude Code would read as set. An empty string, `0` and `false` are not.
fn is_set(value: &str) -> bool {
    !matches!(value.trim(), "" | "0" | "false")
}

// As Claude Code reads a settings file: UTF-16LE after FF FE, UTF-8 otherwise, and one byte
// order mark dropped (`settings_byte_order_mark`).
fn own(path: &Path) -> Option<Layer> {
    let bytes = std::fs::read(path).ok()?;
    let text = match bytes.strip_prefix(&[0xFF, 0xFE]) {
        Some(wide) => String::from_utf16(
            &wide
                .as_chunks::<2>()
                .0
                .iter()
                .map(|pair| u16::from_le_bytes(*pair))
                .collect::<Vec<_>>(),
        )
        .ok()?,
        None => String::from_utf8(bytes).ok()?,
    };
    Some(Layer {
        name: path.display().to_string(),
        text: claude::without_byte_order_mark(&text).to_owned(),
    })
}

// As Claude Code's config loader reads it: UTF-8, one byte order mark dropped
// (`settings_byte_order_mark`).
fn config(ctx: &Context) -> Option<Layer> {
    let path = claude::config_file(ctx);
    let text = std::fs::read_to_string(&path).ok()?;
    Some(Layer {
        name: path.display().to_string(),
        text: claude::without_byte_order_mark(&text).to_owned(),
    })
}

fn administered(name: String, text: &str) -> Layer {
    Layer {
        name,
        text: claude::without_byte_order_mark(text).to_owned(),
    }
}

fn overrides_in(layer: &Layer) -> Vec<Override> {
    let Ok(json) = serde_json::from_str::<Value>(&layer.text) else {
        return Vec::new();
    };
    let layer = layer.name.clone();
    let mut found = Vec::new();
    // A helper that prints an API key is an override whatever it prints.
    if json
        .get("apiKeyHelper")
        .and_then(Value::as_str)
        .is_some_and(|h| !h.trim().is_empty())
    {
        found.push(Override {
            layer: layer.clone(),
            key: "apiKeyHelper".into(),
        });
    }
    if let Some(env) = json.get("env").and_then(Value::as_object) {
        for name in OVERRIDING_ENV {
            let set = match env.get(name) {
                Some(Value::String(v)) => is_set(v),
                Some(Value::Bool(b)) => *b,
                Some(Value::Number(n)) => n.as_i64() != Some(0),
                _ => false,
            };
            if set {
                found.push(Override {
                    layer: layer.clone(),
                    key: format!("env.{name}"),
                });
            }
        }
    }
    found
}

// Set in managed settings, these send every session through the Cloud gateway (auth_precedence).
fn gateway_in(layer: &Layer) -> Vec<Override> {
    let Ok(json) = serde_json::from_str::<Value>(&layer.text) else {
        return Vec::new();
    };
    let required = [
        json.get("forceLoginMethod").and_then(Value::as_str) == Some("gateway"),
        names_a_gateway(&json),
    ];
    ["forceLoginMethod", "forceLoginGatewayUrl"]
        .into_iter()
        .zip(required)
        .filter(|(_, set)| *set)
        .map(|(key, _)| Override {
            layer: layer.name.clone(),
            key: key.into(),
        })
        .collect()
}

fn names_a_gateway(json: &Value) -> bool {
    json.get("forceLoginGatewayUrl")
        .and_then(Value::as_str)
        .is_some_and(|url| !url.is_empty())
}

fn layered(ctx: &Context, settings: &Path) -> Vec<Override> {
    managed(ctx)
        .iter()
        .flat_map(|layer| overrides_in(layer).into_iter().chain(gateway_in(layer)))
        .chain(own(settings).iter().flat_map(overrides_in))
        .collect()
}

const FEDERATION: &str = "oidc_federation";
const OAUTH: &str = "user_oauth";

const CONFIG_DIR: &str = "ANTHROPIC_CONFIG_DIR";
const NAMED: &str = "ANTHROPIC_PROFILE";
const PAIR: [&str; 2] = ["ANTHROPIC_FEDERATION_RULE_ID", "ANTHROPIC_ORGANIZATION_ID"];

// What this process was started with of the variables that choose an Anthropic profile.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Profiles {
    started: Vec<(&'static str, String)>,
    // The profile folder while `ANTHROPIC_CONFIG_DIR` names none.
    fallback: Option<PathBuf>,
}

impl Profiles {
    pub(crate) fn read(env: &Environment) -> Profiles {
        // Each trimmed, as Claude Code reads them, and an empty one unset.
        let set = |name| env.text(name).map(str::trim).filter(|v| !v.is_empty());
        let under = |name, path: &[&str]| {
            set(name).map(|dir| path.iter().fold(PathBuf::from(dir), |p, part| p.join(part)))
        };
        Profiles {
            started: [CONFIG_DIR, NAMED, PAIR[0], PAIR[1]]
                .into_iter()
                .filter_map(|name| Some((name, env.text(name)?.to_owned())))
                .collect(),
            fallback: match env.os() {
                Os::Windows => under("APPDATA", &["Anthropic"])
                    .or_else(|| under("USERPROFILE", &["AppData", "Roaming", "Anthropic"])),
                Os::MacOs | Os::Linux => under("XDG_CONFIG_HOME", &["anthropic"])
                    .or_else(|| under("HOME", &[".config", "anthropic"])),
            },
        }
    }

    fn started(&self, name: &str) -> Option<&str> {
        self.started
            .iter()
            .find_map(|(set, value)| (*set == name).then_some(value.as_str()))
    }
}

// What a session takes for `name`, and where from: Claude Code applies the highest `env` of
// `layers` that sets it over the environment it starts with, a number or a boolean as its text,
// and drops any other value there. Trimmed, and an empty one unset.
fn taken(ctx: &Context, layers: &[Layer], name: &str) -> Option<(String, Override)> {
    let set = layers.iter().find_map(|layer| {
        let text = match setting(ctx.os, layer, name)? {
            Value::String(text) => text,
            Value::Number(number) => number.to_string(),
            Value::Bool(flag) => flag.to_string(),
            _ => return None,
        };
        Some((
            text,
            Override {
                layer: layer.name.clone(),
                key: format!("env.{name}"),
            },
        ))
    });
    let (value, from) = set.or_else(|| {
        let started = ctx.anthropic.started(name)?;
        Some((
            started.to_owned(),
            Override {
                layer: "the environment".into(),
                key: name.into(),
            },
        ))
    })?;
    let value = value.trim();
    (!value.is_empty()).then(|| (value.to_owned(), from))
}

fn profile_file(folder: &Path, name: &str) -> PathBuf {
    folder.join("configs").join(format!("{name}.json"))
}

// A profile's `authentication.type`. Claude Code takes a `user_oauth` one only with a login in
// its credentials file, which a file that is there and not empty stands for: it holds a token.
fn mode(folder: &Path, name: &str) -> Option<String> {
    let profile: Value =
        serde_json::from_str(&std::fs::read_to_string(profile_file(folder, name)).ok()?).ok()?;
    let authentication = profile.get("authentication")?;
    let mode = authentication.get("type")?.as_str()?;
    if mode == OAUTH {
        let credentials = authentication
            .get("credentials_path")
            .and_then(Value::as_str)
            .map_or_else(
                || folder.join("credentials").join(format!("{name}.json")),
                PathBuf::from,
            );
        std::fs::metadata(credentials)
            .ok()
            .filter(|file| file.is_file() && file.len() > 0)?;
    }
    Some(mode.to_owned())
}

// The profile a session takes before the stored login: the one `ANTHROPIC_PROFILE` names, else
// the federation both variables set, else the active profile where it federates. Claude Code
// takes a claude.ai login before an active profile that signs in with OAuth.
fn profile(ctx: &Context) -> Vec<Override> {
    // Below the settings, the config file's `env` (anthropic_profiles). A managed source Pitboard
    // cannot read leaves in every one it can, as `layered` does.
    let layers: Vec<Layer> = managed_taken(ctx)
        .unwrap_or_else(|_| managed(ctx))
        .into_iter()
        .chain(own(&claude::config_dir(ctx).join("settings.json")))
        .chain(config(ctx))
        .collect();
    let folder = taken(ctx, &layers, CONFIG_DIR)
        .map(|(dir, _)| PathBuf::from(dir))
        .or_else(|| ctx.anthropic.fallback.clone());
    if let Some((name, from)) = taken(ctx, &layers, NAMED) {
        return folder
            .and_then(|folder| mode(&folder, &name))
            .filter(|mode| [FEDERATION, OAUTH].contains(&mode.as_str()))
            .map(|_| from)
            .into_iter()
            .collect();
    }
    if let [Some((_, rule)), Some((_, organisation))] = PAIR.map(|name| taken(ctx, &layers, name)) {
        return if rule.layer == organisation.layer {
            vec![Override {
                layer: rule.layer,
                key: format!("{} and {}", rule.key, organisation.key),
            }]
        } else {
            vec![rule, organisation]
        };
    }
    let Some(folder) = folder else {
        return Vec::new();
    };
    let active = std::fs::read_to_string(folder.join("active_config"))
        .ok()
        .map(|name| name.trim().to_owned())
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| "default".into());
    (mode(&folder, &active).as_deref() == Some(FEDERATION))
        .then(|| Override {
            layer: profile_file(&folder, &active).display().to_string(),
            key: format!("the `{FEDERATION}` profile `{active}`"),
        })
        .into_iter()
        .collect()
}

// Each managed source a session takes `forceLoginOrgUUID` from, with the organisations it names
// (organisation_pin). None where one cannot be read: Claude Code then refuses every login.
pub(crate) fn organisation_pins(ctx: &Context) -> Vec<(String, Vec<String>)> {
    managed_pins(ctx)
        .unwrap_or_default()
        .into_iter()
        .filter_map(|layer| {
            let json = serde_json::from_str::<Value>(&layer.text).ok()?;
            let ids = match json.get("forceLoginOrgUUID")? {
                Value::String(id) => vec![id.clone()],
                Value::Array(ids) => ids
                    .iter()
                    .map(|id| id.as_str().map(str::to_owned))
                    .collect::<Option<Vec<_>>>()?,
                _ => return None,
            };
            Some((layer.name, ids))
        })
        .collect()
}

// As Claude Code's settings schema takes it: another value is dropped.
fn login_method(layer: &Layer) -> Option<String> {
    let json = serde_json::from_str::<Value>(&layer.text).ok()?;
    let method = json.get("forceLoginMethod")?.as_str()?;
    ["claudeai", "console", "gateway"]
        .contains(&method)
        .then(|| method.to_owned())
}

// The managed source whose `forceLoginMethod` `console` a sign-in takes (login_method_pin):
// where one cannot be read, any readable one.
pub(crate) fn console_pin(ctx: &Context) -> Option<String> {
    let console = |layer: &Layer| login_method(layer).as_deref() == Some("console");
    let Ok(taken) = managed_pins(ctx) else {
        return managed(ctx)
            .into_iter()
            .find(console)
            .map(|layer| layer.name);
    };
    // A gateway named is taken first, and in the folder a later file overrides an earlier one.
    if taken.iter().any(|layer| {
        serde_json::from_str::<Value>(&layer.text).is_ok_and(|json| names_a_gateway(&json))
    }) {
        return None;
    }
    taken
        .into_iter()
        .rev()
        .find(|layer| login_method(layer).is_some())
        .filter(console)
        .map(|layer| layer.name)
}

// It renames Claude Code's keychain item and config file, so it is a refusal, not a warning.
pub(crate) fn custom_oauth(ctx: &Context) -> bool {
    if ctx.custom_oauth() {
        return true;
    }
    managed(ctx)
        .into_iter()
        .chain(own(&claude::config_dir(ctx).join("settings.json")))
        .any(|layer| {
            serde_json::from_str::<Value>(&layer.text)
                .ok()
                .and_then(|json| {
                    json.get("env")?
                        .get("CLAUDE_CODE_CUSTOM_OAUTH_URL")?
                        .as_str()
                        .map(is_set)
                })
                .unwrap_or(false)
        })
}

// Each read where no descriptor is named for it, and taken before `apiKeyHelper` and the stored
// login (`remote_token_files`).
const OAUTH_TOKEN: (&str, &str) = (".oauth_token", "the OAuth token");
const API_KEY: (&str, &str) = (".api_key", "the API key");
// Claude Code's, past which it takes neither.
const REMOTE_TOKEN_LIMIT: u64 = 65_536;

// On Windows the path names no drive, so it is at the root of whichever drive a session runs
// from.
fn remote_tokens(ctx: &Context, files: &[(&str, &str)]) -> Vec<Override> {
    let folders: Vec<String> = match ctx.os {
        Os::Windows => ctx
            .host()
            .fixed_drives()
            .into_iter()
            .map(|drive| format!(r"{drive}:\home\claude\.claude\remote\"))
            .collect(),
        Os::MacOs | Os::Linux => vec!["/home/claude/.claude/remote/".into()],
    };
    folders
        .iter()
        .flat_map(|folder| {
            files
                .iter()
                .map(move |(file, what)| (format!("{folder}{file}"), *what))
        })
        .filter(|(path, _)| {
            matches!(
                ctx.host()
                    .administered_file_up_to(Path::new(path), REMOTE_TOKEN_LIMIT),
                Administered::Set(text) if !text.trim().is_empty()
            )
        })
        .map(|(layer, what)| Override {
            layer,
            key: what.into(),
        })
        .collect()
}

pub(crate) fn overrides(ctx: &Context) -> Vec<Override> {
    let mut found = layered(ctx, &claude::config_dir(ctx).join("settings.json"));
    found.extend(profile(ctx));
    found.extend(remote_tokens(ctx, &[OAUTH_TOKEN, API_KEY]));
    // What this process was started with, which a command line sees and an app does not.
    found.extend(ctx.overriding_auth().iter().map(|key| Override {
        layer: "the environment".into(),
        key: key.clone(),
    }));
    found
}

// One settings file's or policy's `env` value for a variable.
pub(crate) struct EnvSetting {
    pub(crate) layer: String,
    pub(crate) value: Value,
    pub(crate) managed: bool,
}

// A layer's `env` value for a variable: a name in any case on Windows, as it takes one.
fn setting(os: Os, layer: &Layer, name: &str) -> Option<Value> {
    let json = serde_json::from_str::<Value>(&layer.text).ok()?;
    json.get("env")?
        .as_object()?
        .iter()
        .find(|(key, _)| *key == name || os == Os::Windows && key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.clone())
}

// Highest first: the managed sources a session takes, then the person's own settings.json, which
// Claude Code assigns before them (`windows_backend_choice`). Err names a managed source Pitboard
// cannot read that may be taken.
pub(crate) fn env_settings(ctx: &Context, name: &str) -> Result<Vec<EnvSetting>, String> {
    let managed = managed_taken(ctx)?.into_iter().map(|layer| (layer, true));
    let own = own(&claude::config_dir(ctx).join("settings.json")).map(|layer| (layer, false));
    Ok(managed
        .chain(own)
        .filter_map(|(layer, managed)| {
            Some(EnvSetting {
                value: setting(ctx.os, &layer, name)?,
                layer: layer.name,
                managed,
            })
        })
        .collect())
}

// Managed settings' over the person's own, as each wins over the one below it.
pub(crate) fn status_line_command(ctx: &Context) -> Option<String> {
    managed(ctx)
        .into_iter()
        .chain(own(&claude::config_dir(ctx).join("settings.json")))
        .find_map(|layer| {
            serde_json::from_str::<Value>(&layer.text)
                .ok()?
                .get("statusLine")?
                .get("command")?
                .as_str()
                .map(str::to_owned)
        })
}

// A warm-up's run gets none of this process's environment, and its own token comes before
// `.oauth_token` and any profile.
pub(crate) fn overrides_of_a_run_in(ctx: &Context, config: &Path) -> Vec<Override> {
    let mut found = layered(ctx, &config.join("settings.json"));
    found.extend(remote_tokens(ctx, &[API_KEY]));
    found
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test sets up its scratch files as a person or a tool would"
)]
pub(crate) mod tests_support {
    use super::*;

    pub(crate) fn home() -> (Context, PathBuf, tempfile::TempDir) {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let config = scratch.path().join(".claude");
        std::fs::create_dir_all(&config).expect("a config dir");
        let ctx = Context::new(scratch.path().to_path_buf())
            .with_claude_config_dir(config.to_string_lossy().into_owned());
        (ctx, config, scratch)
    }

    pub(crate) fn write(path: &Path, value: Value) {
        std::fs::write(path, value.to_string()).expect("written");
    }
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test sets up its scratch files as a person or a tool would"
)]
mod tests {
    use super::tests_support::*;
    use super::*;
    use serde_json::json;

    #[test]
    fn the_status_line_command_is_read_from_the_persons_settings() {
        let (ctx, config, _scratch) = home();
        assert_eq!(status_line_command(&ctx), None);
        write(
            &config.join("settings.json"),
            json!({"statusLine": {"type": "command", "command": "pitboard statusline"}}),
        );
        assert_eq!(
            status_line_command(&ctx).as_deref(),
            Some("pitboard statusline")
        );
        write(&config.join("settings.json"), json!({"statusLine": {}}));
        assert_eq!(status_line_command(&ctx), None);
    }

    #[test]
    fn a_settings_file_that_starts_with_a_byte_order_mark_is_read() {
        let (ctx, config, _s) = home();
        let mut bytes = vec![0xEF, 0xBB, 0xBF];
        bytes.extend(
            json!({
                "env": {"ANTHROPIC_API_KEY": "sk-ant-something"},
                "statusLine": {"type": "command", "command": "pitboard statusline"},
            })
            .to_string()
            .into_bytes(),
        );
        std::fs::write(config.join("settings.json"), bytes).expect("written");
        assert_eq!(overrides(&ctx).len(), 1);
        assert_eq!(
            status_line_command(&ctx).as_deref(),
            Some("pitboard statusline")
        );
    }

    #[test]
    fn an_ordinary_machine_has_nothing_in_the_way() {
        let (ctx, config, _s) = home();
        write(&config.join("settings.json"), json!({"theme": "dark"}));
        assert_eq!(overrides(&ctx), Vec::new());
    }

    #[test]
    fn a_settings_file_that_sets_a_key_is_found_where_the_environment_would_not_be() {
        let (ctx, config, _s) = home();
        write(
            &config.join("settings.json"),
            json!({"env": {"ANTHROPIC_API_KEY": "sk-ant-something"}}),
        );
        let found = overrides(&ctx);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].key, "env.ANTHROPIC_API_KEY");
        assert!(found[0].layer.ends_with("settings.json"));
    }

    #[test]
    fn a_helper_that_prints_a_key_is_an_override_whatever_it_prints() {
        let (ctx, config, _s) = home();
        write(
            &config.join("settings.json"),
            json!({"apiKeyHelper": "/usr/local/bin/get-key"}),
        );
        assert_eq!(overrides(&ctx)[0].key, "apiKeyHelper");
    }

    #[test]
    fn a_third_party_provider_is_an_override_too() {
        let (ctx, config, _s) = home();
        for name in ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_MANTLE"] {
            write(&config.join("settings.json"), json!({"env": {name: "1"}}));
            assert_eq!(overrides(&ctx)[0].key, format!("env.{name}"));
        }
    }

    /// Claude Code reads an empty string, `0` and `false` as not set, and so does this.
    #[test]
    fn a_key_that_is_present_but_empty_sets_nothing() {
        let (ctx, config, _s) = home();
        write(
            &config.join("settings.json"),
            json!({
                "apiKeyHelper": "  ",
                "env": {
                    "ANTHROPIC_API_KEY": "",
                    "CLAUDE_CODE_USE_BEDROCK": "0",
                    "CLAUDE_CODE_USE_VERTEX": "false",
                },
            }),
        );
        assert_eq!(overrides(&ctx), Vec::new());
    }

    #[test]
    fn a_settings_file_that_is_not_json_is_not_a_reason_to_refuse_anything() {
        let (ctx, config, _s) = home();
        std::fs::write(config.join("settings.json"), "{ not json").expect("written");
        assert_eq!(overrides(&ctx), Vec::new());
    }
}

#[cfg(test)]
mod custom_oauth_tests {
    use super::tests_support::*;
    use super::*;
    use serde_json::json;

    #[test]
    fn a_custom_endpoint_in_a_settings_file_is_found_the_way_the_environment_one_is() {
        let (ctx, config, _s) = home();
        assert!(!custom_oauth(&ctx));
        write(
            &config.join("settings.json"),
            json!({"env": {"CLAUDE_CODE_CUSTOM_OAUTH_URL": "https://oauth.example"}}),
        );
        assert!(custom_oauth(&ctx));
    }
}

#[cfg(test)]
mod managed_tests {
    use super::*;
    use crate::context::Environment;
    use crate::host::memory::MemoryHost;
    use serde_json::json;
    use std::sync::Arc;

    fn on(os: Os, memory: &Arc<MemoryHost>) -> (Context, tempfile::TempDir) {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let home = scratch.path().to_string_lossy().into_owned();
        let config = scratch
            .path()
            .join(".claude")
            .to_string_lossy()
            .into_owned();
        let env = Environment::on(
            os,
            [
                ("HOME", home.as_str()),
                ("USERPROFILE", home.as_str()),
                ("CLAUDE_CONFIG_DIR", config.as_str()),
            ],
        );
        let ctx = Context::for_command_line(&env).with_memory_stores(Arc::clone(memory));
        (ctx, scratch)
    }

    fn said(found: &[Override]) -> Vec<(String, String)> {
        found
            .iter()
            .map(|o| (o.layer.clone(), o.key.clone()))
            .collect()
    }

    #[test]
    fn managed_settings_are_read_where_claude_code_keeps_them_on_each_system() {
        for (os, dir) in [
            (Os::MacOs, "/Library/Application Support/ClaudeCode"),
            (Os::Linux, "/etc/claude-code"),
            (Os::Windows, r"C:\Program Files\ClaudeCode"),
        ] {
            let memory = MemoryHost::new();
            let dir = PathBuf::from(dir);
            let (file, drop_ins) = (
                dir.join("managed-settings.json"),
                dir.join("managed-settings.d"),
            );
            memory.administers(
                &file,
                &json!({"env": {"ANTHROPIC_API_KEY": "sk-ant-x"}}).to_string(),
            );
            memory.administers(
                drop_ins.join("20-helper.json"),
                &json!({"apiKeyHelper": "/opt/key"}).to_string(),
            );
            memory.administers(
                drop_ins.join("10-oauth.json"),
                &json!({"env": {"CLAUDE_CODE_CUSTOM_OAUTH_URL": "https://oauth.example"}})
                    .to_string(),
            );
            memory.administers(
                drop_ins.join("30-notes.txt"),
                &json!({"apiKeyHelper": "/opt/other"}).to_string(),
            );
            let (ctx, scratch) = on(os, &memory);
            let expected = [
                (
                    file.display().to_string(),
                    "env.ANTHROPIC_API_KEY".to_string(),
                ),
                (
                    drop_ins.join("20-helper.json").display().to_string(),
                    "apiKeyHelper".to_string(),
                ),
            ];
            assert_eq!(said(&overrides(&ctx)), expected, "{os:?}");
            assert!(custom_oauth(&ctx), "{os:?}");
            let run = scratch.path().join("warm").join("config");
            assert_eq!(said(&overrides_of_a_run_in(&ctx, &run)), expected, "{os:?}");
        }
    }

    #[test]
    fn windows_policies_are_read_as_claude_code_reads_them() {
        let memory = MemoryHost::new();
        let user = format!(r"HKCU\{POLICIES}\{POLICY}");
        let machine = format!(r"HKLM\{POLICIES}\{POLICY}");
        memory.sets_policy(
            Hive::User,
            POLICIES,
            POLICY,
            &json!({"env": {"CLAUDE_CODE_USE_BEDROCK": "1"}}).to_string(),
        );
        let (ctx, _scratch) = on(Os::Windows, &memory);
        assert_eq!(
            said(&overrides(&ctx)),
            [(user.clone(), "env.CLAUDE_CODE_USE_BEDROCK".to_string())]
        );

        memory.sets_policy(
            Hive::Machine,
            POLICIES,
            POLICY,
            &json!({"managedSourcesBehavior": "merge"}).to_string(),
        );
        assert_eq!(
            said(&overrides(&ctx)),
            [(user, "env.CLAUDE_CODE_USE_BEDROCK".to_string())],
            "one that says only how the sources compose keeps nothing out"
        );

        memory.sets_policy(
            Hive::Machine,
            POLICIES,
            POLICY,
            &json!({"apiKeyHelper": "C:\\key.cmd"}).to_string(),
        );
        assert_eq!(
            said(&overrides(&ctx)),
            [(machine, "apiKeyHelper".to_string())]
        );

        let (mac, _scratch) = on(Os::MacOs, &memory);
        assert_eq!(overrides(&mac), Vec::new(), "macOS has no registry");
    }

    // Claude Code treats a failed HKLM query as absent and still reads HKCU, so Pitboard must
    // not miss an HKCU override when the machine policy cannot be read.
    #[test]
    fn an_unreadable_machine_policy_still_lets_hkcu_be_read() {
        let memory = MemoryHost::new();
        let user = format!(r"HKCU\{POLICIES}\{POLICY}");
        memory.policy_unreadable(Hive::Machine, POLICIES, POLICY, "access denied");
        memory.sets_policy(
            Hive::User,
            POLICIES,
            POLICY,
            &json!({"apiKeyHelper": "C:\\key.cmd"}).to_string(),
        );
        let (ctx, _scratch) = on(Os::Windows, &memory);
        assert_eq!(said(&overrides(&ctx)), [(user, "apiKeyHelper".to_string())]);
    }

    #[test]
    fn a_token_in_claude_codes_remote_files_comes_before_the_stored_login() {
        for os in [Os::MacOs, Os::Linux] {
            let memory = MemoryHost::new();
            memory.administers("/home/claude/.claude/remote/.oauth_token", "a token\n");
            memory.administers("/home/claude/.claude/remote/.api_key", " \n");
            let (ctx, _scratch) = on(os, &memory);
            assert_eq!(
                said(&overrides(&ctx)),
                [(
                    "/home/claude/.claude/remote/.oauth_token".to_string(),
                    "the OAuth token".to_string()
                )],
                "{os:?}"
            );
            assert_eq!(
                overrides(&ctx)[0].to_string(),
                "the OAuth token in /home/claude/.claude/remote/.oauth_token"
            );
        }
    }

    #[test]
    fn a_remote_token_file_over_claude_codes_limit_holds_no_token() {
        let key = "/home/claude/.claude/remote/.api_key";
        let memory = MemoryHost::new();
        memory.administers(key, &"k".repeat(65_536));
        let (ctx, _scratch) = on(Os::Linux, &memory);
        assert_eq!(
            said(&overrides(&ctx)),
            [(key.to_string(), "the API key".to_string())]
        );

        memory.administers(key, &"k".repeat(65_537));
        assert_eq!(overrides(&ctx), Vec::new());
    }

    // A warm-up's own token comes before `.oauth_token`, and `.api_key` before both.
    #[test]
    fn a_warm_ups_run_takes_the_api_key_in_claude_codes_remote_file() {
        for (os, folder) in [
            (Os::MacOs, "/home/claude/.claude/remote/"),
            (Os::Linux, "/home/claude/.claude/remote/"),
            (Os::Windows, r"C:\home\claude\.claude\remote\"),
        ] {
            let memory = MemoryHost::new();
            memory.administers(format!("{folder}.oauth_token"), "a token");
            let (ctx, scratch) = on(os, &memory);
            let run = scratch.path().join("warm").join("config");
            assert_eq!(overrides_of_a_run_in(&ctx, &run), Vec::new(), "{os:?}");

            memory.administers(format!("{folder}.api_key"), "sk-ant-x");
            assert_eq!(
                said(&overrides_of_a_run_in(&ctx, &run)),
                [(format!("{folder}.api_key"), "the API key".to_string())],
                "{os:?}"
            );
        }
    }

    #[test]
    fn on_windows_a_remote_token_file_is_at_a_drives_root() {
        let memory = MemoryHost::new();
        memory.administers(r"C:\home\claude\.claude\remote\.api_key", "sk-ant-x");
        memory.administers("/home/claude/.claude/remote/.oauth_token", "a token");
        let (ctx, _scratch) = on(Os::Windows, &memory);
        assert_eq!(
            said(&overrides(&ctx)),
            [(
                r"C:\home\claude\.claude\remote\.api_key".to_string(),
                "the API key".to_string()
            )]
        );

        memory.has_fixed_drives(&['C', 'D']);
        memory.administers(r"D:\home\claude\.claude\remote\.oauth_token", "a token");
        assert_eq!(
            said(&overrides(&ctx)),
            [
                (
                    r"C:\home\claude\.claude\remote\.api_key".to_string(),
                    "the API key".to_string()
                ),
                (
                    r"D:\home\claude\.claude\remote\.oauth_token".to_string(),
                    "the OAuth token".to_string()
                ),
            ]
        );
    }

    // Read in 2.1.309 (auth_precedence): managed settings that require the Cloud gateway's
    // sign-in send every session there, a warm-up's run included. The person's own only aim
    // `/login` at it.
    #[test]
    #[allow(
        clippy::disallowed_methods,
        reason = "a test sets up its scratch files as a person or a tool would"
    )]
    fn managed_settings_that_require_the_gateway_sign_in_override_the_login() {
        for (os, dir) in [
            (Os::MacOs, "/Library/Application Support/ClaudeCode"),
            (Os::Linux, "/etc/claude-code"),
            (Os::Windows, r"C:\Program Files\ClaudeCode"),
        ] {
            let file = PathBuf::from(dir).join("managed-settings.json");
            let memory = MemoryHost::new();
            let (ctx, scratch) = on(os, &memory);
            let own = scratch.path().join(".claude").join("settings.json");
            std::fs::create_dir_all(own.parent().expect("its folder")).expect("a config dir");
            std::fs::write(
                &own,
                json!({"forceLoginMethod": "gateway", "forceLoginGatewayUrl": "https://gw.example"})
                    .to_string(),
            )
            .expect("written");
            memory.administers(&file, &json!({"forceLoginMethod": "claudeai"}).to_string());
            assert_eq!(overrides(&ctx), Vec::new(), "{os:?}");

            let run = scratch.path().join("warm").join("config");
            for (set, key) in [
                (json!({"forceLoginMethod": "gateway"}), "forceLoginMethod"),
                (
                    json!({"forceLoginGatewayUrl": "https://gw.example"}),
                    "forceLoginGatewayUrl",
                ),
            ] {
                memory.administers(&file, &set.to_string());
                let expected = [(file.display().to_string(), key.to_string())];
                assert_eq!(said(&overrides(&ctx)), expected, "{os:?}");
                assert_eq!(said(&overrides_of_a_run_in(&ctx, &run)), expected, "{os:?}");
            }
        }
    }

    // Read in 2.1.309 (organisation_pin): one organisation or a list of them, from the managed
    // sources a session takes and not from the person's own settings.
    #[test]
    #[allow(
        clippy::disallowed_methods,
        reason = "a test sets up its scratch files as a person or a tool would"
    )]
    fn a_managed_organisation_pin_is_read_as_one_or_a_list() {
        let memory = MemoryHost::new();
        let (ctx, scratch) = on(Os::Linux, &memory);
        let own = scratch.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(own.parent().expect("its folder")).expect("a config dir");
        std::fs::write(&own, json!({"forceLoginOrgUUID": "org-own"}).to_string()).expect("written");
        assert_eq!(organisation_pins(&ctx), Vec::new());

        let dir = PathBuf::from("/etc/claude-code");
        let (file, drop_in) = (
            dir.join("managed-settings.json"),
            dir.join("managed-settings.d").join("10-org.json"),
        );
        memory.administers(&file, &json!({"forceLoginOrgUUID": "org-a"}).to_string());
        memory.administers(
            &drop_in,
            &json!({"forceLoginOrgUUID": ["org-b", "org-c"]}).to_string(),
        );
        assert_eq!(
            organisation_pins(&ctx),
            [
                (file.display().to_string(), vec!["org-a".to_string()]),
                (
                    drop_in.display().to_string(),
                    vec!["org-b".to_string(), "org-c".to_string()]
                ),
            ]
        );
    }

    // Read in 2.1.310 (login_method_pin, managed_login_pins): `console` alone, from the managed
    // sources a sign-in takes it from.
    #[test]
    fn a_managed_console_pin_is_read_from_the_sources_a_session_takes() {
        let memory = MemoryHost::new();
        let (ctx, _scratch) = on(Os::MacOs, &memory);
        let dir = PathBuf::from("/Library/Application Support/ClaudeCode");
        let (file, drop_in) = (
            dir.join("managed-settings.json"),
            dir.join("managed-settings.d").join("10-login.json"),
        );
        assert_eq!(console_pin(&ctx), None);
        for method in ["claudeai", "gateway"] {
            memory.administers(&drop_in, &json!({"forceLoginMethod": method}).to_string());
            assert_eq!(console_pin(&ctx), None, "{method}");
        }

        memory.administers(
            &drop_in,
            &json!({"forceLoginMethod": "console"}).to_string(),
        );
        assert_eq!(console_pin(&ctx), Some(drop_in.display().to_string()));
        memory.administers(&file, &json!({"forceLoginMethod": "gateway"}).to_string());
        assert_eq!(console_pin(&ctx), Some(drop_in.display().to_string()));
        memory.administers(
            &file,
            &json!({"forceLoginGatewayUrl": "https://gw.example"}).to_string(),
        );
        assert_eq!(console_pin(&ctx), None, "a gateway named is taken first");

        memory.administers(&file, &json!({"forceLoginMethod": "console"}).to_string());
        memory.administers(
            &drop_in,
            &json!({"forceLoginMethod": "claudeai"}).to_string(),
        );
        assert_eq!(
            console_pin(&ctx),
            None,
            "a later file overrides an earlier one"
        );
        memory.administers(&drop_in, &json!({"forceLoginMethod": "x"}).to_string());
        assert_eq!(
            console_pin(&ctx),
            Some(file.display().to_string()),
            "a method Claude Code does not know is dropped"
        );

        let plist =
            PathBuf::from("/Library/Managed Preferences").join("com.anthropic.claudecode.plist");
        memory.administers(&plist, &json!({"forceLoginMethod": "claudeai"}).to_string());
        assert_eq!(
            console_pin(&ctx),
            None,
            "the plist is taken over the folder"
        );
        memory.administers(
            &plist,
            &json!({"managedSourcesBehavior": "merge", "model": "x"}).to_string(),
        );
        assert_eq!(
            console_pin(&ctx),
            None,
            "merged in, the folder keeps no login pin"
        );
    }

    #[test]
    fn where_a_managed_source_is_unreadable_any_readable_console_pin_is_taken() {
        let memory = MemoryHost::new();
        let (ctx, _scratch) = on(Os::MacOs, &memory);
        let dir = PathBuf::from("/Library/Application Support/ClaudeCode");
        let file = dir.join("managed-settings.json");
        memory.administers_unreadably(
            dir.join("managed-settings.d").join("10-login.json"),
            "permission denied",
        );
        memory.administers(&file, &json!({"forceLoginMethod": "console"}).to_string());
        assert_eq!(console_pin(&ctx), Some(file.display().to_string()));
    }

    // Read in 2.1.309 (macos_managed_preferences): a configuration profile's plist goes where
    // `HKLM` goes on Windows.
    #[test]
    fn macos_managed_preferences_are_taken_over_the_folder_unless_they_merge() {
        let memory = MemoryHost::new();
        let plist =
            PathBuf::from("/Library/Managed Preferences").join("com.anthropic.claudecode.plist");
        let file =
            PathBuf::from("/Library/Application Support/ClaudeCode").join("managed-settings.json");
        let pins = |ctx: &Context| -> Vec<String> {
            organisation_pins(ctx)
                .into_iter()
                .map(|(layer, _)| layer)
                .collect()
        };
        memory.administers(&file, &json!({"forceLoginOrgUUID": "org-file"}).to_string());
        memory.administers(
            &plist,
            &json!({"forceLoginOrgUUID": "org-mdm", "apiKeyHelper": "/opt/key"}).to_string(),
        );
        let (mac, _scratch) = on(Os::MacOs, &memory);
        assert_eq!(pins(&mac), [plist.display().to_string()]);
        assert_eq!(
            said(&overrides(&mac)),
            [(plist.display().to_string(), "apiKeyHelper".to_string())]
        );
        let (linux, _scratch) = on(Os::Linux, &memory);
        assert_eq!(overrides(&linux), Vec::new(), "only macOS has them");

        memory.administers(
            &plist,
            &json!({"forceLoginOrgUUID": "org-mdm", "managedSourcesBehavior": "merge"}).to_string(),
        );
        assert_eq!(
            pins(&mac),
            [plist.display().to_string()],
            "merged in, the folder keeps no login pin (managed_login_pins)"
        );

        memory.administers(
            &plist,
            &json!({"managedSourcesBehavior": "merge"}).to_string(),
        );
        assert_eq!(
            pins(&mac),
            [file.display().to_string()],
            "no policy is not taken"
        );
    }

    // Under the name the passwd entry gives, as Claude Code's `os.userInfo()` reads it.
    #[test]
    fn the_persons_managed_preferences_come_before_the_devices() {
        let memory = MemoryHost::new();
        let paths = preferences(Some("dana".into()));
        let [person, device] = [&paths[0], &paths[1]];
        assert_eq!(
            person,
            Path::new("/Library/Managed Preferences/dana/com.anthropic.claudecode.plist")
        );
        let (ctx, _scratch) = on(Os::MacOs, &memory);
        let taken = |ctx: &Context| plist_taken(ctx, &paths).map(|plist| plist.map(|l| l.name));
        memory.administers(device, &json!({"forceLoginOrgUUID": "org-d"}).to_string());
        assert_eq!(taken(&ctx), Ok(Some(device.display().to_string())));

        memory.administers(person, &json!({"forceLoginOrgUUID": "org-p"}).to_string());
        assert_eq!(taken(&ctx), Ok(Some(person.display().to_string())));

        memory.administers(person, "{}");
        assert_eq!(taken(&ctx), Ok(None), "the first read is the one");

        memory.administers_unreadably(person, "holds a date");
        assert!(taken(&ctx).is_err());
    }

    #[test]
    fn a_managed_file_keeps_the_persons_policy_out() {
        let memory = MemoryHost::new();
        memory.sets_policy(
            Hive::User,
            POLICIES,
            POLICY,
            &json!({"apiKeyHelper": "C:\\key.cmd"}).to_string(),
        );
        memory.administers(
            PathBuf::from(r"C:\Program Files\ClaudeCode").join("managed-settings.json"),
            &json!({"permissions": {"deny": ["WebFetch"]}}).to_string(),
        );
        let (ctx, _scratch) = on(Os::Windows, &memory);
        assert_eq!(overrides(&ctx), Vec::new());
    }
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test sets up its scratch files as a person or a tool would"
)]
mod profile_tests {
    use super::*;
    use crate::context::Environment;
    use serde_json::json;

    fn on(os: Os, scratch: &Path, set: &[(&str, &str)]) -> Context {
        let home = scratch.to_string_lossy().into_owned();
        let config = scratch.join(".claude").to_string_lossy().into_owned();
        let mut pairs = vec![
            ("HOME", home.as_str()),
            ("USERPROFILE", home.as_str()),
            ("CLAUDE_CONFIG_DIR", config.as_str()),
        ];
        pairs.extend_from_slice(set);
        Context::for_command_line(&Environment::on(os, pairs))
    }

    fn profile(folder: &Path, name: &str, mode: &str) -> PathBuf {
        let path = folder.join("configs").join(format!("{name}.json"));
        std::fs::create_dir_all(path.parent().expect("its folder")).expect("a folder");
        std::fs::write(&path, json!({"authentication": {"type": mode}}).to_string())
            .expect("written");
        path
    }

    fn signed_in(folder: &Path, name: &str) {
        let path = folder.join("credentials").join(format!("{name}.json"));
        std::fs::create_dir_all(path.parent().expect("its folder")).expect("a folder");
        std::fs::write(path, json!({"refresh_token": "not-a-token"}).to_string()).expect("written");
    }

    fn said(ctx: &Context) -> Vec<String> {
        overrides(ctx).iter().map(ToString::to_string).collect()
    }

    // Read in 2.1.309 (anthropic_profiles): the active profile comes before the stored login
    // only where it federates; a claude.ai login comes before one signed in with OAuth.
    #[test]
    fn the_active_profile_overrides_the_login_where_it_federates() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let folder = scratch.path().join(".config").join("anthropic");
        let ctx = on(Os::Linux, scratch.path(), &[]);
        assert_eq!(said(&ctx), Vec::<String>::new());

        let default = profile(&folder, "default", "oidc_federation");
        assert_eq!(
            said(&ctx),
            [format!(
                "the `oidc_federation` profile `default` in {}",
                default.display()
            )]
        );

        std::fs::write(folder.join("active_config"), "work\n").expect("written");
        profile(&folder, "work", "user_oauth");
        signed_in(&folder, "work");
        assert_eq!(said(&ctx), Vec::<String>::new());
    }

    // `ANTHROPIC_PROFILE` takes a profile of either mode, but only one there: a user_oauth
    // profile with no login in its credentials file is none, and then nothing else is looked at.
    #[test]
    fn a_named_profile_overrides_the_login_where_it_is_there() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let folder = scratch.path().join(".config").join("anthropic");
        let named = [
            ("ANTHROPIC_PROFILE", " work "),
            ("ANTHROPIC_FEDERATION_RULE_ID", "rule"),
            ("ANTHROPIC_ORGANIZATION_ID", "org"),
        ];
        let ctx = on(Os::MacOs, scratch.path(), &named);
        profile(&folder, "default", "oidc_federation");
        profile(&folder, "work", "user_oauth");
        assert_eq!(said(&ctx), Vec::<String>::new());

        signed_in(&folder, "work");
        assert_eq!(said(&ctx), ["ANTHROPIC_PROFILE in the environment"]);
    }

    // The file holds a login, so it is looked at for being there and not empty, never read:
    // what it holds, text or not, is Claude Code's to read.
    #[test]
    fn a_profiles_credentials_file_is_never_read() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let folder = scratch.path().join(".config").join("anthropic");
        let ctx = on(Os::Linux, scratch.path(), &[("ANTHROPIC_PROFILE", "work")]);
        profile(&folder, "work", "user_oauth");
        signed_in(&folder, "work");
        let credentials = folder.join("credentials").join("work.json");
        std::fs::write(&credentials, b"\xff\xfe not text").expect("written");
        assert_eq!(said(&ctx), ["ANTHROPIC_PROFILE in the environment"]);

        std::fs::write(&credentials, "").expect("emptied");
        assert_eq!(said(&ctx), Vec::<String>::new());
    }

    // Both variables, with no `ANTHROPIC_PROFILE`, are a federation of their own.
    #[test]
    fn a_federation_the_environment_sets_overrides_the_login() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let pair = [
            ("ANTHROPIC_FEDERATION_RULE_ID", "rule"),
            ("ANTHROPIC_ORGANIZATION_ID", "org"),
        ];
        assert_eq!(
            said(&on(Os::Linux, scratch.path(), &pair)),
            ["ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID in the environment"]
        );
        assert_eq!(
            said(&on(Os::Linux, scratch.path(), &pair[..1])),
            Vec::<String>::new()
        );
        assert_eq!(
            said(&on(
                Os::Linux,
                scratch.path(),
                &[pair[0], ("ANTHROPIC_ORGANIZATION_ID", " ")]
            )),
            Vec::<String>::new()
        );
    }

    fn own_settings(scratch: &Path, env: Value) -> PathBuf {
        let path = scratch.join(".claude").join("settings.json");
        std::fs::create_dir_all(path.parent().expect("its folder")).expect("a folder");
        std::fs::write(&path, json!({ "env": env }).to_string()).expect("written");
        path
    }

    // Claude Code 2.1.309 applies a settings file's `env` over the environment it starts with
    // before it looks for a profile (anthropic_profiles).
    #[test]
    fn a_profile_a_settings_file_names_is_taken_over_the_environments() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let folder = scratch.path().join(".config").join("anthropic");
        let ctx = on(Os::Linux, scratch.path(), &[("ANTHROPIC_PROFILE", "home")]);
        profile(&folder, "home", "user_oauth");
        profile(&folder, "work", "oidc_federation");
        let settings = own_settings(scratch.path(), json!({"ANTHROPIC_PROFILE": " work "}));
        assert_eq!(
            said(&ctx),
            [format!("env.ANTHROPIC_PROFILE in {}", settings.display())]
        );

        own_settings(scratch.path(), json!({"anthropic_profile": "work"}));
        assert_eq!(
            said(&ctx),
            Vec::<String>::new(),
            "another variable off Windows"
        );

        own_settings(scratch.path(), json!({"ANTHROPIC_PROFILE": ""}));
        let default = profile(&folder, "default", "oidc_federation");
        assert_eq!(
            said(&ctx),
            [format!(
                "the `oidc_federation` profile `default` in {}",
                default.display()
            )],
            "an empty one unsets the environment's"
        );
    }

    #[test]
    fn a_federation_a_settings_file_sets_overrides_the_login() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let both = json!({"ANTHROPIC_FEDERATION_RULE_ID": "rule", "ANTHROPIC_ORGANIZATION_ID": 7});
        let settings = own_settings(scratch.path(), both);
        let ctx = on(Os::MacOs, scratch.path(), &[]);
        assert_eq!(
            said(&ctx),
            [format!(
                "env.ANTHROPIC_FEDERATION_RULE_ID and env.ANTHROPIC_ORGANIZATION_ID in {}",
                settings.display()
            )]
        );

        own_settings(scratch.path(), json!({"ANTHROPIC_ORGANIZATION_ID": "org"}));
        let ctx = on(
            Os::MacOs,
            scratch.path(),
            &[("ANTHROPIC_FEDERATION_RULE_ID", "rule")],
        );
        assert_eq!(
            said(&ctx),
            [
                "ANTHROPIC_FEDERATION_RULE_ID in the environment".to_string(),
                format!("env.ANTHROPIC_ORGANIZATION_ID in {}", settings.display()),
            ]
        );
    }

    // Claude Code 2.1.309 applies its config file's `env` first, below every settings file's.
    #[test]
    fn a_profile_the_config_file_names_is_taken_below_the_settings() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let folder = scratch.path().join(".config").join("anthropic");
        profile(&folder, "home", "user_oauth");
        profile(&folder, "work", "oidc_federation");
        let ctx = on(Os::Linux, scratch.path(), &[("ANTHROPIC_PROFILE", "home")]);
        let config = crate::provider::claude::paths::config_file(&ctx);
        std::fs::create_dir_all(config.parent().expect("its folder")).expect("a folder");
        let env = json!({"env": {"ANTHROPIC_PROFILE": "work"}});
        std::fs::write(&config, format!("\u{feff}{env}")).expect("written");
        assert_eq!(
            said(&ctx),
            [format!("env.ANTHROPIC_PROFILE in {}", config.display())]
        );

        own_settings(scratch.path(), json!({"ANTHROPIC_PROFILE": "home"}));
        assert_eq!(said(&ctx), Vec::<String>::new());
    }

    // Claude Code applies the person's own settings whatever a managed source it cannot read
    // holds.
    #[test]
    fn a_profile_the_persons_settings_name_is_taken_beside_an_unreadable_managed_source() {
        let memory = crate::host::memory::MemoryHost::new();
        memory.administers_unreadably("/etc/claude-code/managed-settings.json", "denied");
        let scratch = tempfile::tempdir().expect("a scratch home");
        let ctx = on(Os::Linux, scratch.path(), &[]).with_memory_stores(memory);
        profile(
            &scratch.path().join(".config").join("anthropic"),
            "work",
            "oidc_federation",
        );
        let settings = own_settings(scratch.path(), json!({"ANTHROPIC_PROFILE": "work"}));
        assert_eq!(
            said(&ctx),
            [format!("env.ANTHROPIC_PROFILE in {}", settings.display())]
        );
    }

    #[test]
    fn the_profile_folder_a_settings_file_names_is_looked_in() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let elsewhere = scratch.path().join("elsewhere");
        own_settings(
            scratch.path(),
            json!({"ANTHROPIC_CONFIG_DIR": elsewhere.to_string_lossy()}),
        );
        let path = profile(&elsewhere, "default", "oidc_federation");
        assert_eq!(
            said(&on(Os::Linux, scratch.path(), &[])),
            [format!(
                "the `oidc_federation` profile `default` in {}",
                path.display()
            )]
        );
    }

    #[test]
    fn profiles_are_where_claude_code_looks_for_them_on_each_system() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let elsewhere = scratch.path().join("elsewhere");
        let named = elsewhere.to_string_lossy().into_owned();
        let roaming = scratch.path().join("Roaming");
        let app_data = roaming.to_string_lossy().into_owned();
        for (ctx, folder) in [
            (
                on(Os::Linux, scratch.path(), &[("XDG_CONFIG_HOME", &named)]),
                elsewhere.join("anthropic"),
            ),
            (
                on(
                    Os::MacOs,
                    scratch.path(),
                    &[
                        ("ANTHROPIC_CONFIG_DIR", &named),
                        ("XDG_CONFIG_HOME", "/xdg"),
                    ],
                ),
                elsewhere.clone(),
            ),
            (
                on(Os::Windows, scratch.path(), &[("APPDATA", &app_data)]),
                roaming.join("Anthropic"),
            ),
            (
                on(Os::Windows, scratch.path(), &[]),
                scratch
                    .path()
                    .join("AppData")
                    .join("Roaming")
                    .join("Anthropic"),
            ),
        ] {
            let path = profile(&folder, "default", "oidc_federation");
            assert_eq!(
                said(&ctx),
                [format!(
                    "the `oidc_federation` profile `default` in {}",
                    path.display()
                )],
                "{folder:?}"
            );
            std::fs::remove_file(path).expect("removed");
        }
    }
}