snix_store/pathinfoservice/
from_addr.rs

1use super::PathInfoService;
2
3use crate::composition::REG;
4use snix_castore::Error;
5use snix_castore::composition::{
6    CompositionContext, DeserializeWithRegistry, ServiceBuilder, with_registry,
7};
8use std::sync::Arc;
9use url::Url;
10
11/// Constructs a new instance of a [PathInfoService] from an URI.
12///
13/// The following URIs are supported:
14/// - `memory:`
15///   Uses a in-memory implementation.
16/// - `redb:`
17///   Uses a in-memory redb implementation.
18/// - `redb:///absolute/path/to/somewhere`
19///   Uses redb, using a path on the disk for persistency. Can be only opened
20///   from one process at the same time.
21/// - `nix+https://cache.nixos.org?trusted-public-keys=cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=`
22///   Exposes the Nix binary cache as a PathInfoService, ingesting NARs into the
23///   {Blob,Directory}Service. You almost certainly want to use this with some cache.
24///   The `trusted-public-keys` URL parameter can be provided, which will then
25///   enable signature verification.
26/// - `grpc+unix:///absolute/path/to/somewhere`
27///   Connects to a local snix-store gRPC service via Unix socket.
28/// - `grpc+http://host:port`, `grpc+https://host:port`
29///   Connects to a (remote) snix-store gRPC service.
30///
31/// As the [PathInfoService] needs to talk to [snix_castore::blobservice::BlobService] and
32/// [snix_castore::directoryservice::DirectoryService], these also need to be passed in.
33pub async fn from_addr(
34    uri: &str,
35    context: Option<&CompositionContext<'_>>,
36) -> Result<Arc<dyn PathInfoService>, Box<dyn std::error::Error + Send + Sync>> {
37    #[allow(unused_mut)]
38    let mut url =
39        Url::parse(uri).map_err(|e| Error::StorageError(format!("unable to parse url: {}", e)))?;
40
41    let path_info_service_config = with_registry(&REG, || {
42        <DeserializeWithRegistry<Box<dyn ServiceBuilder<Output = dyn PathInfoService>>>>::try_from(
43            url,
44        )
45    })?
46    .0;
47    let path_info_service = path_info_service_config
48        .build(
49            "anonymous",
50            context.unwrap_or(&CompositionContext::blank(&REG)),
51        )
52        .await?;
53
54    Ok(path_info_service)
55}
56
57#[cfg(test)]
58mod tests {
59    use super::from_addr;
60    use crate::composition::REG;
61    use rstest::rstest;
62    use snix_castore::blobservice::{BlobService, MemoryBlobServiceConfig};
63    use snix_castore::composition::{Composition, DeserializeWithRegistry, ServiceBuilder};
64    use snix_castore::directoryservice::{DirectoryService, MemoryDirectoryServiceConfig};
65    use std::sync::LazyLock;
66    use tempfile::TempDir;
67
68    static TMPDIR_REDB_1: LazyLock<TempDir> = LazyLock::new(|| TempDir::new().unwrap());
69    static TMPDIR_REDB_2: LazyLock<TempDir> = LazyLock::new(|| TempDir::new().unwrap());
70
71    // the gRPC tests below don't fail, because we connect lazily.
72
73    #[rstest]
74    /// This uses a unsupported scheme.
75    #[case::unsupported_scheme("http://foo.example/test", false)]
76    /// This correctly sets the scheme, and doesn't set a path.
77    #[case::memory_valid("memory://", true)]
78    /// This sets a memory url host to `foo`
79    #[case::memory_invalid_host("memory://foo", false)]
80    /// This sets a memory url path to "/", which is invalid.
81    #[case::memory_invalid_root_path("memory:///", false)]
82    /// This sets a memory url path to "/foo", which is invalid.
83    #[case::memory_invalid_root_path_foo("memory:///foo", false)]
84    /// redb with a host, and a valid path path, which should fail.
85    #[case::redb_invalid_host_with_valid_path(&format!("redb://foo.example{}", &TMPDIR_REDB_1.path().join("bar").to_str().unwrap()), false)]
86    /// redb with / as path, which should fail.
87    #[case::redb_invalid_root("redb:///", false)]
88    /// This configures redb with a valid path, which should succeed.
89    #[case::redb_valid_path(&format!("redb://{}", &TMPDIR_REDB_2.path().join("foo").to_str().unwrap()), true)]
90    /// redb using the in-memory backend, which should succeed.
91    #[case::redb_valid_in_memory("redb://", true)]
92    /// Correct Scheme for the cache.nixos.org binary cache.
93    #[case::correct_nix_https("nix+https://cache.nixos.org", true)]
94    /// Correct Scheme for the cache.nixos.org binary cache (HTTP URL).
95    #[case::correct_nix_http("nix+http://cache.nixos.org", true)]
96    /// Correct Scheme for Nix HTTP Binary cache, with a subpath.
97    #[case::correct_nix_http_with_subpath("nix+http://192.0.2.1/foo", true)]
98    /// Correct Scheme for Nix HTTP Binary cache, with a subpath and port.
99    #[case::correct_nix_http_with_subpath_and_port("nix+http://[::1]:8080/foo", true)]
100    /// Correct Scheme for the cache.nixos.org binary cache, and correct trusted public key set
101    #[case::correct_nix_https_with_trusted_public_key(
102        "nix+https://cache.nixos.org?trusted-public-keys=cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=",
103        true
104    )]
105    /// Correct Scheme for the cache.nixos.org binary cache, and two correct trusted public keys set
106    #[case::correct_nix_https_with_two_trusted_public_keys(
107        "nix+https://cache.nixos.org?trusted-public-keys=cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=%20foo:jp4fCEx9tBEId/L0ZsVJ26k0wC0fu7vJqLjjIGFkup8=",
108        true
109    )]
110    /// Correct scheme to connect to a unix socket.
111    #[case::grpc_valid_unix_socket("grpc+unix:///path/to/somewhere", true)]
112    /// Correct scheme for unix socket, but setting a host too, which is invalid.
113    #[case::grpc_invalid_unix_socket_and_host("grpc+unix://host.example/path/to/somewhere", false)]
114    /// Correct scheme to connect to localhost, with port 12345
115    #[case::grpc_valid_ipv6_localhost_port_12345("grpc+http://[::1]:12345", true)]
116    /// Correct scheme to connect to localhost over http, without specifying a port.
117    #[case::grpc_valid_http_host_without_port("grpc+http://localhost", true)]
118    /// Correct scheme to connect to localhost over http, without specifying a port.
119    #[case::grpc_valid_https_host_without_port("grpc+https://localhost", true)]
120    /// Correct scheme to connect to localhost over http, but with additional path, which is invalid.
121    #[case::grpc_invalid_host_and_path("grpc+http://localhost/some-path", false)]
122    /// A valid example for Bigtable.
123    #[cfg_attr(
124        all(feature = "cloud", feature = "integration"),
125        case::bigtable_valid(
126            "bigtable://instance-1?project_id=project-1&table_name=table-1&family_name=cf1",
127            true
128        )
129    )]
130    /// An invalid example for Bigtable, missing fields
131    #[cfg_attr(
132        all(feature = "cloud", feature = "integration"),
133        case::bigtable_invalid_missing_fields("bigtable://instance-1", false)
134    )]
135    #[tokio::test]
136    async fn test_from_addr_tokio(#[case] uri_str: &str, #[case] exp_succeed: bool) {
137        let mut comp = Composition::new(&REG);
138        comp.extend(vec![(
139            "root".into(),
140            DeserializeWithRegistry(Box::new(MemoryBlobServiceConfig {})
141                as Box<dyn ServiceBuilder<Output = dyn BlobService>>),
142        )]);
143        comp.extend(vec![(
144            "root".into(),
145            DeserializeWithRegistry(Box::new(MemoryDirectoryServiceConfig {})
146                as Box<dyn ServiceBuilder<Output = dyn DirectoryService>>),
147        )]);
148
149        let resp = from_addr(uri_str, Some(&comp.context())).await;
150
151        if exp_succeed {
152            resp.expect("should succeed");
153        } else {
154            assert!(resp.is_err(), "should fail");
155        }
156    }
157}