dove-core 0.1.0

The shared library behind dove — client-side-encrypted, expiring file sharing from a cloud you own.
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
//! The self-hosted backend: your own S3 bucket (and, full tier, your own
//! DynamoDB table + access-gate). Config-only at construction — no secrets
//! load, no network call — so building a `SelfHosted` can never fail on I/O;
//! only the lazily-built [`Store`] touches credentials or the network.

use crate::config::{Backend, SelfHostedConfig};
use crate::error::{Error, Result};
use crate::progress::Progress;
use crate::request::{CreateRequest, NewRequest, RequestStatus};
use crate::request_ledger::{self, RequestRecord};
use crate::s3::Store;
use crate::transfer::*;
use crate::{crypto, duration as dur, ledger};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Read};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// The full-tier gate's on/off state, as reported by `dove gate status`.
pub struct GateState {
    pub enabled: bool,
}

#[derive(Debug)]
pub struct SelfHosted {
    cfg: SelfHostedConfig,
}

impl SelfHosted {
    /// Build from a registry backend. I/O-free: this only deserializes the
    /// backend's config table into [`SelfHostedConfig`] — the same
    /// `toml::Value::Table(...).try_into()` path [`Backend`]'s registry
    /// helpers use. The [`Store`] (which loads secrets) is built lazily, on
    /// first use, by [`Self::store`].
    pub fn from_backend(b: &Backend) -> Result<Self> {
        let cfg: SelfHostedConfig = toml::Value::Table(b.config.clone())
            .try_into()
            .map_err(|e| Error::Config(format!("backend {}: {e}", b.name)))?;
        Ok(Self { cfg })
    }

    /// A backend-agnostic instance for operations that don't need a
    /// configured backend. Today that's only `get`: a share link carries its
    /// own host, and the decryption key rides the URL fragment — fetching one
    /// doesn't depend on which backend (if any) is active on this machine.
    pub fn adhoc() -> Self {
        Self {
            cfg: SelfHostedConfig::default(),
        }
    }

    fn store(&self) -> Result<Store> {
        Store::new(
            &self.cfg.bucket,
            &self.cfg.region,
            self.cfg.endpoint.as_deref(),
        )
        .map_err(|e| Error::Aws(e.to_string()))
    }

    /// Full tier: always encrypt, register a download policy in DynamoDB, and
    /// hand out a gate link (`<gate>/d/<id>#<secret>`). The gate enforces the
    /// budget; the key **and** the filename + trust metadata ride the
    /// fragment, so the server sees neither the content nor the real
    /// filename.
    #[allow(clippy::too_many_arguments)]
    fn share_full(
        &self,
        store: &Store,
        source: &Path,
        name: &str,
        ttl: Duration,
        downloads: u32,
        pin: Option<String>,
        from: Option<String>,
        message: Option<String>,
        progress: &dyn Progress,
    ) -> Result<Share> {
        // A MAC'd share id: the gate rejects any id it didn't mint before
        // touching the database, so forged / random-id floods die at a cheap
        // check.
        let gate_secret = crate::secrets::Secrets::load()
            .map_err(|e| Error::Config(e.to_string()))?
            .gate_secret
            .ok_or_else(|| {
                Error::Config(
                    "no gate secret in secrets.toml — re-run `dove provision full`".into(),
                )
            })?;
        let share_id =
            crypto::new_share_id(&gate_secret).map_err(|e| Error::Other(e.to_string()))?;

        // The fragment always carries a random secret. Without a PIN it *is*
        // the content key. With a PIN, the content key is PBKDF2(PIN, secret)
        // — the PIN (already resolved by the caller, delivered out of band)
        // is the second factor, and the gate also verifies it.
        let fragment_secret = crypto::gen_key();
        let (content_key, pin_hash) = match &pin {
            Some(p) => (
                crypto::derive_key(p, &fragment_secret),
                Some(crypto::pin_hash(&share_id, p)),
            ),
            None => (fragment_secret, None),
        };

        let ct = temp_ct_path();
        progress.step("encrypting");
        let encrypted = (|| -> Result<()> {
            let reader = File::open(source)
                .map_err(|e| Error::Other(format!("opening {}: {e}", source.display())))?;
            let writer = BufWriter::new(
                File::create(&ct)
                    .map_err(|e| Error::Other(format!("creating {}: {e}", ct.display())))?,
            );
            crypto::encrypt(&content_key, crypto::DEFAULT_CHUNK, reader, writer)
                .map_err(|e| Error::Other(e.to_string()))
        })();
        if encrypted.is_ok() {
            progress.done("encrypting");
        }
        encrypted?;

        let object_key = share_id.clone(); // name-free: the filename is E2E, in the fragment
        let uploaded = store.put_file(&object_key, &ct, progress);
        let _ = std::fs::remove_file(&ct);
        let size = uploaded.map_err(|e| Error::Aws(e.to_string()))?;

        // The filename + trust (sender name, message) are encrypted with the
        // secret and stored on the server as opaque ciphertext — the server
        // can't read them (same as the file). Kept *off* the URL so links
        // stay short and constant regardless of filename/message length; the
        // page/`get` fetch + decrypt it.
        let meta_json = serde_json::json!({
            "name": name,
            "from": from.as_deref().unwrap_or(""),
            "msg": message.as_deref().unwrap_or(""),
        })
        .to_string();
        let meta_blob = crypto::encrypt_meta(&fragment_secret, meta_json.as_bytes());

        let expires_at = now_epoch() + ttl.as_secs();
        progress.step("registering policy");
        let registered = self.put_policy_item(
            &share_id,
            &object_key,
            downloads,
            expires_at,
            size,
            &meta_blob,
            pin_hash.as_deref(),
        );
        if registered.is_ok() {
            progress.done("registering policy");
        }
        registered?;

        // Keep a local id → filename record so `dove ls` can show it (the
        // server, holding only a name-free key, can't). Best-effort; never
        // fails the share.
        let _ = ledger::record(ledger::ShareRecord {
            id: share_id.clone(),
            name: name.to_string(),
            from: from.clone(),
            created_at: now_epoch(),
            expires_at,
            downloads,
        });

        let gate = self
            .cfg
            .gate_url
            .as_ref()
            .ok_or_else(|| Error::Config("no gate URL in config".into()))?;
        let link = format!(
            "{gate}/d/{share_id}#{}",
            crypto::key_to_fragment(&fragment_secret)
        );

        Ok(Share {
            id: share_id,
            link,
            size,
            expires_at,
        })
    }

    /// Write the share's policy row to DynamoDB using the **scoped IAM key**
    /// (which `provision` grants `dynamodb:PutItem`) — never the operator
    /// profile, so `dove share` needs no elevated credentials.
    #[allow(clippy::too_many_arguments)]
    fn put_policy_item(
        &self,
        id: &str,
        s3_key: &str,
        downloads: u32,
        expires_at: u64,
        size: u64,
        meta_blob: &str,
        pin_hash: Option<&str>,
    ) -> Result<()> {
        let table = self
            .cfg
            .table
            .as_ref()
            .ok_or_else(|| Error::Config("no table in config".into()))?;
        // `size` is stored so /meta reads it from DynamoDB instead of a
        // per-request S3 HeadObject. `meta` is the encrypted filename+trust
        // blob — opaque to the server, decrypted client-side with the
        // fragment secret.
        let mut item = serde_json::json!({
            "id": {"S": id},
            "s3_key": {"S": s3_key},
            "downloads_remaining": {"N": downloads.to_string()},
            "downloads_total": {"N": downloads.to_string()},
            "expires_at": {"N": expires_at.to_string()},
            "created_at": {"N": now_epoch().to_string()},
            "size": {"N": size.to_string()},
            "meta": {"S": meta_blob},
        });
        if let Some(hash) = pin_hash {
            // pin_attempts starts at 0; the gate increments on each wrong
            // guess and locks the share once it hits the ceiling.
            item["pin_hash"] = serde_json::json!({"S": hash});
            item["pin_attempts"] = serde_json::json!({"N": "0"});
        }
        let item = item.to_string();
        let secrets = crate::secrets::Secrets::load()
            .map_err(|e| Error::Config(format!("loading scoped credentials: {e}")))?;
        let mut cmd = Command::new("aws");
        cmd.env("AWS_ACCESS_KEY_ID", &secrets.access_key_id)
            .env("AWS_SECRET_ACCESS_KEY", &secrets.secret_access_key)
            .env("AWS_DEFAULT_REGION", &self.cfg.region);
        cmd.args([
            "dynamodb",
            "put-item",
            "--table-name",
            table,
            "--item",
            &item,
        ]);
        let out = cmd
            .output()
            .map_err(|e| Error::Aws(format!("running aws dynamodb put-item: {e}")))?;
        if !out.status.success() {
            return Err(Error::Aws(format!(
                "registering the share policy failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            )));
        }
        Ok(())
    }

    /// Mint a `dove request`: the PIN-gated ask for someone else to upload a
    /// file to you. Mirrors `share_full` run backwards — a MAC'd id, a fresh
    /// fragment secret, an encrypted trust blob — but the row this writes
    /// tracks an upload budget instead of a download budget, and there's no
    /// content to encrypt yet (the other side supplies that later, via the
    /// gate's `/up` + `/done`). Full tier only: a request needs the gate +
    /// table the simple tier doesn't have.
    pub fn create_request(&self, req: CreateRequest, p: &dyn Progress) -> Result<NewRequest> {
        if !self.cfg.is_full() {
            return Err(Error::Config(
                "dove request needs the full tier (a gate + DynamoDB table) — provision it \
                 with `dove provision full`."
                    .into(),
            ));
        }

        let gate_secret = crate::secrets::Secrets::load()
            .map_err(|e| Error::Config(e.to_string()))?
            .gate_secret
            .ok_or_else(|| {
                Error::Config(
                    "no gate secret in secrets.toml — re-run `dove provision full`".into(),
                )
            })?;
        let id = crypto::new_share_id(&gate_secret).map_err(|e| Error::Other(e.to_string()))?;

        // The fragment secret is the content key for whatever gets uploaded,
        // and the key for both meta blobs — never the PIN, which is only the
        // gate's upload-authorization factor (see the wire contract). It
        // never reaches the gate; it rides the URL fragment, and the local
        // ledger below is the only other place it's kept.
        let fragment_secret = crypto::gen_key();
        let pin_hash = req.pin.as_deref().map(|pin| crypto::pin_hash(&id, pin));

        // The trust blob: who's asking, their message, and what they're
        // asking for. Encrypted with the fragment secret, so the gate holds
        // it as opaque ciphertext (same as a share's meta blob) — the
        // upload page decrypts it to show the uploader who they're trusting.
        let meta_json = serde_json::json!({
            "from": req.from.as_deref().unwrap_or(""),
            "msg": req.message.as_deref().unwrap_or(""),
            "desc": req.description,
        })
        .to_string();
        let meta_blob = crypto::encrypt_meta(&fragment_secret, meta_json.as_bytes());

        let expires_at = now_epoch() + req.expires.as_secs();
        p.step("registering request");
        let registered = self.put_request_item(
            &id,
            req.uploads,
            expires_at,
            pin_hash.as_deref(),
            &meta_blob,
        );
        if registered.is_ok() {
            p.done("registering request");
        }
        registered?;

        // A local record of {id, fragment, description} is the only way
        // `dove requests`/`collect` can later decrypt whatever comes in —
        // the gate never sees the fragment, and (unlike a share) it's never
        // handed to anyone else either: this ledger row is the requester's
        // ONLY durable copy of the decryption key. Best-effort like the
        // share ledger — a write failure never fails the request itself,
        // since the link below still carries the fragment — but silent is
        // wrong here, so a failure surfaces as a progress warning instead of
        // being swallowed.
        let fragment = crypto::key_to_fragment(&fragment_secret);
        if let Err(e) = request_ledger::record(RequestRecord {
            id: id.clone(),
            fragment: fragment.clone(),
            description: req.description.clone(),
            created_at: now_epoch(),
        }) {
            p.field(
                "warning",
                &format!(
                    "couldn't save this request locally ({e}) — keep the printed link; \
                     it carries your only decryption key"
                ),
            );
        }

        let gate = self
            .cfg
            .gate_url
            .as_ref()
            .ok_or_else(|| Error::Config("no gate URL in config".into()))?;
        let link = request_link(gate, &id, &fragment);

        Ok(NewRequest { id, link })
    }

    /// Live status of a request, straight from the gate's `/rmeta/<id>` — no
    /// local fulfilment state exists (the gate is the only side that knows
    /// whether anything's been uploaded).
    pub fn request_status(&self, rec: &RequestRecord) -> Result<RequestStatus> {
        let gate = self
            .cfg
            .gate_url
            .as_ref()
            .ok_or_else(|| Error::Config("no gate URL in config".into()))?;
        let body = fetch_rmeta(gate, &rec.id)?;
        let fragment_secret =
            crypto::key_from_fragment(&rec.fragment).map_err(|e| Error::Other(e.to_string()))?;
        Ok(rmeta_to_status(&body, &fragment_secret))
    }

    /// Collect what was uploaded: confirm the gate says `received`, decrypt
    /// the filename from `/rmeta`'s `upload_meta`, then download the object
    /// directly (the scoped key already has `s3:GetObject` — no gate
    /// endpoint is involved in the download itself) and decrypt it with the
    /// fragment secret. Mirrors `get()`'s download+decrypt path.
    pub fn collect_request(
        &self,
        rec: &RequestRecord,
        out: Option<PathBuf>,
        p: &dyn Progress,
    ) -> Result<Fetched> {
        let gate = self
            .cfg
            .gate_url
            .as_ref()
            .ok_or_else(|| Error::Config("no gate URL in config".into()))?;
        let body = fetch_rmeta(gate, &rec.id)?;
        let v: serde_json::Value = serde_json::from_str(&body)
            .map_err(|e| Error::Other(format!("parsing the gate's response: {e}")))?;
        if v["status"].as_str() != Some("received") {
            return Err(Error::Other(
                "this request hasn't been fulfilled yet".into(),
            ));
        }

        let fragment_secret =
            crypto::key_from_fragment(&rec.fragment).map_err(|e| Error::Other(e.to_string()))?;

        // The filename rides `upload_meta` (`name_meta` in the /rmeta JSON),
        // encrypted by the browser with the same fragment secret. Best-effort:
        // a missing/undecryptable blob falls back to a generic name rather
        // than failing the whole collect.
        let name = decrypt_meta_field(&v, "name_meta", &fragment_secret, "name")
            .unwrap_or_else(|| "upload".to_string());
        // The create-time trust blob rides `meta`, same secret.
        let from =
            decrypt_meta_field(&v, "meta", &fragment_secret, "from").filter(|s| !s.is_empty());
        let message =
            decrypt_meta_field(&v, "meta", &fragment_secret, "msg").filter(|s| !s.is_empty());

        let out_path = out.unwrap_or_else(|| PathBuf::from(&name));

        let store = self.store()?;
        let dl_url = store.presign_get(&format!("req/{}", rec.id), Duration::from_secs(300));
        let resp = match ureq::get(&dl_url).call() {
            Ok(r) => r,
            Err(ureq::Error::Status(code, _)) => {
                return Err(Error::Aws(format!(
                    "downloading the upload failed: HTTP {code}"
                )))
            }
            Err(e @ ureq::Error::Transport(_)) => {
                return Err(Error::Network(format!(
                    "downloading the upload failed: {}",
                    transport_err(e)
                )))
            }
        };
        let total: u64 = resp
            .header("Content-Length")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);
        let reader = CountingReader {
            inner: resp.into_reader(),
            seen: 0,
            total,
            progress: p,
        };
        let file = BufWriter::new(
            File::create(&out_path)
                .map_err(|e| Error::Other(format!("creating {}: {e}", out_path.display())))?,
        );
        crypto::decrypt(&fragment_secret, reader, file).map_err(|_| Error::Integrity)?;

        Ok(Fetched {
            path: out_path,
            from,
            message,
        })
    }

    /// Write the request's row to DynamoDB using the same scoped-key pattern
    /// as [`Self::put_policy_item`] — the operator's `dove request` never
    /// needs elevated credentials either.
    fn put_request_item(
        &self,
        id: &str,
        uploads: u32,
        expires_at: u64,
        pin_hash: Option<&str>,
        meta_blob: &str,
    ) -> Result<()> {
        let table = self
            .cfg
            .table
            .as_ref()
            .ok_or_else(|| Error::Config("no table in config".into()))?;
        let item = request_item_json(id, uploads, expires_at, pin_hash, meta_blob).to_string();
        let secrets = crate::secrets::Secrets::load()
            .map_err(|e| Error::Config(format!("loading scoped credentials: {e}")))?;
        let mut cmd = Command::new("aws");
        cmd.env("AWS_ACCESS_KEY_ID", &secrets.access_key_id)
            .env("AWS_SECRET_ACCESS_KEY", &secrets.secret_access_key)
            .env("AWS_DEFAULT_REGION", &self.cfg.region);
        cmd.args([
            "dynamodb",
            "put-item",
            "--table-name",
            table,
            "--item",
            &item,
        ]);
        let out = cmd
            .output()
            .map_err(|e| Error::Aws(format!("running aws dynamodb put-item: {e}")))?;
        if !out.status.success() {
            return Err(Error::Aws(format!(
                "registering the request failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            )));
        }
        Ok(())
    }

    /// Disable the full-tier gate: reserved concurrency 0, so every request
    /// fails fast at no cost — the same lever the cost breaker pulls
    /// automatically on a flood. Non-interactive; no terminal output (the
    /// caller renders the result).
    pub fn gate_disable(&self) -> Result<()> {
        let (profile, function) = self.gate_function()?;
        run_aws(
            profile.as_deref(),
            &[
                "lambda",
                "put-function-concurrency",
                "--function-name",
                &function,
                "--reserved-concurrent-executions",
                "0",
            ],
        )
    }

    /// Re-enable the gate (remove the reserved-concurrency override).
    pub fn gate_enable(&self) -> Result<()> {
        let (profile, function) = self.gate_function()?;
        run_aws(
            profile.as_deref(),
            &[
                "lambda",
                "delete-function-concurrency",
                "--function-name",
                &function,
            ],
        )
    }

    /// Whether the gate is currently enabled (reserved concurrency isn't 0).
    pub fn gate_status(&self) -> Result<GateState> {
        let (profile, function) = self.gate_function()?;
        let out = aws_cmd(
            profile.as_deref(),
            &[
                "lambda",
                "get-function-concurrency",
                "--function-name",
                &function,
                "--output",
                "json",
            ],
        )?;
        Ok(GateState {
            enabled: gate_enabled(&out.stdout),
        })
    }

    /// The gate Lambda's `(profile, function name)` from the config + AWS
    /// identity — `dove-gate-<account>`, the name `provision full` gives it.
    fn gate_function(&self) -> Result<(Option<String>, String)> {
        if !self.cfg.is_full() {
            return Err(Error::Other(
                "this config has no gate — it isn't full tier (`dove provision full`)".into(),
            ));
        }
        let out = aws_cmd(
            self.cfg.profile.as_deref(),
            &[
                "sts",
                "get-caller-identity",
                "--query",
                "Account",
                "--output",
                "text",
            ],
        )?;
        if !out.status.success() {
            return Err(Error::Aws(format!(
                "resolving the AWS account: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            )));
        }
        let account = String::from_utf8_lossy(&out.stdout).trim().to_string();
        Ok((self.cfg.profile.clone(), format!("dove-gate-{account}")))
    }
}

impl Transfer for SelfHosted {
    fn share(&self, req: ShareRequest, progress: &dyn Progress) -> Result<Share> {
        if req.pin.is_some() && !self.cfg.is_full() {
            return Err(Error::Config(
                "--pin is a full-tier feature: it's checked at the gate, which the simple tier \
                 doesn't have. Provision it with `dove provision full`."
                    .into(),
            ));
        }
        if (req.from.is_some() || req.message.is_some()) && !self.cfg.is_full() {
            return Err(Error::Config(
                "--from/--message ride an encrypted metadata blob in the full-tier link. \
                 Provision it with `dove provision full`."
                    .into(),
            ));
        }

        let name = req
            .path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| Error::Other(format!("{} has no usable filename", req.path.display())))?
            .to_string();
        let store = self.store()?;

        if self.cfg.is_full() {
            return self.share_full(
                &store,
                &req.path,
                &name,
                req.expires,
                req.downloads.unwrap_or(100),
                req.pin,
                req.from,
                req.message,
                progress,
            );
        }

        // Simple tier: presigned links, capped at 7 days, optional --encrypt.
        if !dur::within_presign_limit(req.expires) {
            return Err(Error::Other(format!(
                "a share expiry of {} is over the 7-day limit for the simple tier's presigned \
                 links. Use 7d or less. Longer-lived shares and download limits are the full \
                 tier — provision it with `dove provision full`.",
                dur::human(req.expires)
            )));
        }
        let (upload_path, ct_temp, fragment) = if req.encrypt {
            let content_key = crypto::gen_key();
            let ct = temp_ct_path();
            progress.step("encrypting");
            let encrypted = (|| -> Result<()> {
                let reader = File::open(&req.path)
                    .map_err(|e| Error::Other(format!("opening {}: {e}", req.path.display())))?;
                let writer = BufWriter::new(
                    File::create(&ct)
                        .map_err(|e| Error::Other(format!("creating {}: {e}", ct.display())))?,
                );
                crypto::encrypt(&content_key, crypto::DEFAULT_CHUNK, reader, writer)
                    .map_err(|e| Error::Other(e.to_string()))
            })();
            if encrypted.is_ok() {
                progress.done("encrypting");
            }
            encrypted?;
            (
                ct.clone(),
                Some(ct),
                Some(crypto::key_to_fragment(&content_key)),
            )
        } else {
            (req.path.clone(), None, None)
        };

        let object_key = share_key(&name);
        let uploaded = store.put_file(&object_key, &upload_path, progress);
        if let Some(t) = ct_temp {
            let _ = std::fs::remove_file(t);
        }
        let size = uploaded.map_err(|e| Error::Aws(e.to_string()))?;

        let mut link = store.presign_get(&object_key, req.expires);
        if let Some(frag) = fragment {
            link.push('#');
            link.push_str(&frag);
        }
        let expires_at = now_epoch() + req.expires.as_secs();
        // The simple tier has no server-side id of its own; the object key's
        // random prefix is what `dove ls`/`revoke` key off of.
        let id = object_key
            .split_once('/')
            .map(|(id, _)| id.to_string())
            .unwrap_or(object_key);

        Ok(Share {
            id,
            link,
            size,
            expires_at,
        })
    }

    fn get(&self, req: GetRequest, progress: &dyn Progress) -> Result<Fetched> {
        let (base, fragment) = req.url.rsplit_once('#').ok_or_else(|| {
            Error::Other(
                "this link has no key — it isn't a dove-encrypted share (nothing after `#`)".into(),
            )
        })?;
        // The fragment is the secret (older links may append ".<meta>" —
        // ignore it). Without a PIN the secret *is* the key; with one, the
        // key is PBKDF2(PIN, secret).
        let secret = crypto::key_from_fragment(fragment.split('.').next().unwrap_or(fragment))
            .map_err(|e| Error::Other(e.to_string()))?;
        let key = match &req.pin {
            Some(p) => crypto::derive_key(p, &secret),
            None => secret,
        };

        // Filename + trust come from the gate's /meta blob, decrypted with
        // the secret (the server holds it as opaque ciphertext).
        let meta = fetch_meta(base, &secret);
        let from = meta
            .as_ref()
            .map(|(_, from, _)| from.clone())
            .filter(|s| !s.is_empty());
        let message = meta
            .as_ref()
            .map(|(_, _, msg)| msg.clone())
            .filter(|s| !s.is_empty());
        let meta_name = meta
            .as_ref()
            .map(|(n, _, _)| n.clone())
            .filter(|n| !n.is_empty());

        // Trust: surface who it's from (and their message) *before* pulling
        // the file, not after — the whole point of the callout is deciding
        // whether to download at all.
        if let Some(f) = &from {
            progress.field("from", f);
        }
        if let Some(m) = &message {
            progress.field("message", m);
        }

        let out_path = req
            .out
            .clone()
            .or_else(|| meta_name.map(PathBuf::from))
            .unwrap_or_else(|| PathBuf::from(filename_from_url(base)));

        // A full-tier link is the browser page URL (`…/d/<id>/<name>`); the
        // gate's download endpoint is `…/dl/<id>` (which decrements + 302s).
        // A simple-tier presigned URL is fetched as-is. The PIN rides a query
        // param the gate checks (only on a gate link — never on a signed
        // presigned URL).
        let mut fetch_url = to_download_url(base);
        if let Some(p) = &req.pin {
            if fetch_url.contains("/dl/") {
                fetch_url.push_str(&format!("?pin={p}"));
            }
        }
        let resp = match ureq::get(&fetch_url).call() {
            Ok(r) => r,
            Err(ureq::Error::Status(code, resp)) => {
                return Err(gate_error(code, resp, req.pin.is_some()))
            }
            Err(e @ ureq::Error::Transport(_)) => {
                return Err(Error::Network(format!(
                    "fetching the share failed: {}",
                    transport_err(e)
                )))
            }
        };
        let total: u64 = resp
            .header("Content-Length")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let reader = CountingReader {
            inner: resp.into_reader(),
            seen: 0,
            total,
            progress,
        };
        let file = BufWriter::new(
            File::create(&out_path)
                .map_err(|e| Error::Other(format!("creating {}: {e}", out_path.display())))?,
        );
        crypto::decrypt(&key, reader, file).map_err(|_| Error::Integrity)?;

        Ok(Fetched {
            path: out_path,
            from,
            message,
        })
    }

    /// The shares currently in the bucket. Full-tier shares are listed by id
    /// only: their filenames are end-to-end encrypted in the link, so the
    /// server (and therefore this) genuinely doesn't have them — the local
    /// ledger fills in what it can.
    fn list(&self) -> Result<Vec<ShareInfo>> {
        let store = self.store()?;
        let keys = store.list("").map_err(|e| Error::Aws(e.to_string()))?;
        let records: HashMap<String, ledger::ShareRecord> = ledger::load()
            .unwrap_or_default()
            .into_iter()
            .map(|r| (r.id.clone(), r))
            .collect();
        Ok(keys.iter().map(|k| share_info(k, &records)).collect())
    }

    /// Delete a share early, so its link 404s (it would have been reaped by
    /// the lifecycle rule anyway). Handles both name-free full-tier keys
    /// (`<id>`) and simple-tier keys (`<id>/<name>`).
    fn revoke(&self, id: &str) -> Result<()> {
        let store = self.store()?;
        let keys = store.list(id).map_err(|e| Error::Aws(e.to_string()))?;
        let key = keys
            .first()
            .ok_or_else(|| Error::Other(format!("no share with id {id}")))?;
        store
            .delete_object(key)
            .map_err(|e| Error::Aws(e.to_string()))?;
        let _ = ledger::remove(id);
        Ok(())
    }

    fn status(&self) -> Result<BackendStatus> {
        let mut summary = vec![
            ("bucket".to_string(), self.cfg.bucket.clone()),
            ("region".to_string(), self.cfg.region.clone()),
        ];
        if let Some(t) = &self.cfg.table {
            summary.push(("table".into(), t.clone()));
        }
        if let Some(g) = &self.cfg.gate_url {
            summary.push(("gate".into(), g.clone()));
        }
        Ok(BackendStatus { summary })
    }
}

fn now_epoch() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// A unique temp path for the ciphertext written before upload.
fn temp_ct_path() -> PathBuf {
    let mut b = [0u8; 8];
    getrandom::getrandom(&mut b).expect("OS RNG unavailable");
    let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
    std::env::temp_dir().join(format!("dove-{hex}.zip"))
}

/// Map one S3 listing key (matched against the local ledger) to a
/// `ShareInfo` — the pure core of `list()`, split out so it's testable
/// without touching S3. A simple-tier key carries its name in the key itself
/// (`<id>/<name>`); a full-tier key is name-free, so the name (and expiry), if
/// known, come from the local ledger entry `share_full` recorded at share time.
fn share_info(key: &str, records: &HashMap<String, ledger::ShareRecord>) -> ShareInfo {
    match key.split_once('/') {
        Some((id, name)) => ShareInfo {
            id: id.to_string(),
            filename: Some(name.to_string()),
            expires_at: records.get(id).map(|r| r.expires_at).unwrap_or(0),
        },
        None => {
            let rec = records.get(key);
            ShareInfo {
                id: key.to_string(),
                filename: rec.map(|r| r.name.clone()),
                expires_at: rec.map(|r| r.expires_at).unwrap_or(0),
            }
        }
    }
}

/// A share object key: a random prefix so filenames neither collide nor
/// expose a guessable listing — `<8 hex>/<filename>`.
fn share_key(filename: &str) -> String {
    let mut b = [0u8; 4];
    getrandom::getrandom(&mut b).expect("OS RNG unavailable");
    format!(
        "{:02x}{:02x}{:02x}{:02x}/{filename}",
        b[0], b[1], b[2], b[3]
    )
}

/// Build the request row's DynamoDB put-item JSON (typed-attribute form),
/// exactly as the wire contract specifies: `kind="request"`,
/// `uploads_remaining`/`uploads_total` both seeded from `uploads`,
/// `upload_attempts=0`, and — only when a PIN is set — `pin_hash` alongside
/// `pin_attempts=0`. The pure core of [`SelfHosted::put_request_item`], split
/// out so the exact attribute shape is testable without shelling out to
/// `aws`.
fn request_item_json(
    id: &str,
    uploads: u32,
    expires_at: u64,
    pin_hash: Option<&str>,
    meta_blob: &str,
) -> serde_json::Value {
    let mut item = serde_json::json!({
        "id": {"S": id},
        "kind": {"S": "request"},
        "uploads_remaining": {"N": uploads.to_string()},
        "uploads_total": {"N": uploads.to_string()},
        "expires_at": {"N": expires_at.to_string()},
        "upload_attempts": {"N": "0"},
        "meta": {"S": meta_blob},
    });
    if let Some(hash) = pin_hash {
        item["pin_hash"] = serde_json::json!({"S": hash});
        item["pin_attempts"] = serde_json::json!({"N": "0"});
    }
    item
}

/// The request link: `{gate}/r/{id}#{fragment}` — the request-page analogue
/// of `share_full`'s `{gate}/d/{id}#{fragment}`. Factored so the exact
/// assembly is testable without minting a real id/fragment.
fn request_link(gate: &str, id: &str, fragment: &str) -> String {
    format!("{gate}/r/{id}#{fragment}")
}

/// GET the gate's `/rmeta/<id>` and return the raw JSON body. Shared by
/// `request_status` and `collect_request`; a missing id (404) maps to
/// `Error::NotFound` since neither caller has a meaningful `RequestStatus`
/// for "the gate has never heard of this id".
fn fetch_rmeta(gate: &str, id: &str) -> Result<String> {
    let url = format!("{gate}/rmeta/{id}");
    match ureq::get(&url).call() {
        Ok(r) => r
            .into_string()
            .map_err(|e| Error::Network(format!("reading the gate's response: {e}"))),
        Err(ureq::Error::Status(404, _)) => Err(Error::NotFound),
        Err(ureq::Error::Status(code, _)) => Err(Error::Other(format!(
            "checking request status failed: HTTP {code}"
        ))),
        Err(e @ ureq::Error::Transport(_)) => Err(Error::Network(format!(
            "checking request status failed: {}",
            transport_err(e)
        ))),
    }
}

/// Map the gate's `/rmeta/<id>` JSON body to a [`RequestStatus`], decrypting
/// the uploaded filename (`name_meta`) with `fragment_secret` when the
/// status is `received`. Pure function — no network — so it's unit-testable
/// from a fixed JSON string. Malformed JSON (the gate should never send
/// this, but a proxy/CDN could mangle a body) maps to `Failed` rather than
/// panicking or silently reading as `Waiting`.
fn rmeta_to_status(body: &str, fragment_secret: &[u8; 32]) -> RequestStatus {
    let v: serde_json::Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => {
            return RequestStatus::Failed {
                reason: "malformed response from the gate".into(),
            }
        }
    };
    match v["status"].as_str().unwrap_or("waiting") {
        "received" => {
            let size = v["size"].as_u64().unwrap_or(0);
            let name = decrypt_meta_field(&v, "name_meta", fragment_secret, "name")
                .unwrap_or_else(|| "(encrypted)".to_string());
            RequestStatus::Received { name, size }
        }
        "failed" => RequestStatus::Failed {
            reason: v["reason"].as_str().unwrap_or("failed").to_string(),
        },
        _ => RequestStatus::Waiting,
    }
}

/// Decrypt one string field out of a JSON body's named blob attribute
/// (`meta` or `name_meta`): base64url-decode + AES-GCM-decrypt the blob at
/// `v[blob_field]` with `fragment_secret`, then pull `json_key` out of the
/// resulting plaintext JSON. `None` on any failure along the way (missing
/// field, bad blob, wrong key, absent key in the plaintext) — every caller
/// treats this as best-effort and supplies its own fallback.
fn decrypt_meta_field(
    v: &serde_json::Value,
    blob_field: &str,
    fragment_secret: &[u8; 32],
    json_key: &str,
) -> Option<String> {
    let blob = v[blob_field].as_str()?;
    let plain = crypto::decrypt_meta(fragment_secret, blob).ok()?;
    let j: serde_json::Value = serde_json::from_slice(&plain).ok()?;
    j[json_key].as_str().map(|s| s.to_string())
}

/// Fetch the gate's `/meta`, decrypt its `meta` blob with the secret, and
/// return `(filename, from, message)`. Best-effort: any failure (not a gate
/// link, no blob, decrypt error) yields `None` and `get` falls back to the
/// URL filename.
fn fetch_meta(base: &str, secret: &[u8; 32]) -> Option<(String, String, String)> {
    let meta_url = to_meta_url(base)?;
    let body = ureq::get(&meta_url).call().ok()?.into_string().ok()?;
    let v: serde_json::Value = serde_json::from_str(&body).ok()?;
    let blob = v["meta"].as_str().filter(|s| !s.is_empty())?;
    let plain = crypto::decrypt_meta(secret, blob).ok()?;
    let j: serde_json::Value = serde_json::from_slice(&plain).ok()?;
    let s = |k: &str| j[k].as_str().unwrap_or("").to_string();
    Some((s("name"), s("from"), s("msg")))
}

/// Turn a gate page URL (`scheme://host/d/<id>`) into its `/meta/<id>`
/// endpoint. Returns `None` for a non-gate URL (e.g. a simple-tier presigned
/// URL).
fn to_meta_url(base: &str) -> Option<String> {
    let scheme_end = base.find("://")?;
    let after = &base[scheme_end + 3..];
    let slash = after.find('/')?;
    let host = &base[..scheme_end + 3 + slash];
    let path = after[slash..].split('?').next().unwrap_or("");
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    (segs.len() >= 2 && segs[0] == "d").then(|| format!("{host}/meta/{}", segs[1]))
}

/// Derive the output filename from the URL's last path segment
/// (percent-decoded), ignoring the query string. Fallback when a link
/// carries no metadata.
fn filename_from_url(base: &str) -> String {
    let path = base.split('?').next().unwrap_or(base);
    let name = path.rsplit('/').next().unwrap_or("download");
    let decoded = percent_decode(name);
    if decoded.is_empty() {
        "download".to_string()
    } else {
        decoded
    }
}

/// Turn a full-tier page URL (`scheme://host/d/<id>/<name>`) into the gate's
/// download endpoint (`scheme://host/dl/<id>`). Any other URL (e.g. a
/// simple-tier presigned URL) is returned unchanged.
fn to_download_url(base: &str) -> String {
    if let Some(scheme_end) = base.find("://") {
        let after = &base[scheme_end + 3..];
        if let Some(slash) = after.find('/') {
            let host = &base[..scheme_end + 3 + slash];
            let path = after[slash..].split('?').next().unwrap_or("");
            let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
            if segs.len() >= 2 && segs[0] == "d" {
                return format!("{host}/dl/{}", segs[1]);
            }
        }
    }
    base.to_string()
}

/// Minimal percent-decoding for a URL path segment (`%20` → space, etc.).
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let Ok(b) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
                out.push(b);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Turn a gate error status (+ its JSON body) into an [`Error`] a recipient
/// can act on: needs a PIN, wrong PIN with tries left, locked out, or gone.
fn gate_error(code: u16, resp: ureq::Response, had_pin: bool) -> Error {
    let body = resp.into_string().unwrap_or_default();
    let json: serde_json::Value = serde_json::from_str(&body).unwrap_or(serde_json::Value::Null);
    let attempts = json.get("attempts_remaining").and_then(|v| v.as_u64());
    match code {
        401 if !had_pin => Error::PinRequired(
            "this share is PIN-locked — pass --pin <PIN> (the sender sent it separately)".into(),
        ),
        401 => Error::PinRequired(match attempts {
            Some(n) => format!(
                "wrong PIN — {n} attempt{} left",
                if n == 1 { "" } else { "s" }
            ),
            None => "wrong PIN".into(),
        }),
        423 => Error::Locked(
            "this share is locked — too many wrong PINs. Ask the sender to re-share.".into(),
        ),
        410 => Error::Gone,
        _ => Error::Other(format!(
            "the share link returned HTTP {code} — it may have expired or been revoked"
        )),
    }
}

/// Run an `aws` subcommand for its side effect, erroring unless it exits 0.
fn run_aws(profile: Option<&str>, args: &[&str]) -> Result<()> {
    let out = aws_cmd(profile, args)?;
    if out.status.success() {
        return Ok(());
    }
    Err(Error::Aws(format!(
        "aws {} failed: {}",
        args.join(" "),
        String::from_utf8_lossy(&out.stderr).trim()
    )))
}

/// Shell out to the `aws` CLI (with `--profile`, if one is configured),
/// returning its raw output for the caller to interpret.
fn aws_cmd(profile: Option<&str>, args: &[&str]) -> Result<std::process::Output> {
    let mut cmd = Command::new("aws");
    if let Some(p) = profile {
        cmd.args(["--profile", p]);
    }
    cmd.args(args)
        .output()
        .map_err(|e| Error::Aws(format!("running aws {}: {e}", args.join(" "))))
}

/// Whether the gate is enabled, given the raw JSON stdout of `aws lambda
/// get-function-concurrency`. Reserved concurrency of exactly 0 means
/// disabled; anything else — including output that doesn't parse — reads as
/// enabled, the same fallback the CLI used before this was extracted.
fn gate_enabled(stdout: &[u8]) -> bool {
    let reserved = serde_json::from_slice::<serde_json::Value>(stdout)
        .ok()
        .and_then(|v| v["ReservedConcurrentExecutions"].as_i64());
    reserved != Some(0)
}

/// A short transport-error string that never echoes the (signed) request URL.
fn transport_err(e: ureq::Error) -> String {
    match e {
        ureq::Error::Status(code, _) => format!("HTTP {code}"),
        ureq::Error::Transport(t) => t.kind().to_string(),
    }
}

/// Wraps the response body to drive the download progress bar.
struct CountingReader<'a, R> {
    inner: R,
    seen: u64,
    total: u64,
    progress: &'a dyn Progress,
}

impl<R: Read> Read for CountingReader<'_, R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let k = self.inner.read(buf)?;
        self.seen += k as u64;
        self.progress.bytes(self.seen, self.total);
        Ok(k)
    }
}

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

    #[test]
    fn status_summarizes_bucket_region_table_and_gate() {
        let cfg = SelfHostedConfig {
            bucket: "dove-shares-example".into(),
            region: "us-east-1".into(),
            profile: None,
            endpoint: None,
            table: Some("dove-shares-example".into()),
            gate_url: Some("https://share.example.com".into()),
            distribution_id: None,
        };
        let backend = Backend::self_hosted("default", &cfg).unwrap();

        let sh = SelfHosted::from_backend(&backend).unwrap();
        let status = sh.status().unwrap();

        assert!(status
            .summary
            .contains(&("bucket".to_string(), "dove-shares-example".to_string())));
        assert!(status
            .summary
            .contains(&("region".to_string(), "us-east-1".to_string())));
        assert!(status
            .summary
            .contains(&("table".to_string(), "dove-shares-example".to_string())));
        assert!(status
            .summary
            .contains(&("gate".to_string(), "https://share.example.com".to_string())));
    }

    #[test]
    fn from_backend_is_io_free_even_with_no_secrets_present() {
        // Building a SelfHosted must never touch the filesystem or network —
        // only Store::new() (built lazily by `store()`) loads secrets. This
        // guards against a regression that adds I/O to the constructor.
        let cfg = SelfHostedConfig {
            bucket: "b".into(),
            region: "us-east-1".into(),
            profile: None,
            endpoint: None,
            table: None,
            gate_url: None,
            distribution_id: None,
        };
        let backend = Backend::self_hosted("default", &cfg).unwrap();
        assert!(SelfHosted::from_backend(&backend).is_ok());
    }

    #[test]
    fn adhoc_is_io_free_and_not_full() {
        let sh = SelfHosted::adhoc();
        assert!(!sh.cfg.is_full());
    }

    #[test]
    fn share_key_has_random_prefix_and_keeps_the_name() {
        let k = share_key("report.pdf");
        assert!(k.ends_with("/report.pdf"), "{k}");
        let prefix = k.split('/').next().unwrap();
        assert_eq!(prefix.len(), 8);
        assert!(prefix.chars().all(|c| c.is_ascii_hexdigit()));
        // Randomised: two keys for the same name differ.
        assert_ne!(share_key("report.pdf"), share_key("report.pdf"));
    }

    #[test]
    fn to_download_url_maps_gate_page_to_dl_endpoint() {
        assert_eq!(
            to_download_url("https://abc.lambda-url.us-east-1.on.aws/d/8f3a/report.pdf"),
            "https://abc.lambda-url.us-east-1.on.aws/dl/8f3a"
        );
        // A simple-tier presigned URL is untouched.
        let presigned = "https://b.s3.amazonaws.com/ab12/report.pdf?X-Amz-Sig=x";
        assert_eq!(to_download_url(presigned), presigned);
    }

    #[test]
    fn filename_from_url_takes_last_segment_and_decodes() {
        assert_eq!(
            filename_from_url("https://b.s3.amazonaws.com/ab12/report.pdf?X-Amz-Sig=x"),
            "report.pdf"
        );
        assert_eq!(
            filename_from_url("https://b/ab12/quarterly%20report.pdf?q=1"),
            "quarterly report.pdf"
        );
    }

    #[test]
    fn to_meta_url_only_matches_gate_page_urls() {
        assert_eq!(
            to_meta_url("https://share.example.com/d/8f3a/report.pdf"),
            Some("https://share.example.com/meta/8f3a".to_string())
        );
        assert_eq!(
            to_meta_url("https://b.s3.amazonaws.com/ab12/report.pdf?X-Amz-Sig=x"),
            None
        );
    }

    #[test]
    fn gate_error_maps_known_codes() {
        // 410 matches the fixed Error::Gone message exactly.
        assert_eq!(
            Error::Gone.to_string(),
            "this share has expired or reached its download limit"
        );
    }

    /// The gate's recoverable codes must map to the typed variants a GUI can
    /// match on, while keeping the exact message text the CLI has always
    /// printed (`to_string()` unchanged pre- vs post-refactor).
    #[test]
    fn gate_error_maps_recoverable_codes_to_typed_variants() {
        let no_pin = gate_error(
            401,
            ureq::Response::new(401, "Unauthorized", "").unwrap(),
            false,
        );
        assert!(matches!(no_pin, Error::PinRequired(_)));
        assert_eq!(
            no_pin.to_string(),
            "this share is PIN-locked — pass --pin <PIN> (the sender sent it separately)"
        );

        let wrong_pin = gate_error(
            401,
            ureq::Response::new(401, "Unauthorized", r#"{"attempts_remaining":2}"#).unwrap(),
            true,
        );
        assert!(matches!(wrong_pin, Error::PinRequired(_)));
        assert_eq!(wrong_pin.to_string(), "wrong PIN — 2 attempts left");

        let locked = gate_error(423, ureq::Response::new(423, "Locked", "").unwrap(), true);
        assert!(matches!(locked, Error::Locked(_)));
        assert_eq!(
            locked.to_string(),
            "this share is locked — too many wrong PINs. Ask the sender to re-share."
        );
    }

    #[test]
    fn share_info_simple_tier_key_carries_its_own_name() {
        let info = share_info("ab12cd34/report.pdf", &HashMap::new());
        assert_eq!(info.id, "ab12cd34");
        assert_eq!(info.filename.as_deref(), Some("report.pdf"));
    }

    #[test]
    fn share_info_full_tier_key_uses_the_ledger() {
        let mut records = HashMap::new();
        records.insert(
            "890ad620f2c0b442".to_string(),
            ledger::ShareRecord {
                id: "890ad620f2c0b442".into(),
                name: "vault.txt".into(),
                from: None,
                created_at: 0,
                expires_at: 1_700_000_000,
                downloads: 1,
            },
        );
        let info = share_info("890ad620f2c0b442", &records);
        assert_eq!(info.id, "890ad620f2c0b442");
        assert_eq!(info.filename.as_deref(), Some("vault.txt"));
        assert_eq!(info.expires_at, 1_700_000_000);
    }

    #[test]
    fn share_info_unknown_full_tier_key_has_no_filename() {
        let info = share_info("deadbeefdeadbeef", &HashMap::new());
        assert_eq!(info.id, "deadbeefdeadbeef");
        assert_eq!(info.filename, None);
        assert_eq!(info.expires_at, 0);
    }

    #[test]
    fn gate_enabled_reads_reserved_concurrency() {
        assert!(!gate_enabled(br#"{"ReservedConcurrentExecutions": 0}"#));
        assert!(gate_enabled(br#"{"ReservedConcurrentExecutions": 5}"#));
        // Unparseable/empty output falls back to "enabled", same as before extraction.
        assert!(gate_enabled(b""));
    }

    #[test]
    fn request_item_json_without_pin_matches_the_wire_contract() {
        let item = request_item_json("abc123", 1, 1_700_000_000, None, "encrypted-trust-blob");
        assert_eq!(
            item,
            serde_json::json!({
                "id": {"S": "abc123"},
                "kind": {"S": "request"},
                "uploads_remaining": {"N": "1"},
                "uploads_total": {"N": "1"},
                "expires_at": {"N": "1700000000"},
                "upload_attempts": {"N": "0"},
                "meta": {"S": "encrypted-trust-blob"},
            })
        );
    }

    #[test]
    fn request_item_json_with_pin_adds_pin_hash_and_pin_attempts() {
        let item = request_item_json(
            "abc123",
            3,
            1_700_000_000,
            Some("deadbeefpinhash"),
            "encrypted-trust-blob",
        );
        assert_eq!(
            item,
            serde_json::json!({
                "id": {"S": "abc123"},
                "kind": {"S": "request"},
                "uploads_remaining": {"N": "3"},
                "uploads_total": {"N": "3"},
                "expires_at": {"N": "1700000000"},
                "upload_attempts": {"N": "0"},
                "meta": {"S": "encrypted-trust-blob"},
                "pin_hash": {"S": "deadbeefpinhash"},
                "pin_attempts": {"N": "0"},
            })
        );
    }

    #[test]
    fn request_link_format_is_locked() {
        let link = request_link("https://share.example.com", "abc123", "AAECAwQFBg");
        assert_eq!(link, "https://share.example.com/r/abc123#AAECAwQFBg");
    }

    #[test]
    fn rmeta_to_status_waiting_when_status_absent_or_waiting() {
        let secret = [1u8; 32];
        assert!(matches!(
            rmeta_to_status(r#"{"status":"waiting"}"#, &secret),
            RequestStatus::Waiting
        ));
        // Missing "status" also reads as waiting (the gate's default).
        assert!(matches!(
            rmeta_to_status("{}", &secret),
            RequestStatus::Waiting
        ));
    }

    #[test]
    fn rmeta_to_status_failed_carries_the_reason() {
        let secret = [1u8; 32];
        let status = rmeta_to_status(r#"{"status":"failed","reason":"expired"}"#, &secret);
        assert!(matches!(status, RequestStatus::Failed { reason } if reason == "expired"));
    }

    #[test]
    fn rmeta_to_status_received_decrypts_the_filename() {
        let secret = [2u8; 32];
        let name_meta = crypto::encrypt_meta(&secret, br#"{"name":"invoice.pdf"}"#);
        let body = serde_json::json!({
            "status": "received",
            "size": 4096,
            "name_meta": name_meta,
        })
        .to_string();

        let status = rmeta_to_status(&body, &secret);
        match status {
            RequestStatus::Received { name, size } => {
                assert_eq!(name, "invoice.pdf");
                assert_eq!(size, 4096);
            }
            other => panic!("expected Received, got {other:?}"),
        }
    }

    #[test]
    fn rmeta_to_status_received_falls_back_when_name_meta_is_undecryptable() {
        let secret = [3u8; 32];
        let wrong_secret = [4u8; 32];
        let name_meta = crypto::encrypt_meta(&wrong_secret, br#"{"name":"invoice.pdf"}"#);
        let body = serde_json::json!({
            "status": "received",
            "size": 10,
            "name_meta": name_meta,
        })
        .to_string();

        let status = rmeta_to_status(&body, &secret);
        match status {
            RequestStatus::Received { name, size } => {
                assert_eq!(name, "(encrypted)");
                assert_eq!(size, 10);
            }
            other => panic!("expected Received, got {other:?}"),
        }
    }

    #[test]
    fn rmeta_to_status_malformed_json_is_failed_not_a_panic() {
        let secret = [1u8; 32];
        let status = rmeta_to_status("not json", &secret);
        assert!(
            matches!(status, RequestStatus::Failed { reason } if reason == "malformed response from the gate")
        );
    }

    #[test]
    fn decrypt_meta_field_round_trips_and_is_none_on_failure() {
        let secret = [5u8; 32];
        let blob = crypto::encrypt_meta(&secret, br#"{"from":"Alex","msg":"the codes"}"#);
        let v = serde_json::json!({ "meta": blob });

        assert_eq!(
            decrypt_meta_field(&v, "meta", &secret, "from").as_deref(),
            Some("Alex")
        );
        assert_eq!(
            decrypt_meta_field(&v, "meta", &secret, "msg").as_deref(),
            Some("the codes")
        );
        // Wrong key → decrypt fails → None.
        assert_eq!(decrypt_meta_field(&v, "meta", &[9u8; 32], "from"), None);
        // Missing field → None.
        assert_eq!(decrypt_meta_field(&v, "name_meta", &secret, "name"), None);
        // Absent JSON key inside a validly-decrypted blob → None.
        assert_eq!(decrypt_meta_field(&v, "meta", &secret, "desc"), None);
    }

    #[test]
    fn create_request_requires_full_tier() {
        let cfg = SelfHostedConfig {
            bucket: "b".into(),
            region: "us-east-1".into(),
            profile: None,
            endpoint: None,
            table: None,
            gate_url: None, // not full tier
            distribution_id: None,
        };
        let backend = Backend::self_hosted("default", &cfg).unwrap();
        let sh = SelfHosted::from_backend(&backend).unwrap();
        let err = sh
            .create_request(
                CreateRequest {
                    description: "invoice".into(),
                    from: None,
                    message: None,
                    pin: None,
                    expires: Duration::from_secs(86_400),
                    uploads: 1,
                },
                &crate::progress::Silent,
            )
            .unwrap_err();
        assert!(matches!(err, Error::Config(_)));
        assert!(err.to_string().contains("full tier"), "{err}");
    }

    #[test]
    fn gate_function_rejects_a_config_with_no_gate() {
        let cfg = SelfHostedConfig {
            bucket: "b".into(),
            region: "us-east-1".into(),
            profile: None,
            endpoint: None,
            table: None,
            gate_url: None, // not full tier
            distribution_id: None,
        };
        let backend = Backend::self_hosted("default", &cfg).unwrap();
        let sh = SelfHosted::from_backend(&backend).unwrap();
        let err = sh.gate_disable().unwrap_err();
        assert_eq!(
            err.to_string(),
            "this config has no gate — it isn't full tier (`dove provision full`)"
        );
    }
}