Skip to main content

passalong_https/
lib.rs

1//! passalong-server storage backend for `passalong`: the `https` kind.
2//!
3//! It is written from the server's published API documents alone; the
4//! server is AGPL-3.0-or-later and no code of it is used here. Like the SSH
5//! backend, it is kept free of CLI dependencies so GUI and Android
6//! front-ends can reuse it.
7
8pub mod admin;
9pub mod api;
10pub mod client;
11pub mod error;
12pub mod store;
13pub mod tls;
14
15use std::sync::Arc;
16
17use passalong_core::api_key::load_api_key;
18use passalong_core::clock::SystemClock;
19use passalong_core::config::Config;
20use passalong_core::crypto::KeyId;
21use passalong_core::encryption::{Claim, EncryptionError, SystemGit, load_key_file, opening};
22use passalong_core::store::{AdminFuture, BackendFuture, BackendRegistry, Store, StoreError};
23
24pub use admin::HttpEncryptionAdmin;
25pub use client::Client;
26pub use error::{Code, HttpsError, Problem};
27pub use store::{HttpStore, Partition, store_error};
28
29use crate::api::EncryptionState;
30
31/// Adds the `https` kind to `registry`.
32pub fn register(registry: &mut BackendRegistry) {
33    registry.register("https", opener);
34    registry.register_admin("https", admin_opener);
35}
36
37fn admin_opener(config: &Config) -> AdminFuture<'_> {
38    Box::pin(async move {
39        let admin = HttpEncryptionAdmin::new(connect(config)?, Arc::new(SystemClock));
40        Ok(Box::new(admin) as Box<dyn passalong_core::encryption::EncryptionAdmin>)
41    })
42}
43
44fn opener(config: &Config) -> BackendFuture<'_> {
45    Box::pin(async move { Ok(Box::new(open_https_store(config).await?) as Box<dyn Store>) })
46}
47
48/// A client of the server `config` names, with its API key.
49///
50/// # Errors
51///
52/// [`StoreError::Config`] without a `[server.https]` section or an API key,
53/// the key file's refusal, and the transport's error.
54pub fn connect(config: &Config) -> Result<Arc<Client>, StoreError> {
55    let https =
56        config.server.https.as_ref().ok_or_else(|| {
57            StoreError::Config("the `server.https` section is missing".to_owned())
58        })?;
59    let key = load_api_key(&https.api_key_file, &SystemGit::new())
60        .map_err(EncryptionError::from)?
61        .ok_or_else(|| {
62            StoreError::Config(format!(
63                "no API key in {}: run `passalong init`, or put the key the server's operator gave you there",
64                https.api_key_file.display()
65            ))
66        })?;
67    Ok(Arc::new(Client::new(https, key).map_err(store_error)?))
68}
69
70/// What the server says about the workspace's encryption.
71///
72/// # Errors
73///
74/// [`StoreError::Backend`] when it names a state or key id this client
75/// cannot read.
76pub fn claim(encryption: &api::Encryption) -> Result<Claim, StoreError> {
77    let key_id = || {
78        let id = encryption.key_id.as_deref().unwrap_or_default();
79        KeyId::parse(id).map_err(|_| {
80            StoreError::Backend(format!(
81                "the server names the key id `{id}`, which is not one"
82            ))
83        })
84    };
85    Ok(match encryption.state {
86        EncryptionState::Plaintext => Claim::Plain,
87        EncryptionState::Sealed => Claim::Encrypted(key_id()?),
88        // The server tells when a rewrite's lease ends, not when it began.
89        EncryptionState::Rewriting => Claim::Rewriting { started: None },
90        _ => {
91            return Err(StoreError::Backend(
92                "the server reports an encryption state this version of passalong does not know"
93                    .to_owned(),
94            ));
95        }
96    })
97}
98
99/// Opens the workspace `config` names for its device: sealed with the
100/// device's key, or plaintext. A device holding a key never opens a
101/// workspace as plaintext, whatever the server says.
102///
103/// # Errors
104///
105/// As [`connect`], the refusals of `opening`, and the server's error.
106pub async fn open_https_store(config: &Config) -> Result<HttpStore, StoreError> {
107    let client = connect(config)?;
108    let workspace = client.workspace().await.map_err(store_error)?;
109    let key = match &config.client.key_file {
110        Some(path) => load_key_file(path, &SystemGit::new()).map_err(EncryptionError::from)?,
111        None => None,
112    };
113    let sealer = opening(claim(&workspace.encryption)?, key)?;
114    tracing::debug!(workspace = %workspace.name, sealed = sealer.is_some(), "opened a server workspace");
115    Ok(HttpStore::new(client, sealer, Arc::new(SystemClock)))
116}
117
118/// Version of this crate, shared by every crate in the workspace.
119pub const VERSION: &str = env!("CARGO_PKG_VERSION");
120
121#[cfg(test)]
122mod tests {
123    #[test]
124    fn version_is_the_workspace_version() {
125        assert_eq!(super::VERSION, "0.3.0");
126    }
127}