signstar-client 0.1.0

Library and executable for creating, reading and writing of signing requests for files
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
//! SSH-client for sending signing requests.
//!
//! This module provides Signstar client. The client is used to
//! connect to a Signstar host and request signatures for given files.
//!
//! # Examples
//!
//! ```no_run
//! # async fn sign() -> testresult::TestResult {
//! use signstar_client::ssh::client::ConnectConfig;
//! use signstar_common::request_api::Request;
//!
//! let options = ConnectConfig::from_first_system_config()?;
//!
//! let mut session = options.connect("user").await?;
//! let request = Request::for_file("package")?;
//! let response = session.send(&request).await?;
//! // process response
//! #     Ok(()) }
//! ```
use std::{
    collections::{BTreeMap, HashMap},
    fs::{File, OpenOptions, read_to_string},
    io::Read,
    num::NonZeroU32,
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
    time::Duration,
};

use garde::Validate;
use log::{error, info};
use rand::{rng, seq::IndexedRandom};
use russh::{
    ChannelMsg,
    Disconnect,
    MethodSet,
    client::{AuthResult, Config, Handle, Handler, connect},
    keys::{
        PublicKeyOrCertificate,
        agent::client::AgentClient,
        ssh_key::{
            known_hosts::Entry,
            {HashAlg, PublicKey},
        },
    },
};
use serde::{Deserialize, Deserializer};
use signstar_common::request_api::{Request, Response};
use tokio::net::UnixStream;

/// SSH communication error.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Invalid options used.
    #[error("Invalid options used: {0}")]
    InvalidOptions(String),

    /// Authentication failed.
    #[error("Authentication failed")]
    AuthFailed {
        /// The server suggests to proceed with these authentication methods.
        remaining_methods: MethodSet,

        /// The server says that though authentication method has been accepted, further
        /// authentication is required.
        partial_success: bool,
    },

    /// Invalid user specified.
    #[error("User {user} is not defined in the config file")]
    InvalidUser {
        /// User name that is missing.
        user: String,
    },

    /// Invalid Signstar host specified.
    #[error("Host {host} is not defined in the config file")]
    InvalidSignstarHost {
        /// Host name that is not defined.
        host: String,
    },

    /// I/O error occurred.
    #[error("I/O error: {source} when processing {file}")]
    Io {
        /// File being processed.
        ///
        /// This field will be empty ([`PathBuf::new`]) if the error
        /// was encountered when processing generic I/O streams.
        file: PathBuf,

        /// Source error.
        source: std::io::Error,
    },

    /// The remote program did not exit cleanly.
    #[error("Program did not exit cleanly")]
    UncleanExit,

    /// The remote application returned a non-zero status code.
    #[error("Remote application failed with status code: {status_code}")]
    RemoteApplicationFailure {
        /// Status code returned by the application.
        status_code: NonZeroU32,
    },

    /// Internal `russh` protocol error.
    #[error("SSH protocol error: {0}")]
    SshProtocol(#[from] russh::Error),

    /// SSH format error.
    #[error("SSH format error: {0}")]
    SshFormat(#[from] russh::keys::Error),

    /// SSH format error.
    #[error("SSH key error: {0}")]
    SshKey(#[from] russh::keys::ssh_key::Error),

    /// Internal `russh` client agent error.
    #[error("SSH agent error: {0}")]
    Agent(#[from] russh::AgentAuthError),

    /// JSON serialization error.
    #[error("Serde serialization error: {source}")]
    Serialization {
        /// The error source.
        source: serde_json::Error,
    },

    /// JSON deserialization error.
    #[error("Serde derialization error: {source}")]
    Deserialization {
        /// The error source.
        source: serde_json::Error,
    },
}

/// The default config file below "/usr/".
pub const DEFAULT_CONFIG: &str = "/usr/share/signstar/request-signature.toml";

/// The override config file below "/run/".
pub const RUN_OVERRIDE_CONFIG: &str = "/run/signstar/request-signature.toml";

/// The override config file below "/etc/".
pub const ETC_OVERRIDE_CONFIG: &str = "/etc/signstar/request-signature.toml";

/// The connection to a Signstar system a specific user can use.
#[derive(Debug, Deserialize, Validate)]
pub struct SignstarHost {
    /// The host name of the Signstar system.
    #[garde(length(min = 1))]
    host: String,

    /// The SSH port of the Signstar system.
    #[garde(range(min = 1))]
    port: u16,

    /// The known_hosts entries for the Signstar system.
    #[serde(deserialize_with = "deserialize_entries")]
    #[garde(length(min = 1))]
    known_hosts: Vec<Entry>,
}

/// Connection configuration for sending a signature request.
///
/// The configuration tracks a list of all valid targets for connecting.
#[derive(Debug, Default, Deserialize, Validate)]
#[garde(custom(validate_host_ids))]
pub struct ConnectConfig {
    /// List of hosts configured.
    #[garde(
        custom(validate_host_port_uniqueness),
        custom(validate_known_hosts_consistency),
        dive
    )]
    pub hosts: BTreeMap<String, SignstarHost>,

    /// List of users.
    #[garde(custom(validate_ssh_public_key_consistency), dive)]
    pub users: BTreeMap<String, ConnectOptions>,
}

impl ConnectConfig {
    /// The order of configuration files.
    ///
    /// The following files are inspected, in descending priority:
    /// - `/etc/signstar/request-signature.toml`
    /// - `/run/signstar/request-signature.toml`
    /// - `/usr/share/signstar/request-signature.toml`
    pub const CONFIG_ORDER: &[&str] = &[ETC_OVERRIDE_CONFIG, RUN_OVERRIDE_CONFIG, DEFAULT_CONFIG];

    /// Connects to a host over SSH and returns a [`Session`] object.
    ///
    /// This function sets up an authenticated, bidirectional channel
    /// between the client and the server. No signing requests are exchanged at this point but any
    /// number of them can be issued later using [`Session::send`] function.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn sign() -> testresult::TestResult {
    /// use signstar_client::ssh::client::ConnectConfig;
    ///
    /// let options = ConnectConfig::from_first_system_config()?;
    ///
    /// let mut session = options.connect("user").await?;
    /// // use session to send signing requests
    /// #     Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - the client public key is not set,
    /// - the server public key is not present in the provided SSH `known_hosts` data,
    /// - the client public key is not recognized by the server,
    /// - the client authentication with the agent fails,
    /// - an SSH protocol error is encountered.
    pub async fn connect(&self, username: &str) -> Result<Session, crate::Error> {
        let user = &self.users.get(username).ok_or(Error::InvalidUser {
            user: username.to_string(),
        })?;
        let host_id = user.hosts.sample(&mut rng(), 1).next();
        let target = if let Some(host_id) = host_id.as_ref() {
            &self.hosts.get(*host_id).ok_or(Error::InvalidSignstarHost {
                host: host_id.to_string(),
            })?
        } else {
            return Err(Error::InvalidOptions("at least one host must be defined".into()).into());
        };
        let client_auth_public_key = &user.user_public_key;

        let config = Arc::new(Config {
            inactivity_timeout: Some(Duration::from_secs(5)),
            ..Default::default()
        });

        let stream = UnixStream::connect(&user.agent_socket)
            .await
            .map_err(|source| crate::Error::IoPath {
                path: user.agent_socket.clone(),
                context: "connecting to the Unix socket".to_string(),
                source,
            })?;
        let mut future = AgentClient::connect(stream);
        let mut session = connect(
            config,
            (target.host.clone(), target.port),
            KeyValidator {
                host: target.host.clone(),
                port: target.port,
                entries: target.known_hosts.clone(),
            },
        )
        .await?;
        let auth_res = session
            .authenticate_publickey_with(
                username,
                client_auth_public_key.clone(),
                Some(HashAlg::Sha512),
                &mut future,
            )
            .await
            .map_err(Error::Agent)?;

        if let AuthResult::Failure {
            remaining_methods,
            partial_success,
        } = auth_res
        {
            return Err(Error::AuthFailed {
                remaining_methods,
                partial_success,
            }
            .into());
        }

        Ok(Session {
            session,
            host: target.host.clone(),
            port: target.port,
        })
    }

    /// Return the first configuration file that exists in the filesystem out of
    /// [`Self::CONFIG_ORDER`] list or returns a [`crate::Error::ConfigMissing`] error.
    ///
    /// # Errors
    ///
    /// Returns an error, if no configuration file is found.
    fn first_existing_system_config() -> Result<(File, PathBuf), crate::Error> {
        for path in Self::CONFIG_ORDER.iter().map(PathBuf::from) {
            let Ok(path) = path.canonicalize() else {
                info!("Unable to canonicalize path for configuration {path:?}. Skipping...");
                continue;
            };
            let Ok(file) = OpenOptions::new().read(true).open(&path) else {
                error!("Unable to open configuration {path:?}. Skipping...");
                continue;
            };

            return Ok((file, path));
        }
        Err(crate::Error::ConfigMissing)
    }

    /// Return the configuration created from the first configuration file that exists in the
    /// filesystem out of [`Self::CONFIG_ORDER`] list or returns a
    /// [`crate::Error::ConfigMissing`] error.
    ///
    /// # Errors
    ///
    /// Returns an error, if
    /// - a configuration file cannot be found
    /// - the file cannot be read to string
    /// - the contents are not valid TOML
    /// - the configuration fails validation
    pub fn from_first_system_config() -> Result<Self, crate::Error> {
        let (mut file, path) = Self::first_existing_system_config()?;
        let mut data = String::new();
        file.read_to_string(&mut data)
            .map_err(|source| crate::Error::IoPath {
                path,
                context: "reading the config file".to_string(),
                source,
            })?;

        Self::from_str(&data)
    }

    /// Reads the configuration file, validates it and returns the [`ConnectConfig`].
    ///
    /// # Errors
    ///
    /// Returns an error:
    /// - [`crate::Error::Io`] if reading the config file fails
    /// - [`crate::Error::Validation`] if the config file has invalid contents
    pub fn from_config_file(file: impl AsRef<Path>) -> Result<Self, crate::Error> {
        let path = file.as_ref();
        let contents = read_to_string(path).map_err(|source| crate::Error::IoPath {
            path: path.to_path_buf(),
            context: "reading a configuration file".to_string(),
            source,
        })?;

        Self::from_str(&contents)
    }
}

impl FromStr for ConnectConfig {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let config: ConnectConfig = toml::from_str(s)?;
        config
            .validate()
            .map_err(|source| crate::Error::Validation {
                context: "reading configuration file".to_owned(),
                source,
            })?;

        Ok(config)
    }
}

/// Ensures, that SSH public keys are unique per user.
///
/// # Errors
///
/// Returns an error if an SSH public key is used by more than one user.
fn validate_ssh_public_key_consistency(
    users: &BTreeMap<String, ConnectOptions>,
    _context: &(),
) -> garde::Result {
    let failures = users
        .iter()
        .map(|(user, connect_option)| (user, &connect_option.user_public_key))
        .fold(
            HashMap::<&PublicKey, Vec<&str>>::new(),
            |mut acc, (user, user_public_key)| {
                acc.entry(user_public_key).or_default().push(user);
                acc
            },
        )
        .into_iter()
        .filter(|(_, users)| users.len() > 1)
        .map(|(pk, users)| {
            format!(
                "Public key {pk} is shared by these users: {users}",
                pk = pk.to_string(),
                users = users.join(", ")
            )
        })
        .collect::<Vec<_>>();
    if !failures.is_empty() {
        return Err(garde::Error::new(format!(
            "The SSH public key used for a user cannot be used for another user:\n{failures}",
            failures = failures.join("\n")
        )));
    }

    Ok(())
}

/// Ensures, that the `known_hosts` entries are unique per `host:port` combinations.
///
/// # Errors
///
/// Returns an error if the `known_hosts` entries differ for any instance of a `host:port`
/// combination.
fn validate_known_hosts_consistency(
    connect_options: &BTreeMap<String, SignstarHost>,
    _context: &(),
) -> garde::Result {
    let failures = connect_options
        .iter()
        .map(|(host, config)| (host, &config.known_hosts))
        .fold(
            HashMap::<String, Vec<&str>>::new(),
            |mut acc, (host, known_hosts)| {
                for known_host in known_hosts {
                    acc.entry(known_host.to_string()).or_default().push(host);
                }
                acc
            },
        )
        .into_iter()
        .filter(|(_, hosts)| hosts.len() > 1)
        .map(|(entry, hosts)| {
            format!(
                "Entry {entry} is shared by these hosts: {hosts}",
                hosts = hosts.join(", ")
            )
        })
        .collect::<Vec<_>>();
    if !failures.is_empty() {
        return Err(garde::Error::new(format!(
            "The known host entry used for a host cannot be used for another host:\n{failures}",
            failures = failures.join("\n")
        )));
    }

    Ok(())
}

/// Ensures, that each host:port combination is unique.
///
/// # Errors
///
/// Returns an error if there is a duplicate host:port combination.
fn validate_host_port_uniqueness(
    connect_options: &BTreeMap<String, SignstarHost>,
    _context: &(),
) -> garde::Result {
    let failures = connect_options
        .iter()
        .map(|(host_id, config)| (host_id, &config.host, config.port))
        .fold(
            HashMap::<(&str, u16), Vec<&str>>::new(),
            |mut acc, (host_id, host, port)| {
                acc.entry((host, port)).or_default().push(host_id);

                acc
            },
        )
        .into_iter()
        .filter(|(_, host_ids)| host_ids.len() > 1)
        .map(|((host, port), host_ids)| {
            format!(
                "Host {host}:{port} is shared by these hosts: {host_ids}",
                host_ids = host_ids.join(", ")
            )
        })
        .collect::<Vec<_>>();
    if !failures.is_empty() {
        return Err(garde::Error::new(format!(
            "Two connections cannot have the same host:port combinations:\n{failures}",
            failures = failures.join("\n")
        )));
    }

    Ok(())
}

/// Ensures, that each `host_id` in a [`ConnectConfig`] is defined.
///
/// # Errors
///
/// Returns an error if there are host_ids which are not defined.
fn validate_host_ids(config: &ConnectConfig, _context: &()) -> garde::Result {
    let failures = config
        .users
        .iter()
        .flat_map(|(user_id, options)| {
            options
                .hosts
                .iter()
                .filter(|host| !config.hosts.contains_key(*host))
                .map(move |invalid_host| (user_id, invalid_host))
        })
        .map(|(user, invalid_host)| {
            format!("User {user} is using host_id which is not defined: {invalid_host}",)
        })
        .collect::<Vec<_>>();

    if !failures.is_empty() {
        return Err(garde::Error::new(failures.join("\n")));
    }

    Ok(())
}

/// Connection options for sending a signature request.
///
/// The options capture target host parameters and all necessary
/// information related to authentication for both the client
/// (client's public key and authentication agent) and server (a list
/// of valid and known server public keys).
///
/// # Examples
///
/// ```no_run
/// # fn main() -> testresult::TestResult {
/// use signstar_client::ssh::client::ConnectOptions;
///
/// let options = ConnectOptions::new("localhost".into(), "ssh-ed25519 ...")?
///     .agent_socket(std::env::var("SSH_AUTH_SOCK")?);
/// # Ok(()) }
/// ```
#[derive(Debug, Deserialize, Validate)]
pub struct ConnectOptions {
    /// The path to the SSH agent socket used for the connection to `user` on the Signstar
    /// system(s).
    #[garde(skip)]
    pub agent_socket: PathBuf,

    /// The SSH public key used for the connections to `user` on the Signstar system(s).
    #[garde(skip)]
    pub user_public_key: PublicKey,

    /// The list of Signstar hosts that the `user` can connect to.
    #[garde(length(min = 1))]
    pub hosts: Vec<String>,
}

impl ConnectOptions {
    /// Sets the path to an OpenSSH agent socket for client authentication.
    pub fn agent_socket(mut self, agent_socket: impl Into<PathBuf>) -> Self {
        self.agent_socket = agent_socket.into();
        self
    }

    /// Sets an SSH public key of a client for SSH authentication.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> testresult::TestResult {
    /// use signstar_client::ssh::client::ConnectOptions;
    ///
    /// let client_pk =
    ///     "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILHCXBJYlPPkrt2WYyP3SZoMx43lDBB5QALjE762EQlc";
    /// let options = ConnectOptions::new("localhost".into(), client_pk)?;
    /// #     Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the public key is not well-formatted. This
    /// function only accepts public keys following the
    /// [`authorized_keys` file format].
    ///
    /// [`authorized_keys` file format]: https://man.archlinux.org/man/core/openssh/sshd.8.en#AUTHORIZED_KEYS_FILE_FORMAT.
    pub fn user_public_key(
        mut self,
        user_public_key: impl Into<String>,
    ) -> Result<Self, crate::Error> {
        self.user_public_key =
            PublicKey::from_openssh(&user_public_key.into()).map_err(Error::SshKey)?;
        Ok(self)
    }

    /// Constructs a new [`ConnectOptions`] with target host and client public key.
    pub fn new(
        host: String,
        client_auth_public_key: impl AsRef<str>,
    ) -> Result<Self, crate::Error> {
        let client_auth_public_key =
            PublicKey::from_openssh(client_auth_public_key.as_ref()).map_err(Error::SshKey)?;
        Ok(Self {
            hosts: vec![host],
            agent_socket: Default::default(),
            user_public_key: client_auth_public_key,
        })
    }
}

fn deserialize_entries<'de, D>(deserializer: D) -> Result<Vec<Entry>, D::Error>
where
    D: Deserializer<'de>,
{
    Vec::<String>::deserialize(deserializer)?
        .into_iter()
        .map(|entry: String| Entry::from_str(&entry).map_err(serde::de::Error::custom))
        .collect::<Result<_, _>>()
}

/// Validator for a host's SSH keys and a list of `known_hosts` entries.
///
/// Tracks a `host` and its `port`, as well as a list of `entries` in the [SSH `known_hosts` file
/// format].
///
/// [SSH `known_hosts` file format]: https://man.archlinux.org/man/sshd.8#SSH_KNOWN_HOSTS_FILE_FORMAT
struct KeyValidator {
    host: String,
    port: u16,
    entries: Vec<Entry>,
}

impl Handler for KeyValidator {
    type Error = Error;

    /// Checks whether a set of server details can be found in SSH `known_hosts` data.
    ///
    /// Based on a `host` and its `port`, this function evaluates whether a supplied `key` is part
    /// of a list of `entries` in the SSH known_hosts file format. Returns `true`, if the
    /// combination of `key`, `host` and `port` matches an entry in the list of `entries` and that
    /// entry is not a CA key or a revoked key. Returns `false` in all other cases.
    async fn check_server_key(
        &mut self,
        server_public_key: &PublicKeyOrCertificate,
    ) -> Result<bool, Error> {
        if let PublicKeyOrCertificate::PublicKey { key, .. } = server_public_key {
            Ok(crate::ssh::known_hosts::is_server_known(
                self.entries.iter(),
                &self.host,
                self.port,
                key,
            ))
        } else {
            Ok(false)
        }
    }
}

/// An open session with a host that can be used to send multiple signing requests.
pub struct Session {
    session: Handle<KeyValidator>,
    host: String,
    port: u16,
}

impl std::fmt::Debug for Session {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "SSH session for host {} on port {}",
            self.host, self.port
        )
    }
}

impl Session {
    /// Send a signing request to the server and return a signing response.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn sign() -> testresult::TestResult {
    /// use signstar_client::ssh::client::ConnectConfig;
    /// use signstar_common::request_api::Request;
    ///
    /// let options = ConnectConfig::from_first_system_config()?;
    ///
    /// let mut session = options.connect("user").await?;
    /// let request = Request::for_file("package")?;
    /// let response = session.send(&request).await?;
    /// // process response
    /// #     Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if sending or processing the signing request fails:
    /// - if the remote server rejects the signing request,
    /// - if the remote application exits unexpectedly,
    /// - the returned data cannot be deserialized into a [`Response`],
    /// - if an SSH protocol error is encountered.
    pub async fn send(&mut self, data: &Request) -> Result<Response, crate::Error> {
        let mut channel = self
            .session
            .channel_open_session()
            .await
            .map_err(Error::SshProtocol)?;
        // the command name is empty as it is assumed that the server will
        // pick correct binary anyway
        let command_name = b"";
        channel
            .exec(true, command_name)
            .await
            .map_err(Error::SshProtocol)?;
        let data = serde_json::to_vec(&data).map_err(|source| Error::Serialization { source })?;
        channel
            .data(data.as_ref())
            .await
            .map_err(Error::SshProtocol)?;
        channel.eof().await.map_err(Error::SshProtocol)?;

        let mut code = None;
        let mut stdout = vec![];

        while let Some(msg) = channel.wait().await {
            match msg {
                ChannelMsg::Data { ref data } => {
                    stdout.extend(data.iter());
                }
                ChannelMsg::ExitStatus { exit_status } => {
                    code = Some(exit_status);
                    // cannot leave the loop immediately, there might still be more data to receive
                }
                _ => {}
            }
        }

        if let Some(code) = code {
            if let Some(status_code) = NonZeroU32::new(code) {
                Err(Error::RemoteApplicationFailure { status_code }.into())
            } else {
                Ok(serde_json::from_slice(&stdout)
                    .map_err(|source| Error::Deserialization { source })?)
            }
        } else {
            Err(Error::UncleanExit.into())
        }
    }

    /// Close the authentication session.
    ///
    /// This function cleanly closes the session and informs the
    /// server that no further requests will be sent.
    ///
    /// # Examples
    ///
    /// This example shows that after the [`Session::close`] function is invoked no further requests
    /// can be sent.
    ///
    /// ```compile_fail
    /// # async fn sign() -> testresult::TestResult {
    /// use signstar_client::ssh::client::ConnectConfig;
    ///
    /// let options = ConnectConfig::from_first_system_config();
    ///
    /// let mut session = options.connect("user").await?;
    /// session.close();
    ///
    /// // the session object has been consumed and cannot be reused
    /// let request = Request::for_file("package")?;
    /// let response = session.send(&request).await?;
    /// #     Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if at any stage of the connecting process fails:
    /// - if the client public key is not set,
    /// - if the server public key is not pinned in the known hosts file,
    /// - if the client public key is not recognized by the server,
    /// - if the client authentication with the agent fails,
    /// - if an SSH protocol error is encountered.
    pub async fn close(self) -> Result<(), crate::Error> {
        Ok(self
            .session
            .disconnect(
                Disconnect::ByApplication,
                "Client is closing the connection",
                "en",
            )
            .await
            .map_err(Error::SshProtocol)?)
    }
}

#[cfg(test)]
mod tests {

    use garde::Validate;
    use insta::assert_snapshot;
    use testresult::TestResult;

    use super::*;

    #[test]
    fn validate_success() -> TestResult {
        let config = ConnectConfig {
                users: [("test-user".into(), ConnectOptions::new(
                    "local".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPp",
                )?)].into_iter().collect(),
                hosts: [("local".into(), SignstarHost {
                    host: "127.0.0.1".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAd")?],
                })].into_iter().collect(),
            };

        config.validate()?;

        Ok(())
    }

    #[test]
    fn validate_ssh_public_key_cannot_be_reused() -> TestResult {
        let config = ConnectConfig {
                users: [("test-user".into(), ConnectOptions::new(
                    "local".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPp",
                )?),("test-user2".into(), ConnectOptions::new(
                    "local".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPp",
                )?)].into_iter().collect(),
                hosts: [("local".into(), SignstarHost {
                    host: "127.0.0.1".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAd")?],
                })].into_iter().collect(),
            };

        let error_msg = match config.validate() {
            Ok(()) => {
                panic!("Expected to fail with garde::Error, but succeeded instead.")
            }
            Err(error) => error.to_string(),
        };

        assert_snapshot!(error_msg);

        Ok(())
    }

    #[test]
    fn validate_known_hosts_entries_unique_per_host_port_of_the_user() -> TestResult {
        let config = ConnectConfig {
                users: [("test-user".into(), ConnectOptions::new(
                    "local".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPp",
                )?),("test-user2".into(), ConnectOptions::new(
                    "local2".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPP",
                )?)].into_iter().collect(),
                hosts: [("local".into(), SignstarHost {
                    host: "127.0.0.1".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAd")?],
                }),("local2".into(), SignstarHost {
                    host: "127.0.0.2".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAd")?],
                })].into_iter().collect(),
            };

        let error_msg = match config.validate() {
            Ok(()) => {
                panic!("Expected to fail with garde::Error, but succeeded instead.")
            }
            Err(error) => error.to_string(),
        };

        assert_snapshot!(error_msg);

        Ok(())
    }

    #[test]
    fn validate_host_port_uniqueness() -> TestResult {
        let config = ConnectConfig {
                users: [("test-user".into(), ConnectOptions::new(
                    "local".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPp",
                )?),("test-user2".into(), ConnectOptions::new(
                    "local2".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPP",
                )?)].into_iter().collect(),
                hosts: [("local".into(), SignstarHost {
                    host: "127.0.0.1".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAD")?],
                }),("local2".into(), SignstarHost {
                    host: "127.0.0.1".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAd")?],
                })].into_iter().collect(),
            };

        let error_msg = match config.validate() {
            Ok(()) => {
                panic!("Expected to fail with garde::Error, but succeeded instead.")
            }
            Err(error) => error.to_string(),
        };

        assert_snapshot!(error_msg);

        Ok(())
    }

    #[test]
    fn validate_host_ids() -> TestResult {
        let config = ConnectConfig {
                users: [("test-user".into(), ConnectOptions::new(
                    "test".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPp",
                )?),("test-user2".into(), ConnectOptions::new(
                    "test".into(),
                    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMPF9G0NQMEIBWR0NBc7sVBc2uxkKwY3SWvzRWQAtLPP",
                )?)].into_iter().collect(),
                hosts: [("test2".into(), SignstarHost {
                    host: "127.0.0.1".into(),
                    port: 22,
                    known_hosts: vec![Entry::from_str("test1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh8eDowbkS5cA/50DhIsOUI5bDf5Kx0sSJZDQgfoRAd")?],
                })].into_iter().collect(),
            };

        let error_msg = match config.validate() {
            Ok(()) => {
                panic!("Expected to fail with garde::Error, but succeeded instead.")
            }
            Err(error) => error.to_string(),
        };

        assert_snapshot!(error_msg);

        Ok(())
    }
}