siguldry 0.7.0

An implementation of the Sigul protocol.
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
// SPDX-License-Identifier: MIT
// Copyright (c) Microsoft Corporation.

//! The structures used in the Sigul protocol.
//!
//! All structures described in this documenation are to be sent in network byte order (big endian).
//!
//! # Outer TLS Session
//!
//! Both the client and server connect to the bridge service using TLS, authenticated via client
//! certificates. Once the connection is established, the connecting side (the client or server)
//! sends a protocol header and waits for an acknowledgement from the bridge. After the
//! acknowledgement is received, no further communication occurs in the outer TLS session.
//!
//! ## Protocol Header and Ack
//!
//! Every connection to the bridge must begin with the protocol header, which announces the protocol
//! version to follow. The server may reject the request if the version is unknown or unsupported. A
//! server may support multiple versions, but must always use the version requested by the client if
//! it is supported.
//!
//! |--------------------------|
//! |      Protocol Header     |
//! |--------------------------|
//! | u64 | Magic number       |
//! | u32 | Protocol version   |
//! | u8  | Role               |
//! |--------------------------|
//!
//! The bridge responds with an acknowledgement which includes a session ID for the connection and
//! a status to indicate whether the inner TLS connection can proceed.
//!
//! |--------------------------|
//! |      Protocol Ack        |
//! |--------------------------|
//! | u128 | Session ID        |
//! | u8   | Bridge status     |
//! |--------------------------|
//!
//! The session ID is a UUID generated by the bridge and provided to both the client and the server.
//! This can be used to identify a connection on both the client and server.
//!
//! Refer to [`BridgeStatus`] for possible status values.
//!
//! The protocol version is increased whenever any of the following structures are changed. Thus,
//! all structures described below are specific to version 2 of the protocol.
//!
//! # Inner TLS Session
//!
//! After the protocol header is acknowledged, the client starts a second TLS session within the
//! first one. In this session, the client must configure the TLS session to accept the Sigul
//! server's hostname and must present its client TLS certificate. All future communication occurs
//! over this nested TLS session.
//!
//! ## Frames
//!
//! Each message in the inner TLS session must start with a frame, which describes the size of the
//! data to follow. Requests include two sections; the first is a JSON-serialized, UTF-8 encoded
//! dictionary describing the request and its parameters. The second section is an arbitrary,
//! request-specific binary blob. This binary blob is used exclusively for various signing requests
//! and management commands do not include one. When the command does not have a binary blob, the
//! size in the frame must be set to 0.
//!
//! |---------------------------|
//! |        Frame Header       |
//! |---------------------------|
//! | u64 | JSON size (bytes)   |
//! | u64 | Binary size (bytes) |
//! |---------------------------|

use openssl::nid::Nid;
use sequoia_openpgp::cert::CipherSuite;
use serde::{Deserialize, Serialize};
use tokio::{
    io::{AsyncRead, AsyncReadExt},
    task::JoinError,
};
use tokio_openssl::SslStream;
use tracing::instrument;
use uuid::Uuid;
use zerocopy::{
    Immutable, IntoBytes, KnownLayout, TryFromBytes,
    byteorder::network_endian::{U32, U64, U128},
};

use crate::error::ConnectionError;

/// Magic number used in the protocol header.
pub const MAGIC: U64 = U64::from_bytes([83, 73, 71, 85, 76, 68, 82, 89]);
/// The Sigul wire protocol version this implementation supports
pub const PROTOCOL_VERSION: U32 = U32::new(2);

/// The possible roles a connection can have.
///
/// This is sent in the [`ProtocolHeader`]. The bridge listens on two separate ports for client
/// connections and server connections, but it is easy to misconfigure the client, server, or bridge
/// such that a client connects to the server port or vice versa. This header field exists to ensure
/// such misconfigurations are clearly reported by the bridge.
#[derive(IntoBytes, Immutable, KnownLayout, TryFromBytes, Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum Role {
    /// Clients should use this role in their protocol header.
    Client = 0,
    /// Server should use this role in their protocol header.
    Server = 1,
}

impl std::fmt::Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Role::Client => write!(f, "client"),
            Role::Server => write!(f, "server"),
        }
    }
}

/// Every connection to the bridge begins with a protocol header to announce the version it expects
/// to use as well as the [`Role`] it intends to take.
#[derive(IntoBytes, Immutable, KnownLayout, TryFromBytes, Debug, Clone)]
pub(crate) struct ProtocolHeader {
    /// Each connection starts with a [`MAGIC`] number. While the version and role also have a fairly
    /// restricted set of valid values, this makes it even more likely a random incoming connection
    /// doesn't send a valid header so the bridge can hang up sooner. This isn't a security thing, just
    /// a "make it very likely you can log the right error" thing.
    pub(crate) magic: U64,
    /// The protocol version being requested by the connection; the current version is
    /// [`PROTOCOL_VERSION`].
    pub(crate) version: U32,
    /// The [`Role`] of this connection; the bridge should listen on entirely different ports and so it
    /// should know whether each connection is a client or a server. This exists primarily to help catch
    /// mis-configurations where the client or server connects to the other's port on the bridge.
    pub(crate) role: Role,
}

/// Part of the protocol Ack sent by the bridge to indicate whether the connection can continue.
#[derive(IntoBytes, Immutable, KnownLayout, TryFromBytes, Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum BridgeStatus {
    /// The requested protocol version and role is acceptable to the bridge.
    Ok = 0,
    /// The requested version is unsupported.
    UnsupportedVersion = 1,
    /// The requested role is invalid or not correct for the given bridge address (e.g. a server
    /// connected to the client port).
    InvalidRole = 2,
    /// The client certificate is signed by a valid CA, but does not include a Common Name field.
    MissingCommonName = 3,
    /// The request did not begin with the correct magic number.
    MissingMagic = 4,
}

impl std::fmt::Display for BridgeStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BridgeStatus::Ok => write!(f, "OK"),
            BridgeStatus::UnsupportedVersion => {
                write!(f, "The requested protocol version is not supported")
            }
            BridgeStatus::InvalidRole => write!(
                f,
                "The requested role is invalid for the bridge address and port"
            ),
            BridgeStatus::MissingCommonName => {
                write!(f, "The client certificate does not contain a CommonName")
            }
            BridgeStatus::MissingMagic => {
                write!(f, "The connection didn't start with the magic number")
            }
        }
    }
}

/// The bridge sends this acknowledgement to connections after receiving the protocol header.
/// The client and server can use this to determine if the inner connection can proceed, and
/// it also includes a session ID so logs across the services can be corrolated.
#[derive(IntoBytes, Immutable, KnownLayout, TryFromBytes, Debug, Clone)]
pub(crate) struct ProtocolAck {
    pub(crate) session_id: U128,
    status: BridgeStatus,
}

impl ProtocolAck {
    pub fn new(status: BridgeStatus) -> Self {
        Self {
            session_id: U128::new(Uuid::now_v7().as_u128()),
            status,
        }
    }

    #[instrument(level = "trace", skip_all, err)]
    pub(crate) async fn check<C: AsyncRead + Unpin>(conn: &mut C) -> Result<Uuid, ConnectionError> {
        let mut ack_buf = [0_u8; std::mem::size_of::<Self>()];
        conn.read_exact(&mut ack_buf).await?;
        let ack = Self::try_ref_from_bytes(&ack_buf)?;
        let session_id = Uuid::from_u128(ack.session_id.get());
        tracing::debug!(?session_id, status=?ack.status, "Bridge acknowledgement received");

        match ack.status {
            BridgeStatus::Ok => Ok(session_id),
            BridgeStatus::MissingCommonName => Err(Error::MissingCommonName.into()),
            other => Err(Error::Bridge(other.to_string()).into()),
        }
    }
}

impl ProtocolHeader {
    /// Create a new protocol header for the given role.
    pub(crate) fn new(role: Role) -> Self {
        Self {
            magic: MAGIC,
            version: PROTOCOL_VERSION,
            role,
        }
    }

    pub(crate) fn check(&self, expected_role: Role) -> BridgeStatus {
        if self.magic != MAGIC {
            BridgeStatus::MissingMagic
        } else if self.version != PROTOCOL_VERSION {
            BridgeStatus::UnsupportedVersion
        } else if self.role != expected_role {
            BridgeStatus::InvalidRole
        } else {
            BridgeStatus::Ok
        }
    }
}

impl From<Role> for ProtocolHeader {
    fn from(role: Role) -> Self {
        ProtocolHeader::new(role)
    }
}

/// Get the remote connection's commonName from its certificate.
pub(crate) fn peer_common_name<S>(stream: &SslStream<S>) -> Result<String, Error> {
    stream
        .ssl()
        .peer_certificate()
        .and_then(|cert| {
            cert.subject_name()
                .entries_by_nid(Nid::COMMONNAME)
                .next()
                .and_then(|entry| entry.data().as_utf8().ok())
        })
        .map(|common_name| common_name.to_string())
        .ok_or(Error::MissingCommonName)
}

/// Possible errors due to protocol violations.
#[derive(Debug, thiserror::Error, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// The client certificate does not include a Common Name, which is used to determine the
    /// username of the client.
    #[error("The peer's certificate does not include a Common Name")]
    MissingCommonName,
    #[error("The frame was invalid: {0}")]
    Framing(String),
    #[error("The bridge rejected the protocol header: {0}")]
    Bridge(String),
}

/// Each client request or server response starts with a frame that describes the size of the request
/// to follow.
#[derive(IntoBytes, Immutable, KnownLayout, TryFromBytes, Debug, Clone)]
pub(crate) struct Frame {
    /// The
    pub(crate) json_size: U64,
}

impl Frame {
    /// Create a new frame.
    pub fn new(json_size: u64) -> Self {
        Self {
            json_size: U64::new(json_size),
        }
    }

    /// Create a new empty frame, used to signal the client is done.
    pub fn empty() -> Self {
        Self {
            json_size: U64::new(0),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.json_size.get() == 0
    }
}

/// The structure used by the client when sending requests to the server.
///
/// # Example
/// ```
/// # use serde_json::Result;
/// # use siguldry::protocol::json::OuterRequest;
/// # fn main() -> Result<()> {
/// let data = r#"
///     {
///         "session_id": "00000000-0000-0000-0000-000000000000",
///         "request_id": 42,
///         "request": {
///             "who_am_i": {}
///         }
///     }
/// "#;
/// let whoami_response: OuterResponse = serde_json::from_str(data)?;
///
/// # Ok(())
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) struct OuterRequest {
    /// The session ID this request is a part of.
    pub(crate) session_id: Uuid,
    /// The request ID; this should be a unique integer within the session,
    /// but has no other requirements. The response will include the same ID
    /// so it can be used to ensure the response matches the request.
    pub(crate) request_id: u64,
    /// The actual client request for the server.
    pub(crate) request: Request,
}

/// The structure used by the server when sending responses to the client.
///
/// # Example
/// ```
/// # use serde_json::Result;
/// # use siguldry::protocol::json::OuterResponse;
/// # fn main() -> Result<()> {
/// let data = r#"
///     {
///         "session_id": "00000000-0000-0000-0000-000000000000",
///         "request_id": 42,
///         "response": {
///             "who_am_i": {"user": "dadams"}
///         }
///     }
/// "#;
/// let whoami_response: OuterResponse = serde_json::from_str(data)?;
///
/// # Ok(())
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) struct OuterResponse {
    /// The session ID this request is a part of.
    pub(crate) session_id: Uuid,
    /// The request ID; this should be a unique integer within the session,
    /// but has no other requirements. The response will include the same ID
    /// so it can be used to ensure the response matches the request.
    pub(crate) request_id: u64,
    /// The serialized [`Request`] or [`Response`].
    pub(crate) response: Response,
}

/// The set of requests a client and server must support.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Request {
    WhoAmI {},
    /// List keys on the server which the current user has access to.
    ListKeys {},
    /// Unlock a key for signing.
    ///
    /// This request must be sent on a connection before any signing requests referencing
    /// the key.
    Unlock {
        /// The name of the key to unlock.
        key: String,
        /// The password to unlock the key with.
        password: String,
    },
    /// Request an RSA or ECDSA signature.
    ///
    /// The type of signature is dependant on the type of the given key.
    ///
    /// # RSA
    ///
    /// For RSA key types, the PKCS #1 padding mode is used.
    Sign {
        /// The signing key to use. This key must be unlocked.
        key: String,
        /// The digest algorithm used on the data; some signing algorithms
        /// embed this in the signature structure.
        digest_algorithm: DigestAlgorithm,
        /// The hex-encoded digest to sign.
        digest: String,
    },
    SignAll {
        key: String,
        /// The set of digests to sign. Digests should be hex-encoded.
        digests: Vec<(DigestAlgorithm, String)>,
    },
    GetKey {
        key: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Response {
    WhoAmI {
        user: String,
    },
    ListKeys {
        keys: Vec<Key>,
    },
    Unlock {},
    GetKey {
        key: Key,
    },
    Sign {
        signature: Signature,
    },
    SignPrehashed {
        signatures: Vec<Signature>,
    },
    Error {
        reason: ServerError,
    },
    /// The client requested a command the server does not support; this could be
    /// a newer client combined with an older server, or a server that has opted to
    /// implement only a subset of commands.
    Unsupported,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Signature {
    /// The signature. This is base64-encoded in the JSON objects.
    pub signature: SignaturePayload,
    /// The digest algorithm used on the payload.
    pub digest: DigestAlgorithm,
    /// The hex-encoded digest value that was signed.
    pub hash: String,
}

impl Signature {
    /// The signature value.
    ///
    /// What's contained depends on the key used to sign.
    pub fn value(&self) -> &[u8] {
        self.signature.as_ref()
    }

    /// Get the signature value in the format expected for PKCS #11 signing operations.
    pub fn pkcs11_value(&self) -> Option<Vec<u8>> {
        match &self.signature {
            SignaturePayload::RSA(pkcs1_15_sig) => Some(pkcs1_15_sig.clone()),
            SignaturePayload::P256(ecdsa_sig) => {
                // The expected value is the raw r and s values
                let ecdsa_sig = openssl::ecdsa::EcdsaSig::from_der(ecdsa_sig)
                    .inspect_err(|error| {
                        tracing::error!(?error, "Failed to parse DER-encoded ECDSASignature");
                    })
                    .ok()?;
                let r = ecdsa_sig
                    .r()
                    .to_vec_padded(32)
                    .inspect_err(|error| {
                        tracing::error!(?error, "Failed to pad ECDSA r value");
                    })
                    .ok()?;
                let s = ecdsa_sig
                    .s()
                    .to_vec_padded(32)
                    .inspect_err(|error| {
                        tracing::error!(?error, "Failed to pad ECDSA s value");
                    })
                    .ok()?;

                let mut r_and_s = Vec::with_capacity(64);
                r_and_s.extend_from_slice(&r);
                r_and_s.extend_from_slice(&s);
                Some(r_and_s)
            }
        }
    }
}

/// Contains the actual signature.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SignaturePayload {
    /// RSA signatures are DER-encoded PKCS#1 v1.5 structures as described in
    /// RFC 8017 Section 9.2.
    #[serde(with = "base64")]
    RSA(Vec<u8>),
    /// Signatures with P256 keys are DER-encoded ECDSASignature structures as
    /// described in RFC 3279 Section 2.2.3.
    #[serde(with = "base64")]
    P256(Vec<u8>),
}

impl std::ops::Deref for SignaturePayload {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        match self {
            SignaturePayload::RSA(value) | SignaturePayload::P256(value) => value,
        }
    }
}

mod base64 {
    use serde::{Deserialize, Serialize};
    use serde::{Deserializer, Serializer};

    pub fn serialize<S: Serializer>(value: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
        String::serialize(&openssl::base64::encode_block(value), serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
        openssl::base64::decode_block(&String::deserialize(deserializer)?)
            .map_err(|error| serde::de::Error::custom(format!("invalid base64: {error:?}")))
    }
}

/// Describes the public portion of keys managed by Siguldry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Certificate {
    /// The PEM-encoded or ASCII-armored certificate.
    pub certificate: String,
    /// The type of the certificate.
    pub certificate_type: CertificateType,
    /// A unique identifier for the certificate.
    pub fingerprint: String,
    /// The name of the certificate in Siguldry.
    ///
    /// Names are unique per-key.
    pub name: String,
}

/// The type of certificate contained in a [`Certificate`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum CertificateType {
    /// A key pair that can be used for OpenPGP signatures.
    Pgp,
    /// A key pair with an associated X509 certificate.
    X509,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Key {
    /// A name that uniquely identifies the key.
    pub name: String,
    /// Indicates the key type.
    pub key_algorithm: KeyAlgorithm,
    /// This uniquely identifies a key. For example, the OpenPGP key fingerprint, or the SHA256 sum of
    /// the public key.
    pub handle: String,
    /// The PEM-encoded public key.
    pub public_key: String,
    /// A list of certificates associated with this key.
    pub certificates: Vec<Certificate>,
}

impl Key {
    /// A list of X509 certificates.
    pub fn x509_certificates(&self) -> Vec<Certificate> {
        self.certificates
            .iter()
            .filter(|c| matches!(c.certificate_type, CertificateType::X509))
            .cloned()
            .collect()
    }

    pub fn openpgp_certificates(&self) -> Vec<Certificate> {
        self.certificates
            .iter()
            .filter(|c| matches!(c.certificate_type, CertificateType::Pgp,))
            .cloned()
            .collect()
    }
}

/// Possible key types.
///
/// This enumeration matches the values in the database's `key_algorithms` table.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[non_exhaustive]
pub enum KeyAlgorithm {
    /// 2048 bit RSA keys.
    Rsa2K,
    /// 4096 bit RSA keys.
    #[default]
    Rsa4K,
    /// NIST P-256 ECC keys (also known as prime256v1 and secp256r1).
    P256,
}

impl KeyAlgorithm {
    pub fn as_str(&self) -> &str {
        match self {
            KeyAlgorithm::Rsa2K => "rsa2k",
            KeyAlgorithm::Rsa4K => "rsa4k",
            KeyAlgorithm::P256 => "P256",
        }
    }
}

impl std::fmt::Display for KeyAlgorithm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            KeyAlgorithm::Rsa2K => "RSA 2048",
            KeyAlgorithm::Rsa4K => "RSA 4096",
            KeyAlgorithm::P256 => "NIST P-256",
        };
        write!(f, "{s}")
    }
}

impl From<KeyAlgorithm> for CipherSuite {
    fn from(value: KeyAlgorithm) -> Self {
        match value {
            KeyAlgorithm::Rsa2K => CipherSuite::RSA2k,
            KeyAlgorithm::Rsa4K => CipherSuite::RSA4k,
            KeyAlgorithm::P256 => CipherSuite::P256,
        }
    }
}

impl TryFrom<&str> for KeyAlgorithm {
    type Error = anyhow::Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "rsa2k" => Ok(Self::Rsa2K),
            "rsa4k" => Ok(Self::Rsa4K),
            "P256" => Ok(Self::P256),
            _ => Err(anyhow::anyhow!("Unknown key type '{value}'!")),
        }
    }
}

impl From<String> for KeyAlgorithm {
    fn from(value: String) -> Self {
        // In the event that the database we're working from has been migrated to a different level
        // than the application, it's possible there's a variant we're not aware of. It's not great
        // but we really should panic and stop.
        let msg = "The database contains key types the application is unaware \
            of; this is either an application bug, or the database migration level does not match \
            the application";
        Self::try_from(value.as_str()).expect(msg)
    }
}

/// The digest algorithm to use when signing.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum DigestAlgorithm {
    Sha256,
    Sha512,
    Sha3_256,
    Sha3_512,
}

impl DigestAlgorithm {
    /// The size, in bytes, of the digest algorithm
    pub fn size(self) -> usize {
        let algorithm: openssl::hash::MessageDigest = self.into();
        algorithm.size()
    }
}

impl std::fmt::Display for DigestAlgorithm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            DigestAlgorithm::Sha256 => "sha256",
            DigestAlgorithm::Sha512 => "sha512",
            DigestAlgorithm::Sha3_256 => "sha3-256",
            DigestAlgorithm::Sha3_512 => "sha3-512",
        };
        write!(f, "{name}")
    }
}

impl From<DigestAlgorithm> for openssl::hash::MessageDigest {
    fn from(value: DigestAlgorithm) -> Self {
        match value {
            DigestAlgorithm::Sha256 => openssl::hash::MessageDigest::sha256(),
            DigestAlgorithm::Sha512 => openssl::hash::MessageDigest::sha512(),
            DigestAlgorithm::Sha3_256 => openssl::hash::MessageDigest::sha3_256(),
            DigestAlgorithm::Sha3_512 => openssl::hash::MessageDigest::sha3_512(),
        }
    }
}

impl From<DigestAlgorithm> for &'static openssl::md::MdRef {
    fn from(value: DigestAlgorithm) -> Self {
        match value {
            DigestAlgorithm::Sha256 => openssl::md::Md::sha256(),
            DigestAlgorithm::Sha512 => openssl::md::Md::sha512(),
            DigestAlgorithm::Sha3_256 => openssl::md::Md::sha3_256(),
            DigestAlgorithm::Sha3_512 => openssl::md::Md::sha3_512(),
        }
    }
}

/// Errors that occur when handling client requests.
///
/// These errors are particular to the request and the server will continue
/// to process additional requests on the connection.
#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ServerError {
    #[error("The user '{0}' does not exist in the database")]
    NoSuchUser(String),

    #[error("The requested operation requires administrator privileges")]
    RequiresAdmin,

    #[error("An internal server error occurred; notify an administrator to check the logs")]
    Internal,
}

#[cfg(feature = "server")]
impl From<sqlx::Error> for ServerError {
    fn from(error: sqlx::Error) -> Self {
        tracing::error!(?error, "A database error occurred");
        Self::Internal
    }
}

impl From<std::io::Error> for ServerError {
    fn from(error: std::io::Error) -> Self {
        tracing::error!(?error, "An IO error occurred");
        Self::Internal
    }
}

impl From<anyhow::Error> for ServerError {
    fn from(error: anyhow::Error) -> Self {
        tracing::error!(?error, "An error occurred");
        Self::Internal
    }
}

impl From<JoinError> for ServerError {
    fn from(error: JoinError) -> Self {
        tracing::error!(?error, "tokio task failed to join");
        Self::Internal
    }
}