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
// SPDX-License-Identifier: AGPL-3.0-or-later
use btconfig::{CredStoreConfig, FigmentExt, NodeCredConsumer};
use btconsole::{BtConsole, BtConsoleConfig};
use btfproto::{
    local_fs::{LocalFs, ModeAuthorizer},
    server::{new_fs_server, FsProvider},
};
use btlib::{bterr, crypto::Creds, error::DisplayErr, log::BuilderExt, Result};
use bttp::Receiver;
use figment::{providers::Serialized, Figment};
use serde::{Deserialize, Serialize};
use std::{net::IpAddr, path::PathBuf, sync::Arc};

#[derive(Debug, Serialize, Deserialize, Clone)]
struct BtfsdConfig {
    #[serde(rename = "credstore")]
    cred_store: CredStoreConfig,
    /// The IP address to listen for filesystem connection on.
    #[serde(rename = "ipaddr")]
    ip_addr: IpAddr,
    /// The path in the local filesystem where blocks are stored.
    #[serde(rename = "blockdir")]
    block_dir: PathBuf,
    /// Configuration for the btconsole webapp.
    console: Option<BtConsoleConfig>,
}

impl BtfsdConfig {
    fn new() -> Result<BtfsdConfig> {
        Figment::new()
            .merge(Serialized::defaults(Self::default()))
            .btconfig()?
            .extract()
            .map_err(|err| err.into())
    }
}

impl Default for BtfsdConfig {
    fn default() -> Self {
        Self {
            cred_store: CredStoreConfig::default(),
            ip_addr: IpAddr::from([127, 0, 0, 1]),
            block_dir: btconfig::default_block_dir(),
            console: Some(BtConsoleConfig::default()),
        }
    }
}

async fn provider(block_dir: PathBuf, creds: Arc<dyn Creds>) -> Result<impl FsProvider> {
    if block_dir.exists() {
        LocalFs::new_existing(block_dir, creds, ModeAuthorizer)
    } else {
        std::fs::create_dir_all(&block_dir)?;
        LocalFs::new_empty(block_dir, 0, creds, ModeAuthorizer).await
    }
}

async fn receiver(config: BtfsdConfig) -> Result<Receiver> {
    let node_creds = config.cred_store.consume(NodeCredConsumer)??;
    let provider = Arc::new(provider(config.block_dir, node_creds.clone()).await?);
    new_fs_server(config.ip_addr, Arc::new(node_creds), provider)
}

#[tokio::main]
async fn main() -> Result<()> {
    env_logger::Builder::from_default_env().btformat().init();
    let mut config = BtfsdConfig::new()?;
    let console_config = config
        .console
        .take()
        .ok_or_else(|| bterr!("No BtConsole configuration was provided"))?;
    let (console, receiver) = tokio::join!(BtConsole::start(console_config), receiver(config));
    let receiver = receiver?;
    let console = console?;
    log::debug!("ready to accept connections");
    let (console, receiver) = tokio::join!(console.has_shutdown(), receiver.complete()?);
    console?;
    receiver.display_err()?;
    Ok(())
}

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

    use btconfig::CredStoreConfig;
    use btconsole::BtConsoleConfig;
    use btfproto::{client::FsClient, msg::*};
    use btlib::{
        crypto::{
            file_cred_store::FileCredStore, tpm::TpmCredStore, ConcreteCreds, CredStore,
            CredStoreMut, CredsPriv, CredsPub,
        },
        log::BuilderExt,
        AuthzAttrs, BlockMetaSecrets, Epoch, IssuedProcRec, Principaled, ProcRec,
    };
    use btlib_tests::{CredStoreTestingExt, TpmCredStoreHarness};
    use bttp::BlockAddr;
    use btserde::from_slice;
    use std::net::{IpAddr, Ipv4Addr};
    use std::{future::ready, net::Ipv6Addr, time::Duration};
    use swtpm_harness::SwtpmHarness;
    use tempdir::TempDir;

    const LOG_LEVEL: &str = "warn";

    #[ctor::ctor]
    fn ctor() {
        std::env::set_var("RUST_LOG", LOG_LEVEL);
        env_logger::Builder::from_default_env().btformat().init();
    }

    struct FileTestCase {
        client: FsClient,
        _rx: Receiver,
        _dir: TempDir,
    }

    async fn file_test_case(dir: TempDir, ipaddr: IpAddr) -> FileTestCase {
        let file_store_path = dir.path().join("cred_store");
        let credstore = CredStoreConfig::File {
            path: file_store_path.clone(),
        };

        {
            let cred_store = FileCredStore::new(file_store_path).unwrap();
            cred_store.provision(ROOT_PASSWD).unwrap();
        }
        let config = BtfsdConfig {
            cred_store: credstore,
            ip_addr: ipaddr,
            block_dir: dir.path().join(BT_DIR),
            console: Some(BtConsoleConfig::default()),
        };
        let rx = receiver(config).await.unwrap();
        let tx = rx.transmitter(rx.addr().clone()).await.unwrap();
        let client = FsClient::new(tx);
        FileTestCase {
            _dir: dir,
            _rx: rx,
            client,
        }
    }

    async fn new_file_test_case() -> FileTestCase {
        let dir = TempDir::new("btfsd").unwrap();
        file_test_case(dir, LOCALHOST).await
    }

    struct TestCase {
        client: FsClient,
        rx: Receiver,
        harness: TpmCredStoreHarness,
        _dir: TempDir,
    }

    const ROOT_PASSWD: &str = "existential_threat";
    const LOCALHOST: IpAddr = IpAddr::V6(Ipv6Addr::LOCALHOST);
    const BT_DIR: &str = "bt";

    async fn tpm_test_case(dir: TempDir, harness: TpmCredStoreHarness, ipaddr: IpAddr) -> TestCase {
        let swtpm = harness.swtpm();
        let credstore = CredStoreConfig::Tpm {
            path: swtpm.state_path().to_owned(),
            tabrmd: swtpm.tabrmd_config().to_owned(),
        };
        let config = BtfsdConfig {
            cred_store: credstore,
            ip_addr: ipaddr,
            block_dir: dir.path().join(BT_DIR),
            console: Some(BtConsoleConfig::default()),
        };
        let rx = receiver(config).await.unwrap();
        let tx = rx.transmitter(rx.addr().clone()).await.unwrap();
        let client = FsClient::new(tx);
        TestCase {
            _dir: dir,
            harness,
            rx,
            client,
        }
    }

    async fn new_tpm_test_case() -> TestCase {
        let dir = TempDir::new("btfsd").unwrap();
        let harness = TpmCredStoreHarness::new(ROOT_PASSWD.to_owned()).unwrap();
        tpm_test_case(dir, harness, LOCALHOST).await
    }

    async fn existing_case(case: TestCase) -> TestCase {
        case.rx.stop().unwrap();
        case.rx.complete().unwrap().await.unwrap();
        let TestCase {
            _dir,
            harness: _harness,
            ..
        } = case;
        tpm_test_case(_dir, _harness, IpAddr::V4(Ipv4Addr::LOCALHOST)).await
    }

    #[allow(dead_code)]
    async fn manual_test() {
        let case = new_tpm_test_case().await;
        case.rx.complete().unwrap().await.unwrap();
    }

    async fn create_write_read(client: FsClient) {
        const FILENAME: &str = "file.txt";
        const EXPECTED: &[u8] = b"potato";

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        let WriteReply { written, .. } = client.write(inode, handle, 0, EXPECTED).await.unwrap();
        assert_eq!(EXPECTED.len() as u64, written);
        let actual = client
            .read(inode, handle, 0, EXPECTED.len() as u64, |reply| {
                let mut buf = Vec::with_capacity(EXPECTED.len());
                buf.extend_from_slice(reply.data);
                ready(buf)
            })
            .await
            .unwrap();

        assert_eq!(EXPECTED, &actual);
    }

    #[tokio::test]
    async fn create_write_read_with_tpm() {
        let case = new_tpm_test_case().await;
        create_write_read(case.client).await;
    }

    #[tokio::test]
    async fn create_write_read_with_file() {
        let case = new_file_test_case().await;
        create_write_read(case.client).await;
    }

    #[tokio::test]
    async fn read_full_sector() {
        const FILENAME: &str = "file.txt";
        const EXPECTED: &[u8] = b"prawn crisps";
        let case = new_tpm_test_case().await;
        let client = case.client;

        let CreateReply {
            inode,
            handle,
            entry,
            ..
        } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        let WriteReply { written, .. } = client.write(inode, handle, 0, EXPECTED).await.unwrap();
        assert_eq!(EXPECTED.len() as u64, written);
        assert!(entry.attr.sect_sz > EXPECTED.len() as u64);
        let actual = client
            .read(inode, handle, 0, entry.attr.sect_sz, |reply| {
                let mut buf = Vec::with_capacity(EXPECTED.len());
                buf.extend_from_slice(reply.data);
                ready(buf)
            })
            .await
            .unwrap();

        assert!(EXPECTED.eq(&actual));
    }

    #[tokio::test]
    async fn read_from_different_instance() {
        const FILENAME: &str = "file.txt";
        const EXPECTED: &[u8] = b"potato";
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        let WriteReply { written, .. } = client.write(inode, handle, 0, EXPECTED).await.unwrap();
        assert_eq!(EXPECTED.len() as u64, written);
        client.flush(inode, handle).await.unwrap();
        let case = existing_case(case).await;
        let client = &case.client;
        let LookupReply { inode, .. } = client
            .lookup(SpecInodes::RootDir.into(), FILENAME)
            .await
            .unwrap();
        let OpenReply { handle, .. } = client
            .open(inode, FlagValue::ReadOnly.into())
            .await
            .unwrap();
        let actual = client
            .read(inode, handle, 0, EXPECTED.len() as u64, |reply| {
                let mut buf = Vec::with_capacity(EXPECTED.len());
                buf.extend_from_slice(reply.data);
                ready(buf)
            })
            .await
            .unwrap();

        assert_eq!(EXPECTED, &actual);
    }

    #[tokio::test]
    async fn create_lookup() {
        const FILENAME: &str = "file.txt";
        let case = new_tpm_test_case().await;
        let client = case.client;

        let CreateReply {
            inode: expected, ..
        } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadOnly.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        let LookupReply { inode: actual, .. } = client
            .lookup(SpecInodes::RootDir.into(), FILENAME)
            .await
            .unwrap();

        assert_eq!(expected, actual);
    }

    #[tokio::test]
    async fn open_existing() {
        const FILENAME: &str = "file.txt";
        let case = new_tpm_test_case().await;
        let client = case.client;

        let CreateReply { inode, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadOnly.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        let result = client.open(inode, FlagValue::ReadWrite.into()).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn write_flush_close_read() {
        const FILENAME: &str = "lyrics.txt";
        const EXPECTED: &[u8] = b"Fate, or something better";
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        let WriteReply { written, .. } = client.write(inode, handle, 0, EXPECTED).await.unwrap();
        assert_eq!(EXPECTED.len() as u64, written);
        client.flush(inode, handle).await.unwrap();
        client.close(inode, handle).await.unwrap();
        let OpenReply { handle, .. } = client
            .open(inode, FlagValue::ReadOnly.into())
            .await
            .unwrap();
        let actual = client
            .read(inode, handle, 0, EXPECTED.len() as u64, |reply| {
                ready(reply.data.to_owned())
            })
            .await
            .unwrap();

        assert_eq!(EXPECTED, &actual);
    }

    #[tokio::test]
    async fn link() {
        const FIRSTNAME: &str = "Jean-Luc";
        const LASTNAME: &str = "Picard";
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FIRSTNAME,
                Flags::default(),
                0o644,
                0,
            )
            .await
            .unwrap();
        client
            .link(inode, SpecInodes::RootDir.into(), LASTNAME)
            .await
            .unwrap();
        let OpenReply {
            handle: root_handle,
            ..
        } = client
            .open(
                SpecInodes::RootDir.into(),
                FlagValue::ReadOnly | FlagValue::Directory,
            )
            .await
            .unwrap();
        let ReadDirReply { entries, .. } = client
            .read_dir(SpecInodes::RootDir.into(), root_handle, 0, 0)
            .await
            .unwrap();

        let filenames: Vec<_> = entries.iter().map(|e| e.0.as_str()).collect();
        assert!(filenames.contains(&FIRSTNAME));
        assert!(filenames.contains(&LASTNAME));
    }

    #[tokio::test]
    async fn unlink() {
        const FIRSTNAME: &str = "Jean-Luc";
        const LASTNAME: &str = "Picard";
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FIRSTNAME,
                Flags::default(),
                0o644,
                0,
            )
            .await
            .unwrap();
        client
            .link(inode, SpecInodes::RootDir.into(), LASTNAME)
            .await
            .unwrap();
        client
            .unlink(SpecInodes::RootDir.into(), FIRSTNAME)
            .await
            .unwrap();
        let OpenReply {
            handle: root_handle,
            ..
        } = client
            .open(
                SpecInodes::RootDir.into(),
                FlagValue::ReadOnly | FlagValue::Directory,
            )
            .await
            .unwrap();
        let ReadDirReply { entries, .. } = client
            .read_dir(SpecInodes::RootDir.into(), root_handle, 0, 0)
            .await
            .unwrap();

        let filenames: Vec<_> = entries.iter().map(|e| e.0.as_str()).collect();
        assert!(filenames.contains(&LASTNAME));
        assert!(!filenames.contains(&FIRSTNAME));
    }

    #[tokio::test]
    async fn delete() {
        const FILENAME: &str = "MANIFESTO.tex";
        let case = new_tpm_test_case().await;
        let client = &case.client;

        client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                Flags::default(),
                0o644,
                0,
            )
            .await
            .unwrap();
        client
            .unlink(SpecInodes::RootDir.into(), FILENAME)
            .await
            .unwrap();
        let OpenReply {
            handle: root_handle,
            ..
        } = client
            .open(
                SpecInodes::RootDir.into(),
                FlagValue::ReadOnly | FlagValue::Directory,
            )
            .await
            .unwrap();
        let ReadDirReply { entries, .. } = client
            .read_dir(SpecInodes::RootDir.into(), root_handle, 0, 0)
            .await
            .unwrap();

        let filenames: Vec<_> = entries.iter().map(|e| e.0.as_str()).collect();
        assert!(!filenames.contains(&FILENAME));
    }

    #[tokio::test]
    async fn read_meta() {
        const FILENAME: &str = "kibosh.txt";
        const EXPECTED: u32 = 0o600;
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let before_create = Epoch::now();
        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                EXPECTED,
                0,
            )
            .await
            .unwrap();
        let before_read = Epoch::now();
        let ReadMetaReply { attrs, .. } = client.read_meta(inode, Some(handle)).await.unwrap();

        let actual = attrs.mode;
        assert_eq!(FileType::Reg | EXPECTED, actual);
        assert!(before_create <= attrs.ctime && attrs.ctime <= before_read);
        assert!(before_create <= attrs.mtime && attrs.mtime <= before_read);
        assert!(before_create <= attrs.atime && attrs.atime <= before_read);
        assert_eq!(attrs.block_id.inode, inode);
        assert_eq!(attrs.size, 0);
        assert!(attrs.tags.is_empty());
    }

    #[tokio::test]
    async fn write_meta() {
        fn assert_eq(expected: &Attrs, actual: &BlockMetaSecrets) {
            assert_eq!(expected.mode, actual.mode);
            assert_eq!(expected.uid, actual.uid);
            assert_eq!(expected.gid, actual.gid);
            assert_eq!(expected.atime, actual.atime);
            assert_eq!(expected.mtime, actual.mtime);
            assert_eq!(expected.ctime, actual.ctime);
            assert_eq!(expected.tags.len(), actual.tags.len());
            for (key, expected_value) in expected.tags.iter() {
                let actual_value = actual.tags.get(key).unwrap();
                assert_eq!(expected_value, actual_value);
            }
        }

        const FILENAME: &str = "word_salad.docx";
        let expected = Attrs {
            mode: 0o600,
            uid: 9290,
            gid: 2190,
            atime: 23193.into(),
            mtime: 53432.into(),
            ctime: 87239.into(),
            tags: Vec::new(),
        };
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                expected.mode | 0o011,
                0,
            )
            .await
            .unwrap();
        let WriteMetaReply { attrs, .. } = client
            .write_meta(inode, Some(handle), expected.clone(), AttrsSet::ALL)
            .await
            .unwrap();
        assert_eq(&expected, &attrs);
        let ReadMetaReply { attrs, .. } = client.read_meta(inode, Some(handle)).await.unwrap();

        assert_eq(&expected, &attrs);
    }

    #[tokio::test]
    async fn allocate_when_empty() {
        const FILENAME: &str = "output.dat";
        const EXPECTED: &[u8] = &[0u8; 8];
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        client
            .allocate(inode, handle, EXPECTED.len() as u64)
            .await
            .unwrap();
        let actual = client
            .read(inode, handle, 0, EXPECTED.len() as u64, |reply| {
                ready(Vec::from(reply.data))
            })
            .await
            .unwrap();

        assert_eq!(EXPECTED, actual);
    }

    #[tokio::test]
    async fn allocate_with_data_present() {
        const FILENAME: &str = "output.dat";
        const EXPECTED: &[u8] = &[1, 1, 1, 1, 0, 0, 0, 0];
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        client.write(inode, handle, 0, &[1, 1, 1, 1]).await.unwrap();
        client
            .allocate(inode, handle, EXPECTED.len() as u64)
            .await
            .unwrap();
        let actual = client
            .read(inode, handle, 0, EXPECTED.len() as u64, |reply| {
                ready(Vec::from(reply.data))
            })
            .await
            .unwrap();

        assert_eq!(EXPECTED, actual);
    }

    #[tokio::test]
    async fn forget() {
        const FILENAME: &str = "seed.dat";
        let case = new_tpm_test_case().await;
        let client = &case.client;

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite.into(),
                0o644,
                0,
            )
            .await
            .unwrap();
        client.close(inode, handle).await.unwrap();
        let result = client.forget(inode, 1).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn add_readcap() {
        const FILENAME: &str = "net";
        let case = new_tpm_test_case().await;
        let client = &case.client;
        let creds = ConcreteCreds::generate().unwrap();

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                FILENAME,
                FlagValue::ReadWrite | FlagValue::Directory,
                0o755,
                0,
            )
            .await
            .unwrap();
        client
            .add_readcap(inode, handle, creds.concrete_pub())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn grant_access_to_root() {
        let case = new_tpm_test_case().await;
        let client = &case.client;
        let mut creds = ConcreteCreds::generate().unwrap();
        let root_creds = case.harness.root_creds().unwrap();
        let writecap = root_creds
            .issue_writecap(
                creds.principal(),
                &mut std::iter::empty(),
                Epoch::now() + Duration::from_secs(3600),
            )
            .unwrap();
        creds.set_writecap(writecap).unwrap();
        let expected = IssuedProcRec {
            addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
            pub_creds: creds.concrete_pub(),
            writecap: creds.writecap().unwrap().to_owned(),
            authz_attrs: AuthzAttrs {
                uid: 9001,
                gid: 9001,
                supp_gids: vec![12, 41, 19],
            },
        };

        client
            .grant_access(SpecInodes::RootDir.into(), expected.clone())
            .await
            .unwrap();
        let LookupReply { inode, entry, .. } = client
            .lookup(SpecInodes::RootDir.into(), &creds.principal().to_string())
            .await
            .unwrap();
        let OpenReply { handle, .. } = client
            .open(inode, FlagValue::ReadOnly.into())
            .await
            .unwrap();
        let record = client
            .read(inode, handle, 0, entry.attr.size, |reply| {
                ready(from_slice::<ProcRec>(reply.data))
            })
            .await
            .unwrap()
            .unwrap();
        let actual = record.validate().unwrap();

        assert_eq!(expected, actual);
    }

    #[tokio::test]
    async fn grant_access_to_non_root_dir() {
        const DIRNAME: &str = "var";
        let case = new_tpm_test_case().await;
        let client = &case.client;
        let mut creds = ConcreteCreds::generate().unwrap();
        let root_creds = case.harness.root_creds().unwrap();
        let writecap = root_creds
            .issue_writecap(
                creds.principal(),
                &mut [DIRNAME].into_iter(),
                Epoch::now() + Duration::from_secs(3600),
            )
            .unwrap();
        creds.set_writecap(writecap).unwrap();
        let expected = IssuedProcRec {
            addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
            pub_creds: creds.concrete_pub(),
            writecap: creds.writecap().unwrap().to_owned(),
            authz_attrs: AuthzAttrs {
                uid: 9001,
                gid: 9001,
                supp_gids: vec![12, 41, 19],
            },
        };

        let CreateReply { inode, handle, .. } = client
            .create(
                SpecInodes::RootDir.into(),
                DIRNAME,
                FlagValue::Directory | FlagValue::ReadWrite,
                0o755,
                0,
            )
            .await
            .unwrap();
        client.close(inode, handle).await.unwrap();
        client.grant_access(inode, expected.clone()).await.unwrap();
        let LookupReply {
            inode: record_inode,
            entry,
            ..
        } = client
            .lookup(inode, &creds.principal().to_string())
            .await
            .unwrap();
        let OpenReply {
            handle: record_handle,
            ..
        } = client
            .open(record_inode, FlagValue::ReadOnly.into())
            .await
            .unwrap();
        let record = client
            .read(record_inode, record_handle, 0, entry.attr.size, |reply| {
                ready(from_slice::<ProcRec>(reply.data))
            })
            .await
            .unwrap()
            .unwrap();
        let actual = record.validate().unwrap();

        assert_eq!(expected, actual);
    }

    #[tokio::test]
    async fn grant_access_non_root_user() {
        const ROOT_FILE: &str = "root.txt";
        const USER_FILE: &str = "user.txt";
        let user_tpm = SwtpmHarness::new().unwrap();
        let case = new_tpm_test_case().await;
        let client = &case.client;
        let root_creds = case.harness.root_creds().unwrap();
        let user_creds = {
            let cred_store = TpmCredStore::from_context(
                user_tpm.context().unwrap(),
                user_tpm.state_path().to_owned(),
            )
            .unwrap();
            let mut creds = cred_store.node_creds().unwrap();
            let writecap = root_creds
                .issue_writecap(
                    creds.principal(),
                    &mut std::iter::empty(),
                    Epoch::now() + Duration::from_secs(3600),
                )
                .unwrap();
            cred_store
                .assign_node_writecap(&mut creds, writecap)
                .unwrap();
            creds
        };
        let expected = IssuedProcRec {
            addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
            pub_creds: user_creds.concrete_pub(),
            writecap: user_creds.writecap().unwrap().to_owned(),
            authz_attrs: AuthzAttrs {
                uid: 9001,
                gid: 9001,
                supp_gids: vec![12, 41, 19],
            },
        };
        let root_inode = SpecInodes::RootDir.into();

        client
            .grant_access(root_inode, expected.clone())
            .await
            .unwrap();
        // Note that non-root users do not have permission to write to ROOT_FILE, but
        // UID 9001 has permission to write to USER_FILE.
        client
            .create(root_inode, ROOT_FILE, FlagValue::ReadWrite.into(), 0o644, 0)
            .await
            .unwrap();
        let CreateReply { inode, handle, .. } = client
            .create(root_inode, USER_FILE, FlagValue::ReadWrite.into(), 0o644, 0)
            .await
            .unwrap();
        let mut attrs = Attrs::default();
        attrs.uid = expected.authz_attrs.uid;
        attrs.gid = expected.authz_attrs.gid;
        client
            .write_meta(inode, Some(handle), attrs, AttrsSet::UID | AttrsSet::GID)
            .await
            .unwrap();

        let node_creds = case.harness.cred_store().node_creds().unwrap();
        let bind_path = node_creds.writecap().unwrap().bind_path();
        let block_addr = Arc::new(BlockAddr::new(LOCALHOST, Arc::new(bind_path)));
        let tx = bttp::Transmitter::new(block_addr, Arc::new(user_creds))
            .await
            .unwrap();
        let client = FsClient::new(tx);
        let root_dir = SpecInodes::RootDir.value();

        let LookupReply { inode, .. } = client.lookup(root_dir, USER_FILE).await.unwrap();
        let result = client.open(inode, FlagValue::ReadWrite.into()).await;
        assert!(result.is_ok());
        let LookupReply { inode, .. } = client.lookup(root_dir, ROOT_FILE).await.unwrap();
        let result = client.open(inode, FlagValue::ReadWrite.into()).await;
        let err = result.err().unwrap().to_string();

        assert_eq!("write access denied", err);
    }
}

#[cfg(test)]
mod config_tests {
    use super::BtfsdConfig;
    use std::{
        net::{IpAddr, SocketAddr},
        path::PathBuf,
    };

    use btconfig::CredStoreConfig;
    use btconsole::BtConsoleConfig;
    use figment::Jail;

    #[test]
    fn cred_store_file_path() {
        Jail::expect_with(|jail| {
            let expected = PathBuf::from("./file_credstore");
            jail.set_env("BT_CREDSTORE_TYPE", "File");
            jail.set_env("BT_CREDSTORE_PATH", expected.display());

            let config = BtfsdConfig::new().unwrap();

            let success = if let CredStoreConfig::File { path: actual } = config.cred_store {
                expected == actual
            } else {
                false
            };
            assert!(success);

            Ok(())
        })
    }

    #[test]
    fn cred_store_tpm_path_tabrmd() {
        Jail::expect_with(|jail| {
            let expected_path = PathBuf::from("./tpm_credstore");
            let expected_tabrmd = String::from("bus_type=session");
            jail.set_env("BT_CREDSTORE_TYPE", "Tpm");
            jail.set_env("BT_CREDSTORE_PATH", expected_path.display());
            jail.set_env("BT_CREDSTORE_TABRMD", expected_tabrmd.as_str());

            let config = BtfsdConfig::new().unwrap();

            let success = if let CredStoreConfig::Tpm {
                path: actual_path,
                tabrmd: actual_tabrmd,
            } = config.cred_store
            {
                expected_path == actual_path && expected_tabrmd == actual_tabrmd
            } else {
                false
            };
            assert!(success);

            Ok(())
        })
    }

    #[test]
    fn ip_addr() {
        Jail::expect_with(|jail| {
            let expected = IpAddr::from([172, 0, 0, 1]);
            jail.set_env("BT_IPADDR", expected);

            let config = BtfsdConfig::new().unwrap();

            assert_eq!(expected, config.ip_addr);

            Ok(())
        })
    }

    #[test]
    fn block_dir() {
        Jail::expect_with(|jail| {
            let expected = PathBuf::from("/tmp/blocks");
            jail.set_env("BT_BLOCKDIR", expected.display());

            let config = BtfsdConfig::new().unwrap();

            assert_eq!(expected, config.block_dir);

            Ok(())
        })
    }

    #[test]
    fn console() {
        Jail::expect_with(|jail| {
            let expected_addr = SocketAddr::from(([127, 0, 0, 42], 4129));
            let expected_dist_path = PathBuf::from("/var/www");
            jail.set_env("BT_CONSOLE_ADDR", expected_addr);
            jail.set_env("BT_CONSOLE_DISTPATH", expected_dist_path.display());
            let expected = BtConsoleConfig::new(expected_addr, expected_dist_path);

            let config = BtfsdConfig::new().unwrap();

            assert_eq!(expected, config.console.unwrap());

            Ok(())
        })
    }
}