ferriskey 0.3.4

Rust client for Valkey, built for FlowFabric. Forked from glide-core (valkey-glide).
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
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::OnceLock;

use crate::pipeline::Pipeline;
use crate::value::ProtocolVersion;
use crate::value::{ErrorKind, Error, Result};

use crate::connection::tls::TlsConnParams;

static CRYPTO_PROVIDER: OnceLock<()> = OnceLock::new();

const DEFAULT_PORT: u16 = 6379;

/// Checks if a given string is a valid Valkey URL.
pub fn parse_redis_url(input: &str) -> Option<url::Url> {
    match url::Url::parse(input) {
        Ok(result) => match result.scheme() {
            "redis" | "rediss" | "redis+unix" | "unix" => Some(result),
            _ => None,
        },
        Err(_) => None,
    }
}

/// TlsMode indicates use or do not use verification of certification.
#[derive(Clone, Copy)]
pub enum TlsMode {
    /// Secure verify certification.
    Secure,
    /// Insecure do not verify certification.
    Insecure,
}

/// Defines the connection address.
#[derive(Clone, Debug)]
pub enum ConnectionAddr {
    /// Format for this is `(host, port)`.
    Tcp(String, u16),
    /// Format for this is `(host, port)`.
    TcpTls {
        /// Hostname
        host: String,
        /// Port
        port: u16,
        /// Disable hostname verification when connecting.
        insecure: bool,
        /// TLS certificates and client key.
        tls_params: Option<TlsConnParams>,
    },
    /// Format for this is the path to the unix socket.
    Unix(PathBuf),
}

impl PartialEq for ConnectionAddr {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ConnectionAddr::Tcp(host1, port1), ConnectionAddr::Tcp(host2, port2)) => {
                host1 == host2 && port1 == port2
            }
            (
                ConnectionAddr::TcpTls {
                    host: host1,
                    port: port1,
                    insecure: insecure1,
                    tls_params: _,
                },
                ConnectionAddr::TcpTls {
                    host: host2,
                    port: port2,
                    insecure: insecure2,
                    tls_params: _,
                },
            ) => port1 == port2 && host1 == host2 && insecure1 == insecure2,
            (ConnectionAddr::Unix(path1), ConnectionAddr::Unix(path2)) => path1 == path2,
            _ => false,
        }
    }
}

impl Eq for ConnectionAddr {}

impl ConnectionAddr {
    /// Checks if this address is supported.
    pub fn is_supported(&self) -> bool {
        match *self {
            ConnectionAddr::Tcp(_, _) => true,
            ConnectionAddr::TcpTls { .. } => true,
            ConnectionAddr::Unix(_) => cfg!(unix),
        }
    }
}

impl fmt::Display for ConnectionAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ConnectionAddr::Tcp(ref host, port) => write!(f, "{host}:{port}"),
            ConnectionAddr::TcpTls { ref host, port, .. } => write!(f, "{host}:{port}"),
            ConnectionAddr::Unix(ref path) => write!(f, "{}", path.display()),
        }
    }
}

/// Holds the connection information that redis should use for connecting.
#[derive(Clone, Debug)]
pub struct ConnectionInfo {
    /// A connection address for where to connect to.
    pub addr: ConnectionAddr,
    /// A boxed connection address for where to connect to.
    pub valkey: ValkeyConnectionInfo,
}

/// Types of pubsub subscriptions
#[derive(Clone, Debug, PartialEq, Eq, Hash, Copy)]
pub enum PubSubSubscriptionKind {
    /// Exact channel name.
    Exact = 0,
    /// Pattern-based channel name.
    Pattern = 1,
    /// Sharded pubsub mode.
    Sharded = 2,
}

impl From<PubSubSubscriptionKind> for usize {
    fn from(val: PubSubSubscriptionKind) -> Self {
        val as usize
    }
}

/// Type for pubsub channels/patterns
pub type PubSubChannelOrPattern = Vec<u8>;

/// Type for pubsub channels/patterns
pub type PubSubSubscriptionInfo = HashMap<PubSubSubscriptionKind, HashSet<PubSubChannelOrPattern>>;

/// Valkey connection information used to establish a connection.
#[derive(Clone, Debug, Default)]
pub struct ValkeyConnectionInfo {
    /// The database number to use.  This is usually `0`.
    pub db: i64,
    /// Optionally a username that should be used for connection.
    pub username: Option<String>,
    /// Optionally a password that should be used for connection.
    pub password: Option<String>,
    /// Version of the protocol to use.
    pub protocol: ProtocolVersion,
    /// Optionally a client name that should be used for connection
    pub client_name: Option<String>,
    /// Optionally a library name that should be used for connection
    pub lib_name: Option<String>,
}

impl FromStr for ConnectionInfo {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        s.into_connection_info()
    }
}

/// Converts an object into a connection info struct.
pub trait IntoConnectionInfo {
    /// Converts the object into a connection info object.
    fn into_connection_info(self) -> Result<ConnectionInfo>;
}

impl IntoConnectionInfo for ConnectionInfo {
    fn into_connection_info(self) -> Result<ConnectionInfo> {
        Ok(self)
    }
}

impl IntoConnectionInfo for &str {
    fn into_connection_info(self) -> Result<ConnectionInfo> {
        match parse_redis_url(self) {
            Some(u) => u.into_connection_info(),
            None => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
        }
    }
}

impl<T> IntoConnectionInfo for (T, u16)
where
    T: Into<String>,
{
    fn into_connection_info(self) -> Result<ConnectionInfo> {
        Ok(ConnectionInfo {
            addr: ConnectionAddr::Tcp(self.0.into(), self.1),
            valkey: ValkeyConnectionInfo::default(),
        })
    }
}

impl IntoConnectionInfo for String {
    fn into_connection_info(self) -> Result<ConnectionInfo> {
        match parse_redis_url(&self) {
            Some(u) => u.into_connection_info(),
            None => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
        }
    }
}

fn url_to_tcp_connection_info(url: url::Url) -> Result<ConnectionInfo> {
    let host = match url.host() {
        Some(host) => match host {
            url::Host::Domain(path) => path.to_string(),
            url::Host::Ipv4(v4) => v4.to_string(),
            url::Host::Ipv6(v6) => v6.to_string(),
        },
        None => fail!((ErrorKind::InvalidClientConfig, "Missing hostname")),
    };
    let port = url.port().unwrap_or(DEFAULT_PORT);
    let addr = if url.scheme() == "rediss" || url.scheme() == "valkeys" {
        match url.fragment() {
            Some("insecure") => ConnectionAddr::TcpTls {
                host,
                port,
                insecure: true,
                tls_params: None,
            },
            Some(_) => fail!((
                ErrorKind::InvalidClientConfig,
                "only #insecure is supported as URL fragment"
            )),
            _ => ConnectionAddr::TcpTls {
                host,
                port,
                insecure: false,
                tls_params: None,
            },
        }
    } else {
        ConnectionAddr::Tcp(host, port)
    };
    let query: HashMap<_, _> = url.query_pairs().collect();
    Ok(ConnectionInfo {
        addr,
        valkey: ValkeyConnectionInfo {
            db: match url.path().trim_matches('/') {
                "" => 0,
                path => path.parse::<i64>().map_err(|_| -> Error {
                    (ErrorKind::InvalidClientConfig, "Invalid database number").into()
                })?,
            },
            username: if url.username().is_empty() {
                None
            } else {
                match percent_encoding::percent_decode(url.username().as_bytes()).decode_utf8() {
                    Ok(decoded) => Some(decoded.into_owned()),
                    Err(_) => fail!((
                        ErrorKind::InvalidClientConfig,
                        "Username is not valid UTF-8 string"
                    )),
                }
            },
            password: match url.password() {
                Some(pw) => match percent_encoding::percent_decode(pw.as_bytes()).decode_utf8() {
                    Ok(decoded) => Some(decoded.into_owned()),
                    Err(_) => fail!((
                        ErrorKind::InvalidClientConfig,
                        "Password is not valid UTF-8 string"
                    )),
                },
                None => None,
            },
            protocol: match query.get("resp3") {
                Some(v) => {
                    if v == "true" {
                        ProtocolVersion::RESP3
                    } else {
                        ProtocolVersion::RESP2
                    }
                }
                _ => ProtocolVersion::RESP2,
            },
            client_name: None,
            lib_name: None,
        },
    })
}

#[cfg(unix)]
fn url_to_unix_connection_info(url: url::Url) -> Result<ConnectionInfo> {
    let query: HashMap<_, _> = url.query_pairs().collect();
    Ok(ConnectionInfo {
        addr: ConnectionAddr::Unix(url.to_file_path().map_err(|_| -> Error {
            (ErrorKind::InvalidClientConfig, "Missing path").into()
        })?),
        valkey: ValkeyConnectionInfo {
            db: match query.get("db") {
                Some(db) => db.parse::<i64>().map_err(|_| -> Error {
                    (ErrorKind::InvalidClientConfig, "Invalid database number").into()
                })?,
                None => 0,
            },
            username: query.get("user").map(|username| username.to_string()),
            password: query.get("pass").map(|password| password.to_string()),
            protocol: match query.get("resp3") {
                Some(v) => {
                    if v == "true" {
                        ProtocolVersion::RESP3
                    } else {
                        ProtocolVersion::RESP2
                    }
                }
                _ => ProtocolVersion::RESP2,
            },
            client_name: None,
            lib_name: None,
        },
    })
}

#[cfg(not(unix))]
fn url_to_unix_connection_info(_: url::Url) -> Result<ConnectionInfo> {
    fail!((
        ErrorKind::InvalidClientConfig,
        "Unix sockets are not available on this platform."
    ));
}

impl IntoConnectionInfo for url::Url {
    fn into_connection_info(self) -> Result<ConnectionInfo> {
        match self.scheme() {
            "redis" | "rediss" | "valkey" | "valkeys" => url_to_tcp_connection_info(self),
            "unix" | "redis+unix" => url_to_unix_connection_info(self),
            _ => fail!((
                ErrorKind::InvalidClientConfig,
                "URL provided is not a valkey URL"
            )),
        }
    }
}

// --- Utilities used by aio and other modules ---

pub(crate) fn create_rustls_config(
    insecure: bool,
    tls_params: Option<TlsConnParams>,
) -> Result<rustls::ClientConfig> {
    CRYPTO_PROVIDER.get_or_init(|| {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
    });

    use crate::connection::tls::ClientTlsParams;
    use rustls_platform_verifier::BuilderVerifierExt;

    let config = match tls_params {
        Some(TlsConnParams { root_cert_store: Some(root_cert_store), client_tls_params }) => {
            let config = rustls::ClientConfig::builder().with_root_certificates(root_cert_store);
            match client_tls_params {
                Some(ClientTlsParams {
                    client_cert_chain: client_cert,
                    client_key,
                }) => config
                    .with_client_auth_cert(client_cert, client_key)
                    .map_err(|err| {
                        tls_config_error(
                            "Failed to configure client cert auth with custom root store",
                            err,
                        )
                    })?,
                None => config.with_no_client_auth(),
            }
        }
        Some(tls_params) => {
            let config = rustls::ClientConfig::builder()
                .with_platform_verifier()
                .map_err(|err| {
                    tls_config_error("Failed to configure platform certificate verifier", err)
                })?;
            match tls_params.client_tls_params {
                Some(ClientTlsParams {
                    client_cert_chain: client_cert,
                    client_key,
                }) => config
                    .with_client_auth_cert(client_cert, client_key)
                    .map_err(|err| {
                        tls_config_error(
                            "Failed to configure client cert auth with platform verifier",
                            err,
                        )
                    })?,
                None => config.with_no_client_auth(),
            }
        }
        None => rustls::ClientConfig::builder()
            .with_platform_verifier()
            .map_err(|err| tls_config_error("Failed to configure default TLS settings", err))?
            .with_no_client_auth(),
    };

    if insecure {
        let mut config = config;
        config.enable_sni = false;
        config
            .dangerous()
            .set_certificate_verifier(Arc::new(NoCertificateVerification {
                supported: rustls::crypto::aws_lc_rs::default_provider()
                    .signature_verification_algorithms,
            }));
        return Ok(config);
    }

    Ok(config)
}

fn tls_config_error(context: &'static str, error: impl std::fmt::Display) -> Error {
    Error::from((ErrorKind::InvalidClientConfig, context, error.to_string()))
}

struct NoCertificateVerification {
    supported: rustls::crypto::WebPkiSupportedAlgorithms,
}

impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
    fn verify_server_cert(
        &self,
        _end_entity: &rustls_pki_types::CertificateDer,
        _intermediates: &[rustls_pki_types::CertificateDer],
        _server_name: &rustls::pki_types::ServerName,
        _ocsp_response: &[u8],
        _now: rustls::pki_types::UnixTime,
    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &rustls_pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &rustls_pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        self.supported.supported_schemes()
    }
}

impl fmt::Debug for NoCertificateVerification {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NoCertificateVerification").finish()
    }
}

pub(crate) fn client_set_info_pipeline(lib_name: Option<&str>) -> Pipeline {
    let mut pipeline = crate::cmd::pipe();
    let lib_name_value = lib_name.unwrap_or("UnknownClient");
    let final_lib_name = option_env!("FERRISKEY_NAME").unwrap_or(lib_name_value);
    pipeline
        .cmd("CLIENT")
        .arg("SETINFO")
        .arg("LIB-NAME")
        .arg(final_lib_name)
        .ignore();
    pipeline
        .cmd("CLIENT")
        .arg("SETINFO")
        .arg("LIB-VER")
        .arg(env!("CARGO_PKG_VERSION"))
        .ignore();
    pipeline
}

/// Common logic for checking real cause of hello3 command error
pub fn get_resp3_hello_command_error(err: Error) -> Error {
    if let Some(detail) = err.detail()
        && detail.starts_with("unknown command `HELLO`")
    {
        return (
            ErrorKind::RESP3NotSupported,
            "Redis Server doesn't support HELLO command therefore resp3 cannot be used",
        )
            .into();
    }
    err
}

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

    #[test]
    fn test_client_set_info_pipeline_default_lib_name() {
        let pipeline = client_set_info_pipeline(None);
        let packed_commands = pipeline.get_packed_pipeline();
        let cmd_str = String::from_utf8_lossy(&packed_commands);
        assert!(cmd_str.contains("CLIENT"));
        assert!(cmd_str.contains("SETINFO"));
        assert!(cmd_str.contains("LIB-NAME"));
        assert!(cmd_str.contains("FerrisKey") || cmd_str.contains("UnknownClient"));
    }

    #[test]
    fn test_parse_redis_url() {
        let cases = vec![
            ("redis://127.0.0.1", true),
            ("redis://[::1]", true),
            ("redis+unix:///run/redis.sock", true),
            ("unix:///run/redis.sock", true),
            ("http://127.0.0.1", false),
            ("tcp://127.0.0.1", false),
        ];
        for (url, expected) in cases.into_iter() {
            let res = parse_redis_url(url);
            assert_eq!(
                res.is_some(),
                expected,
                "Parsed result of `{url}` is not expected"
            );
        }
    }

    #[test]
    fn test_url_to_tcp_connection_info() {
        let cases = vec![
            (
                url::Url::parse("redis://127.0.0.1").unwrap(),
                ConnectionInfo {
                    addr: ConnectionAddr::Tcp("127.0.0.1".to_string(), 6379),
                    valkey: Default::default(),
                },
            ),
            (
                url::Url::parse("redis://[::1]").unwrap(),
                ConnectionInfo {
                    addr: ConnectionAddr::Tcp("::1".to_string(), 6379),
                    valkey: Default::default(),
                },
            ),
        ];
        for (url, expected) in cases.into_iter() {
            let res = url_to_tcp_connection_info(url.clone()).unwrap();
            assert_eq!(res.addr, expected.addr, "addr of {url} is not expected");
            assert_eq!(
                res.valkey.db, expected.valkey.db,
                "db of {url} is not expected"
            );
        }
    }
}