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
// EndBASIC
// Copyright 2021 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Commands to interact with the cloud service.

use crate::*;
use async_trait::async_trait;
use endbasic_core::ast::{ArgSep, ExprType};
use endbasic_core::compiler::{
    ArgSepSyntax, RepeatedSyntax, RepeatedTypeSyntax, RequiredValueSyntax, SingularArgSyntax,
};
use endbasic_core::exec::{Machine, Scope};
use endbasic_core::syms::{
    CallError, CallResult, Callable, CallableMetadata, CallableMetadataBuilder,
};
use endbasic_core::LineCol;
use endbasic_std::console::{is_narrow, read_line, read_line_secure, refill_and_print, Console};
use endbasic_std::storage::{FileAcls, Storage};
use endbasic_std::strings::parse_boolean;
use std::borrow::Cow;
use std::cell::RefCell;
use std::rc::Rc;
use std::str;

/// Category description for all symbols provided by this module.
const CATEGORY: &str = "Cloud access
The EndBASIC service is a cloud service that provides online file sharing across users of \
EndBASIC and the public.
Files that have been shared publicly can be accessed without an account via the cloud:// file \
system scheme.  All you have to do is mount a user's cloud drive and then access the files as you \
would with your own.  For example:
    MOUNT \"X\", \"cloud://user-123\": DIR \"X:\"
To upload files and share them, you need to create an account.  During account creation time, you \
are assigned a unique, persistent drive in which you can store files privately.  You can later \
choose to share individual files with the public or with specific individuals, at which point \
those people will be able to see them by mounting your drive.
If you have any questions or experience any problems while interacting with the cloud service, \
please contact support@endbasic.dev.";

/// The `LOGIN` command.
pub struct LoginCommand {
    metadata: CallableMetadata,
    service: Rc<RefCell<dyn Service>>,
    console: Rc<RefCell<dyn Console>>,
    storage: Rc<RefCell<Storage>>,
}

impl LoginCommand {
    /// Creates a new `LOGIN` command.
    pub fn new(
        service: Rc<RefCell<dyn Service>>,
        console: Rc<RefCell<dyn Console>>,
        storage: Rc<RefCell<Storage>>,
    ) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("LOGIN")
                .with_syntax(&[
                    (
                        &[SingularArgSyntax::RequiredValue(
                            RequiredValueSyntax {
                                name: Cow::Borrowed("username"),
                                vtype: ExprType::Text,
                            },
                            ArgSepSyntax::End,
                        )],
                        None,
                    ),
                    (
                        &[
                            SingularArgSyntax::RequiredValue(
                                RequiredValueSyntax {
                                    name: Cow::Borrowed("username"),
                                    vtype: ExprType::Text,
                                },
                                ArgSepSyntax::Exactly(ArgSep::Long),
                            ),
                            SingularArgSyntax::RequiredValue(
                                RequiredValueSyntax {
                                    name: Cow::Borrowed("password"),
                                    vtype: ExprType::Text,
                                },
                                ArgSepSyntax::End,
                            ),
                        ],
                        None,
                    ),
                ])
                .with_category(CATEGORY)
                .with_description(
                    "Logs into the user's account.
On a successful login, this mounts your personal drive under the CLOUD:/ location, which you can \
access with any other file-related commands.  Using the cloud:// file system scheme, you can mount \
other people's drives with the MOUNT command.
To create an account, use the SIGNUP command.",
                )
                .build(),
            service,
            console,
            storage,
        })
    }

    /// Performs the login workflow against the server.
    async fn do_login(&self, username: &str, password: &str) -> CallResult {
        let response = self.service.borrow_mut().login(username, password).await?;

        {
            let console = &mut *self.console.borrow_mut();
            if !is_narrow(&*console) && !response.motd.is_empty() {
                console.print("")?;
                console.print("----- BEGIN SERVER MOTD -----")?;
                for line in response.motd {
                    refill_and_print(console, [line], "")?;
                }
                console.print("-----  END SERVER MOTD  -----")?;
                console.print("")?;
            }
        }

        let mut storage = self.storage.borrow_mut();
        storage.mount("CLOUD", &format!("cloud://{}", username))?;

        Ok(())
    }
}

#[async_trait(?Send)]
impl Callable for LoginCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(&self, mut scope: Scope<'_>, _machine: &mut Machine) -> CallResult {
        if self.service.borrow().is_logged_in() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Cannot LOGIN again before LOGOUT".to_owned(),
            )
            .into());
        }

        let username = scope.pop_string();
        let password = if scope.nargs() == 0 {
            read_line_secure(&mut *self.console.borrow_mut(), "Password: ").await?
        } else {
            debug_assert_eq!(1, scope.nargs());
            scope.pop_string()
        };

        self.do_login(&username, &password).await
    }
}

/// The `LOGOUT` command.
pub struct LogoutCommand {
    metadata: CallableMetadata,
    service: Rc<RefCell<dyn Service>>,
    console: Rc<RefCell<dyn Console>>,
    storage: Rc<RefCell<Storage>>,
}

impl LogoutCommand {
    /// Creates a new `LOGOUT` command.
    pub fn new(
        service: Rc<RefCell<dyn Service>>,
        console: Rc<RefCell<dyn Console>>,
        storage: Rc<RefCell<Storage>>,
    ) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("LOGOUT")
                .with_syntax(&[(&[], None)])
                .with_category(CATEGORY)
                .with_description(
                    "Logs the user out of their account.
Unmounts the CLOUD drive that was mounted by the LOGIN command.  As a consequence of this, running \
LOGOUT from within the CLOUD drive will fail.",
                )
                .build(),
            service,
            console,
            storage,
        })
    }
}

#[async_trait(?Send)]
impl Callable for LogoutCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(&self, scope: Scope<'_>, _machine: &mut Machine) -> CallResult {
        debug_assert_eq!(0, scope.nargs());

        if !self.service.borrow().is_logged_in() {
            // TODO(jmmv): Now that the access tokens are part of the service, we can easily allow
            // logging in more than once within a session.  Consider adding a LOGOUT command first
            // to make it easier to handle the CLOUD: drive on a second login.
            return Err(
                io::Error::new(io::ErrorKind::InvalidInput, "Must LOGIN first".to_owned()).into()
            );
        }

        let unmounted = match self.storage.borrow_mut().unmount("CLOUD") {
            Ok(()) => true,
            Err(e) if e.kind() == io::ErrorKind::NotFound => false,
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                return Err(io::Error::new(
                    e.kind(),
                    "Cannot log out while the CLOUD drive is active".to_owned(),
                )
                .into())
            }
            Err(e) => return Err(io::Error::new(e.kind(), format!("Cannot log out: {}", e)).into()),
        };

        self.service.borrow_mut().logout().await?;

        {
            let mut console = self.console.borrow_mut();
            console.print("")?;
            if unmounted {
                console.print("    Unmounted CLOUD drive")?;
            }
            console.print("    Good bye!")?;
            console.print("")?;
        }

        Ok(())
    }
}

/// The `SHARE` command.
///
/// Note that this command is not exclusively for use by the cloud drive as this interacts with the
/// generic storage layer.  As a result, one might say that this command belongs where other disk
/// commands such as `DIR` are defined, but given that ACLs are primarily a cloud concept in our
/// case, it makes sense to keep it here.
pub struct ShareCommand {
    metadata: CallableMetadata,
    service: Rc<RefCell<dyn Service>>,
    console: Rc<RefCell<dyn Console>>,
    storage: Rc<RefCell<Storage>>,
    exec_base_url: String,
}

impl ShareCommand {
    /// Creates a new `SHARE` command.
    pub fn new<S: Into<String>>(
        service: Rc<RefCell<dyn Service>>,
        console: Rc<RefCell<dyn Console>>,
        storage: Rc<RefCell<Storage>>,
        exec_base_url: S,
    ) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("SHARE")
                .with_syntax(&[(
                    &[SingularArgSyntax::RequiredValue(
                        RequiredValueSyntax {
                            name: Cow::Borrowed("filename"),
                            vtype: ExprType::Text,
                        },
                        ArgSepSyntax::Exactly(ArgSep::Long),
                    )],
                    Some(&RepeatedSyntax {
                        name: Cow::Borrowed("acl"),
                        type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Text),
                        sep: ArgSepSyntax::Exactly(ArgSep::Long),
                        require_one: false,
                        allow_missing: false,
                    }),
                )])
                .with_category(CATEGORY)
                .with_description(
                    "Displays or modifies the ACLs of a file.
If given only a filename$, this command prints out the ACLs of the file.
Otherwise, when given a list of ACL changes, applies those changes to the file.  The acl1$ to \
aclN$ arguments are strings of the form \"username+r\" or \"username-r\", where the former adds \
\"username\" to the users allowed to read the file, and the latter removes \"username\" from the \
list of users allowed to read the file.
You can use the special \"public+r\" ACL to share a file with everyone.  These files can be \
auto-run via the web interface using the special URL that the command prints on success.
Note that this command only works for cloud-based drives as it is designed to share files \
among users of the EndBASIC service.",
                )
                .build(),
            service,
            console,
            storage,
            exec_base_url: exec_base_url.into(),
        })
    }
}

impl ShareCommand {
    /// Parses a textual ACL specification and adds it to `add` or `remove.
    fn parse_acl(
        mut acl: String,
        acl_pos: LineCol,
        add: &mut FileAcls,
        remove: &mut FileAcls,
    ) -> Result<(), CallError> {
        let change = if acl.len() < 3 { String::new() } else { acl.split_off(acl.len() - 2) };
        let username = acl; // For clarity after splitting off the ACL change request.
        match (username, change.as_str()) {
            (username, "+r") if !username.is_empty() => add.add_reader(username),
            (username, "+R") if !username.is_empty() => add.add_reader(username),
            (username, "-r") if !username.is_empty() => remove.add_reader(username),
            (username, "-R") if !username.is_empty() => remove.add_reader(username),
            (username, change) => {
                return Err(CallError::ArgumentError(
                    acl_pos,
                    format!(
                        "Invalid ACL '{}{}': must be of the form \"username+r\" or \"username-r\"",
                        username, change
                    ),
                ))
            }
        }
        Ok(())
    }

    /// Checks if a file is publicly readable by inspecting a set of ACLs.
    fn has_public_acl(acls: &FileAcls) -> bool {
        for reader in acls.readers() {
            if reader.to_lowercase() == "public" {
                return true;
            }
        }
        false
    }

    /// Fetches and prints the ACLs for `filename`.
    async fn show_acls(&self, filename: &str) -> CallResult {
        let acls = self.storage.borrow().get_acls(filename).await?;

        let mut console = self.console.borrow_mut();
        console.print("")?;
        if acls.readers().is_empty() {
            console.print(&format!("    No ACLs on {}", filename))?;
        } else {
            console.print(&format!("    Reader ACLs on {}:", filename))?;
            for acl in acls.readers() {
                console.print(&format!("    {}", acl))?;
            }
        }
        console.print("")?;

        Ok(())
    }
}

#[async_trait(?Send)]
impl Callable for ShareCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(&self, mut scope: Scope<'_>, _machine: &mut Machine) -> CallResult {
        debug_assert_ne!(0, scope.nargs());
        let filename = scope.pop_string();

        let mut add = FileAcls::default();
        let mut remove = FileAcls::default();
        while scope.nargs() > 0 {
            let (t, pos) = scope.pop_string_with_pos();
            ShareCommand::parse_acl(t, pos, &mut add, &mut remove)?;
        }

        if add.is_empty() && remove.is_empty() {
            return self.show_acls(&filename).await;
        }

        self.storage.borrow_mut().update_acls(&filename, &add, &remove).await?;

        if Self::has_public_acl(&add) {
            let filename = match filename.split_once('/') {
                Some((_drive, path)) => path,
                None => &filename,
            };

            let mut console = self.console.borrow_mut();
            console.print("")?;
            refill_and_print(
                &mut *console,
                [
                    "You have made the file publicly readable.  As a result, other people can now \
auto-run your public file by visiting:",
                    &format!(
                        "{}?run={}/{}",
                        self.exec_base_url,
                        self.service
                            .borrow()
                            .logged_in_username()
                            .expect("SHARE can only succeed against logged in cloud drives"),
                        filename
                    ),
                ],
                "    ",
            )?;
            console.print("")?;
        }

        Ok(())
    }
}

/// Checks if a password is sufficiently complex and returns an error when it isn't.
fn validate_password_complexity(password: &str) -> Result<(), &'static str> {
    if password.len() < 8 {
        return Err("Must be at least 8 characters long");
    }

    let mut alphabetic = false;
    let mut numeric = false;
    for ch in password.chars() {
        if ch.is_alphabetic() {
            alphabetic = true;
        } else if ch.is_numeric() {
            numeric = true;
        }
    }

    if !alphabetic || !numeric {
        return Err("Must contain letters and numbers");
    }

    Ok(())
}

/// The `SIGNUP` command.
pub struct SignupCommand {
    metadata: CallableMetadata,
    service: Rc<RefCell<dyn Service>>,
    console: Rc<RefCell<dyn Console>>,
}

impl SignupCommand {
    /// Creates a new `SIGNUP` command.
    pub fn new(service: Rc<RefCell<dyn Service>>, console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("SIGNUP")
                .with_syntax(&[(&[], None)])
                .with_category(CATEGORY)
                .with_description(
                    "Creates a new user account interactively.
This command will ask you for your personal information to create an account in the EndBASIC \
cloud service.  You will be asked for confirmation before proceeding.",
                )
                .build(),
            service,
            console,
        })
    }

    /// Tries to read a boolean value until it is valid.  Returns `default` if the user hits enter.
    async fn read_bool(console: &mut dyn Console, prompt: &str, default: bool) -> io::Result<bool> {
        loop {
            match read_line(console, prompt, "", None).await? {
                s if s.is_empty() => return Ok(default),
                s => match parse_boolean(s.trim_end()) {
                    Ok(b) => return Ok(b),
                    Err(_) => {
                        console.print("Invalid input; try again.")?;
                        continue;
                    }
                },
            }
        }
    }

    /// Tries to get a password from the user until it is valid.
    async fn read_password(console: &mut dyn Console) -> io::Result<String> {
        loop {
            let password = read_line_secure(console, "Password: ").await?;
            match validate_password_complexity(&password) {
                Ok(()) => (),
                Err(e) => {
                    console.print(&format!("Invalid password: {}; try again.", e))?;
                    continue;
                }
            }

            let second_password = read_line_secure(console, "Retype password: ").await?;
            if second_password != password {
                console.print("Passwords do not match; try again.")?;
                continue;
            }

            return Ok(password);
        }
    }
}

#[async_trait(?Send)]
impl Callable for SignupCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(&self, scope: Scope<'_>, _machine: &mut Machine) -> CallResult {
        debug_assert_eq!(0, scope.nargs());

        let console = &mut *self.console.borrow_mut();
        console.print("")?;
        refill_and_print(
            console,
            ["Let's gather some information to create your cloud account.",
"You can abort this process at any time by hitting Ctrl+C and you will be given a chance to \
review your inputs before creating the account."],
            "    ",
        )?;
        console.print("")?;

        let username = read_line(console, "Username: ", "", None).await?;
        let password = Self::read_password(console).await?;

        console.print("")?;
        refill_and_print(
            console,
            [
                "We also need your email address to activate your account.",
                "Your email address will be kept on file in case we have to notify you of \
important service issues and will never be made public.  You will be asked if you want to receive \
promotional email messages (like new release announcements) or not, and your selection here will \
have no adverse impact in the service you receive.",
            ],
            "    ",
        )?;
        console.print("")?;

        let email = read_line(console, "Email address: ", "", None).await?;
        let promotional_email =
            Self::read_bool(console, "Receive promotional email (y/N)? ", false).await?;

        console.print("")?;
        refill_and_print(
            console,
            ["We are ready to go. Please review your answers before proceeding."],
            "    ",
        )?;
        console.print("")?;

        console.print(&format!("Username: {}", username))?;
        console.print(&format!("Email address: {}", email))?;
        console.print(&format!(
            "Promotional email: {}",
            if promotional_email { "yes" } else { "no" }
        ))?;
        let proceed = Self::read_bool(console, "Continue (y/N)? ", false).await?;
        if !proceed {
            // TODO(jmmv): This should return an error of some form once we have error handling in
            // the language.
            return Ok(());
        }

        let request = SignupRequest { username, password, email, promotional_email };
        self.service.borrow_mut().signup(&request).await?;

        console.print("")?;
        refill_and_print(
            console,
            ["Your account has been created and is pending activation.",
"Check your email now and look for a message from the EndBASIC Service.  Follow the instructions \
in it to activate your account.  Make sure to check your spam folder.",
"Once your account is activated, come back here and use LOGIN to get started!",
"If you encounter any problems, please contact support@endbasic.dev."],
            "    ",
        )?;
        console.print("")?;

        Ok(())
    }
}

/// Adds all remote manipulation commands for `service` to the `machine`, using `console` to
/// display information and `storage` to manipulate the remote drives.
pub fn add_all<S: Into<String>>(
    machine: &mut Machine,
    service: Rc<RefCell<dyn Service>>,
    console: Rc<RefCell<dyn Console>>,
    storage: Rc<RefCell<Storage>>,
    exec_base_url: S,
) {
    storage
        .borrow_mut()
        .register_scheme("cloud", Box::from(CloudDriveFactory::new(service.clone())));

    machine.add_callable(LoginCommand::new(service.clone(), console.clone(), storage.clone()));
    machine.add_callable(LogoutCommand::new(service.clone(), console.clone(), storage.clone()));
    machine.add_callable(ShareCommand::new(
        service.clone(),
        console.clone(),
        storage,
        exec_base_url,
    ));
    machine.add_callable(SignupCommand::new(service, console));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testutils::*;
    use endbasic_std::{console::CharsXY, testutils::*};

    #[test]
    fn test_cloud_scheme_always_available() {
        let t = ClientTester::default();
        assert!(t.get_storage().borrow().has_scheme("cloud"));
    }

    #[test]
    fn test_login_ok_with_password() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "the-username",
            "the-password",
            Ok(LoginResponse { access_token: AccessToken::new("random token"), motd: vec![] }),
        );
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
        t.run(format!(r#"LOGIN "{}", "{}""#, "the-username", "the-password"))
            .expect_access_token("random token")
            .check();
        assert!(t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_login_ok_ask_password() {
        let t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "the-username",
            "the-password",
            Ok(LoginResponse { access_token: AccessToken::new("random token"), motd: vec![] }),
        );
        let storage = t.get_storage();
        assert!(!storage.borrow().mounted().contains_key("CLOUD"));

        t.get_console().borrow_mut().set_interactive(true);
        let mut exp_output =
            vec![CapturedOut::Write("Password: ".to_string()), CapturedOut::SyncNow];
        for _ in 0.."the-password".len() {
            exp_output.push(CapturedOut::Write("*".to_string()));
        }
        exp_output.push(CapturedOut::Print("".to_owned()));

        t.add_input_chars("the-password")
            .add_input_chars("\n")
            .run(format!(r#"LOGIN "{}""#, "the-username"))
            .expect_access_token("random token")
            .expect_output(exp_output)
            .check();

        assert!(storage.borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_login_skip_motd_on_narrow_console() {
        let mut t = ClientTester::default();
        t.get_console().borrow_mut().set_size_chars(CharsXY::new(10, 0));
        t.get_service().borrow_mut().add_mock_login(
            "the-username",
            "the-password",
            Ok(LoginResponse {
                access_token: AccessToken::new("random token"),
                motd: vec!["first line".to_owned(), "second line".to_owned()],
            }),
        );
        t.run(format!(r#"LOGIN "{}", "{}""#, "the-username", "the-password"))
            .expect_access_token("random token")
            .check();
    }

    #[test]
    fn test_login_show_motd_on_wide_console() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "the-username",
            "the-password",
            Ok(LoginResponse {
                access_token: AccessToken::new("random token"),
                motd: vec!["first line".to_owned(), "second line".to_owned()],
            }),
        );
        t.run(format!(r#"LOGIN "{}", "{}""#, "the-username", "the-password"))
            .expect_prints([
                "",
                "----- BEGIN SERVER MOTD -----",
                "first line",
                "second line",
                "-----  END SERVER MOTD  -----",
                "",
            ])
            .expect_access_token("random token")
            .check();
    }

    #[test]
    fn test_login_bad_credentials() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "bad-user",
            "the-password",
            Err(io::Error::new(io::ErrorKind::PermissionDenied, "Unknown user")),
        );
        t.run(format!(r#"LOGIN "{}", "{}""#, "bad-user", "the-password"))
            .expect_err("1:1: In call to LOGIN: Unknown user")
            .check();
        t.get_service().borrow_mut().add_mock_login(
            "the-username",
            "bad-password",
            Err(io::Error::new(io::ErrorKind::PermissionDenied, "Invalid password")),
        );
        t.run(format!(r#"LOGIN "{}", "{}""#, "the-username", "bad-password"))
            .expect_err("1:1: In call to LOGIN: Invalid password")
            .check();
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_login_twice() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "the-username",
            "the-password",
            Ok(LoginResponse { access_token: AccessToken::new("random token"), motd: vec![] }),
        );
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
        t.run(r#"LOGIN "the-username", "the-password": LOGIN "a", "b""#)
            .expect_access_token("random token")
            .expect_err("1:39: In call to LOGIN: Cannot LOGIN again before LOGOUT")
            .check();
        assert!(t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_login_errors() {
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: expected <username$> | <username$, password$>",
            r#"LOGIN"#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: expected <username$> | <username$, password$>",
            r#"LOGIN "a", "b", "c""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: expected <username$> | <username$, password$>",
            r#"LOGIN , "c""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: expected <username$> | <username$, password$>",
            r#"LOGIN ;"#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: 1:7: INTEGER is not a STRING",
            r#"LOGIN 3"#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: 1:7: INTEGER is not a STRING",
            r#"LOGIN 3, "a""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to LOGIN: 1:12: INTEGER is not a STRING",
            r#"LOGIN "a", 3"#,
        );
    }

    #[tokio::test]
    async fn test_logout_ok_cloud_not_mounted() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().do_login().await;
        t.run(r#"LOGOUT"#).expect_prints(["", "    Good bye!", ""]).check();
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[tokio::test]
    async fn test_logout_ok_unmount_cloud() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().do_login().await;
        t.get_storage().borrow_mut().mount("CLOUD", "memory://").unwrap();
        t.run(r#"LOGOUT"#)
            .expect_prints(["", "    Unmounted CLOUD drive", "    Good bye!", ""])
            .check();
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[tokio::test]
    async fn test_logout_cloud_mounted_and_active() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().do_login().await;
        t.get_storage().borrow_mut().mount("CLOUD", "memory://").unwrap();
        t.get_storage().borrow_mut().cd("CLOUD:/").unwrap();
        t.run(r#"LOGOUT"#)
            .expect_err("1:1: In call to LOGOUT: Cannot log out while the CLOUD drive is active")
            .expect_access_token("$")
            .check();
        assert!(t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_logout_errors() {
        client_check_stmt_compilation_err(
            "1:1: In call to LOGOUT: expected no arguments",
            r#"LOGOUT "a""#,
        );
        client_check_stmt_err("1:1: In call to LOGOUT: Must LOGIN first", r#"LOGOUT"#);
    }

    #[test]
    fn test_login_logout_flow_once() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "u1",
            "p1",
            Ok(LoginResponse { access_token: AccessToken::new("token 1"), motd: vec![] }),
        );
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
        t.run(r#"LOGIN "u1", "p1": LOGOUT"#)
            .expect_prints(["", "    Unmounted CLOUD drive", "    Good bye!", ""])
            .check();
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_login_logout_flow_multiple() {
        let mut t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_login(
            "u1",
            "p1",
            Ok(LoginResponse { access_token: AccessToken::new("token 1"), motd: vec![] }),
        );
        t.get_service().borrow_mut().add_mock_login(
            "u2",
            "p2",
            Ok(LoginResponse { access_token: AccessToken::new("token 2"), motd: vec![] }),
        );
        assert!(!t.get_storage().borrow().mounted().contains_key("CLOUD"));
        t.run(r#"LOGIN "u1", "p1": LOGOUT: LOGIN "u2", "p2""#)
            .expect_prints(["", "    Unmounted CLOUD drive", "    Good bye!", ""])
            .expect_access_token("token 2")
            .check();
        assert!(t.get_storage().borrow().mounted().contains_key("CLOUD"));
    }

    #[test]
    fn test_share_parse_acl_ok() {
        let mut add = FileAcls::default();
        let mut remove = FileAcls::default();

        let lc = LineCol { line: 0, col: 0 };

        ShareCommand::parse_acl("user1+r".to_owned(), lc, &mut add, &mut remove).unwrap();
        ShareCommand::parse_acl("user2+R".to_owned(), lc, &mut add, &mut remove).unwrap();
        ShareCommand::parse_acl("X-r".to_owned(), lc, &mut add, &mut remove).unwrap();
        ShareCommand::parse_acl("Y-R".to_owned(), lc, &mut add, &mut remove).unwrap();
        assert_eq!(&["user1".to_owned(), "user2".to_owned()], add.readers());
        assert_eq!(&["X".to_owned(), "Y".to_owned()], remove.readers());
    }

    #[test]
    fn test_share_has_public_acls() {
        let mut acls = FileAcls::default();
        assert!(!ShareCommand::has_public_acl(&acls));
        acls.add_reader("foo");
        assert!(!ShareCommand::has_public_acl(&acls));
        acls.add_reader("PuBlIc");
        assert!(ShareCommand::has_public_acl(&acls));
    }

    #[test]
    fn test_share_parse_acl_errors() {
        let mut add = FileAcls::default().with_readers(["before1".to_owned()]);
        let mut remove = FileAcls::default().with_readers(["before2".to_owned()]);

        for acl in &["", "r", "+r", "-r", "foo+", "bar-"] {
            let err = ShareCommand::parse_acl(
                acl.to_string(),
                LineCol { line: 12, col: 34 },
                &mut add,
                &mut remove,
            )
            .unwrap_err();
            let message = format!("12:34: {:?}", err);
            assert!(message.contains("Invalid ACL"));
            assert!(message.contains(acl));
        }

        assert_eq!(&["before1".to_owned()], add.readers());
        assert_eq!(&["before2".to_owned()], remove.readers());
    }

    #[tokio::test]
    async fn test_share_print_no_acls() {
        let mut t = ClientTester::default();
        t.get_storage().borrow_mut().put("MEMORY:/FOO", "").await.unwrap();
        t.run(r#"SHARE "MEMORY:/FOO""#)
            .expect_prints(["", "    No ACLs on MEMORY:/FOO", ""])
            .expect_file("MEMORY:/FOO", "")
            .check();
    }

    #[tokio::test]
    async fn test_share_print_some_acls() {
        let mut t = ClientTester::default();
        {
            let storage = t.get_storage();
            let mut storage = storage.borrow_mut();
            storage.put("MEMORY:/FOO", "").await.unwrap();
            storage
                .update_acls(
                    "MEMORY:/FOO",
                    &FileAcls::default().with_readers(["some".to_owned(), "person".to_owned()]),
                    &FileAcls::default(),
                )
                .await
                .unwrap();
        }
        t.run(r#"SHARE "MEMORY:/FOO""#)
            .expect_prints(["", "    Reader ACLs on MEMORY:/FOO:", "    person", "    some", ""])
            .expect_file("MEMORY:/FOO", "")
            .check();
    }

    #[tokio::test]
    async fn test_share_make_public() {
        let mut t = ClientTester::default();
        t.get_storage().borrow_mut().put("MEMORY:/FOO.BAS", "").await.unwrap();
        t.get_service().borrow_mut().do_login().await;
        let mut checker = t.run(r#"SHARE "MEMORY:/FOO.BAS", "Public+r""#);
        let output = flatten_output(checker.take_captured_out());
        checker.expect_file("MEMORY:/FOO.BAS", "").expect_access_token("$").check();
        assert!(output.contains("https://repl.example.com/?run=logged-in-username/FOO.BAS"));
    }

    // TODO(jmmv): Add forgotten tests for SHARE modifying ACLs.

    #[test]
    fn test_share_errors() {
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: expected filename$[, acl1$, .., aclN$]",
            r#"SHARE"#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: 1:7: INTEGER is not a STRING",
            r#"SHARE 1"#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: expected filename$[, acl1$, .., aclN$]",
            r#"SHARE , "a""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: expected filename$[, acl1$, .., aclN$]",
            r#"SHARE "a"; "b""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: expected filename$[, acl1$, .., aclN$]",
            r#"SHARE "a", "b"; "c""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: expected filename$[, acl1$, .., aclN$]",
            r#"SHARE "a", , "b""#,
        );
        client_check_stmt_compilation_err(
            "1:1: In call to SHARE: 1:12: INTEGER is not a STRING",
            r#"SHARE "a", 3, "b""#,
        );
        client_check_stmt_err(
            r#"1:1: In call to SHARE: 1:12: Invalid ACL 'foobar': must be of the form "username+r" or "username-r""#,
            r#"SHARE "a", "foobar""#,
        );
    }

    #[test]
    fn test_validate_password_complexity_ok() {
        validate_password_complexity("theP4ssword").unwrap();
    }

    #[test]
    fn test_validate_password_complexity_error() {
        validate_password_complexity("a").unwrap_err().contains("8 characters");
        validate_password_complexity("abcdefg").unwrap_err().contains("8 characters");
        validate_password_complexity("long enough").unwrap_err().contains("letters and numbers");
        validate_password_complexity("1234567890").unwrap_err().contains("letters and numbers");
    }

    #[test]
    fn test_signup_ok() {
        let t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_signup(
            SignupRequest {
                username: "the-username".to_owned(),
                password: "theP4ssword".to_owned(),
                email: "some@example.com".to_owned(),
                promotional_email: false,
            },
            Ok(()),
        );
        t.get_console().borrow_mut().set_interactive(true);

        let mut t = t
            .add_input_chars("the-username\n")
            .add_input_chars("theP4ssword\n")
            .add_input_chars("theP4ssword\n")
            .add_input_chars("some@example.com\n")
            .add_input_chars("\n") // Default promotional email answer.
            .add_input_chars("y\n"); // Confirmation.
        let mut c = t.run("SIGNUP".to_owned());
        let output = flatten_output(c.take_captured_out());
        c.check();

        assert!(output.contains("Username: the-username"));
        assert!(output.contains("Email address: some@example.com"));
        assert!(output.contains("Promotional email: no"));
    }

    #[test]
    fn test_signup_ok_with_promotional_email() {
        let t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_signup(
            SignupRequest {
                username: "foobar".to_owned(),
                password: "AnotherPassword5".to_owned(),
                email: "other@example.com".to_owned(),
                promotional_email: true,
            },
            Ok(()),
        );
        t.get_console().borrow_mut().set_interactive(true);

        let mut t = t
            .add_input_chars("foobar\n")
            .add_input_chars("AnotherPassword5\n")
            .add_input_chars("AnotherPassword5\n")
            .add_input_chars("other@example.com\n")
            .add_input_chars("yes\n") // Promotional email answer.
            .add_input_chars("y\n"); // Confirmation.
        let mut c = t.run("SIGNUP".to_owned());
        let output = flatten_output(c.take_captured_out());
        c.check();

        assert!(output.contains("Username: foobar"));
        assert!(output.contains("Email address: other@example.com"));
        assert!(output.contains("Promotional email: yes"));
    }

    #[test]
    fn test_signup_ok_retry_inputs() {
        let t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_signup(
            SignupRequest {
                username: "the-username".to_owned(),
                password: "AnotherPassword7".to_owned(),
                email: "some@example.com".to_owned(),
                promotional_email: false,
            },
            Ok(()),
        );
        t.get_console().borrow_mut().set_interactive(true);

        let mut t = t
            .add_input_chars("the-username\n")
            .add_input_chars("too simple\n") // Password complexity failure.
            .add_input_chars("123456\n") // Password complexity failure.
            .add_input_chars("AnotherPassword7\n")
            .add_input_chars("does not match\n") // Second password doesn't match.
            .add_input_chars("too simple\n") // Password complexity failure.
            .add_input_chars("123456\n") // Password complexity failure.
            .add_input_chars("AnotherPassword7\n")
            .add_input_chars("AnotherPassword7\n")
            .add_input_chars("some@example.com\n")
            .add_input_chars("123\n") // Promotional email answer failure.
            .add_input_chars("n\n") // Promotional email answer.
            .add_input_chars("foo\n") // Confirmation failure.
            .add_input_chars("y\n"); // Confirmation.
        let mut c = t.run("SIGNUP".to_owned());
        let output = flatten_output(c.take_captured_out());
        c.check();

        assert!(output.contains("Invalid input"));
        assert!(output.contains("Invalid password: Must contain"));
        assert!(output.contains("Passwords do not match"));
        assert!(output.contains("Username: the-username"));
        assert!(output.contains("Email address: some@example.com"));
        assert!(output.contains("Promotional email: no"));
    }

    #[test]
    fn test_signup_abort() {
        let t = ClientTester::default();
        t.get_console().borrow_mut().set_interactive(true);

        let mut t = t
            .add_input_chars("the-username\n")
            .add_input_chars("theP4ssword\n")
            .add_input_chars("theP4ssword\n")
            .add_input_chars("some@example.com\n")
            .add_input_chars("\n") // Default promotional email answer.
            .add_input_chars("\n"); // Default confirmation.
        let mut c = t.run("SIGNUP".to_owned());
        let output = flatten_output(c.take_captured_out());
        c.check();

        assert!(output.contains("Username: the-username"));
        assert!(output.contains("Email address: some@example.com"));
        assert!(output.contains("Promotional email: no"));
    }

    #[test]
    fn test_singup_errors() {
        client_check_stmt_compilation_err(
            "1:1: In call to SIGNUP: expected no arguments",
            r#"SIGNUP "a""#,
        );
    }

    #[test]
    fn test_signup_process_error() {
        let t = ClientTester::default();
        t.get_service().borrow_mut().add_mock_signup(
            SignupRequest {
                username: "the-username".to_owned(),
                password: "theP4ssword".to_owned(),
                email: "some@example.com".to_owned(),
                promotional_email: false,
            },
            Err(io::Error::new(io::ErrorKind::AlreadyExists, "Some error")),
        );
        t.get_console().borrow_mut().set_interactive(true);

        let mut t = t
            .add_input_chars("the-username\n")
            .add_input_chars("theP4ssword\n")
            .add_input_chars("theP4ssword\n")
            .add_input_chars("some@example.com\n")
            .add_input_chars("\n") // Default promotional email answer.
            .add_input_chars("true\n"); // Confirmation.
        let mut c = t.run("SIGNUP".to_owned());
        let output = flatten_output(c.take_captured_out());
        c.expect_err("1:1: In call to SIGNUP: Some error").check();

        assert!(output.contains("Username: the-username"));
        assert!(output.contains("Email address: some@example.com"));
        assert!(output.contains("Promotional email: no"));
    }
}