blob: fa648c1f0ce04561ab2a81abf42fd65a87c61418 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use crate::{
DeviceIdentity, RegisteredRootId, RemoteClientError, RemoteHostConnection, RootId,
ServerDirectorySnapshot, ServerHostEntry, link::Link,
};
use maka_remote_pairing::{RelayEndpoint, parse_peer_id, valid_relay_bearer};
use maka_remote_transport::{PeerEndpoint, Relay, TlsTrust};
use reqwest::{Client, RequestBuilder, StatusCode, Url, redirect::Policy};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use std::{io, net::IpAddr, path::Path, time::Duration};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ServerReadError {
#[error("Maka Server URL must be an HTTPS origin or a loopback HTTP origin")]
InvalidOrigin,
#[error("Maka Server custom TLS trust requires HTTPS")]
InsecureTrust,
#[error("Maka Server TLS configuration failed")]
Tls(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("invalid Maka Server Bearer token")]
InvalidToken,
#[error("invalid mirror session ID")]
InvalidSessionId,
#[error("Maka Server returned {0}")]
Status(StatusCode),
#[error("Maka Server HTTP request failed")]
Http(#[source] reqwest::Error),
#[error("invalid Maka Server JSON")]
Json(#[from] serde_json::Error),
#[error("Maka Server background task failed")]
DecodeTask(#[from] tokio::task::JoinError),
#[error("invalid Maka Server certificate SHA-256 pin")]
InvalidPin,
#[error("could not access saved Maka Server membership")]
Storage(#[from] io::Error),
}
impl ServerReadError {
pub fn is_unauthorized(&self) -> bool {
matches!(self, Self::Status(StatusCode::UNAUTHORIZED))
}
pub fn is_auth_rejected(&self) -> bool {
matches!(
self,
Self::Status(StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN)
)
}
}
#[derive(Debug, Default)]
pub struct MirrorReadFilter<'a> {
pub repo_identity: Option<&'a str>,
pub root_id: Option<&'a RegisteredRootId>,
/// Pass the previous page's `nextCursor` when it contains a cursor.
pub cursor: Option<&'a Value>,
pub limit: Option<u32>,
}
#[derive(Clone)]
/// Authenticated access to the Maka Server directory and read-only mirror.
pub struct MakaServerReadClient {
origin: Url,
http: Client,
}
impl MakaServerReadClient {
pub fn new(server_url: &str, trust: TlsTrust) -> Result<Self, ServerReadError> {
Self::new_with_insecure_http(server_url, trust, false)
}
pub fn new_with_insecure_http(
server_url: &str,
trust: TlsTrust,
allow_insecure_http: bool,
) -> Result<Self, ServerReadError> {
let origin = Url::parse(server_url).map_err(|_| ServerReadError::InvalidOrigin)?;
let host = origin.host_str().ok_or(ServerReadError::InvalidOrigin)?;
if !origin.username().is_empty()
|| origin.password().is_some()
|| origin.query().is_some()
|| origin.fragment().is_some()
|| origin.path() != "/"
{
return Err(ServerReadError::InvalidOrigin);
}
let is_loopback = host == "localhost"
|| host
.trim_matches(['[', ']'])
.parse::<IpAddr>()
.is_ok_and(|ip| ip.is_loopback());
match origin.scheme() {
"https" => {}
"http" if is_loopback || allow_insecure_http => {
if trust != TlsTrust::System {
return Err(ServerReadError::InsecureTrust);
}
}
_ => return Err(ServerReadError::InvalidOrigin),
}
let tls = trust.client_config(&origin).map_err(ServerReadError::Tls)?;
let http = Client::builder()
.redirect(Policy::none())
.no_proxy()
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15))
.tls_backend_preconfigured(tls)
.build()
.map_err(http_error)?;
Ok(Self { origin, http })
}
pub async fn directory(&self, token: &str) -> Result<ServerDirectorySnapshot, ServerReadError> {
Self::json(self.get(token, &["directory"], [])?).await
}
pub async fn mirror_projects(&self, token: &str) -> Result<Value, ServerReadError> {
Self::json(self.get(token, &["mirror", "projects"], [])?).await
}
pub async fn mirror_sessions(
&self,
token: &str,
filter: MirrorReadFilter<'_>,
) -> Result<Value, ServerReadError> {
let cursor = filter.cursor.map(Value::to_string);
let limit = filter.limit.map(|value| value.to_string());
Self::json(self.get(
token,
&["mirror", "sessions"],
[
("repo_identity", filter.repo_identity),
("root_id", filter.root_id.map(RegisteredRootId::as_str)),
("cursor", cursor.as_deref()),
("limit", limit.as_deref()),
],
)?)
.await
}
/// Pass the previous page's non-null `nextCursor` to resume the transcript.
/// A history change expires the cursor (409). A message that exceeds an empty page returns 413.
pub async fn mirror_transcript(
&self,
token: &str,
root: &RegisteredRootId,
session: &str,
cursor: Option<&Value>,
limit: Option<u32>,
) -> Result<Value, ServerReadError> {
if matches!(session, "" | "." | "..") {
return Err(ServerReadError::InvalidSessionId);
}
let cursor = cursor.map(Value::to_string);
let limit = limit.map(|value| value.to_string());
Self::json(self.get(
token,
&["mirror", "sessions", root.as_str(), session],
[("cursor", cursor.as_deref()), ("limit", limit.as_deref())],
)?)
.await
}
pub async fn mirror_search(
&self,
token: &str,
query: &str,
limit: Option<u32>,
) -> Result<Value, ServerReadError> {
let limit = limit.map(|value| value.to_string());
Self::json(self.get(
token,
&["mirror", "search"],
[("q", Some(query)), ("limit", limit.as_deref())],
)?)
.await
}
fn get<'a>(
&self,
token: &str,
path: &[&str],
query: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
) -> Result<RequestBuilder, ServerReadError> {
if !valid_relay_bearer(token) {
return Err(ServerReadError::InvalidToken);
}
let mut url = self.origin.clone();
url.path_segments_mut()
.expect("validated HTTP(S) origin")
.pop_if_empty()
.extend(["api", "v1"])
.extend(path.iter().copied());
for (key, value) in query {
if let Some(value) = value {
url.query_pairs_mut().append_pair(key, value);
}
}
Ok(self.http.get(url).bearer_auth(token))
}
async fn enroll(
&self,
identity: &DeviceIdentity,
invite: &str,
display_name: &str,
) -> Result<String, ServerReadError> {
if !valid_relay_bearer(invite) {
return Err(ServerReadError::InvalidToken);
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Joined {
device_token: String,
}
let proof = hex::encode(identity.sign_enrollment(format!("device\n{invite}").as_bytes()));
let url = self
.origin
.join("/api/v1/devices/join")
.expect("static API path");
let joined: Joined = Self::json(
self.http
.post(url)
.bearer_auth(invite)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(serde_json::to_vec(&serde_json::json!({
"peerId": identity.public_key().to_string(),
"displayName": display_name,
"proof": proof,
}))?),
)
.await?;
Ok(joined.device_token)
}
pub async fn revoke_host(
&self,
token: &str,
root_id: &str,
purge_mirror: bool,
) -> Result<bool, ServerReadError> {
if !valid_relay_bearer(token) {
return Err(ServerReadError::InvalidToken);
}
#[derive(Deserialize)]
struct Revoked {
revoked: bool,
}
let url = self
.origin
.join("/api/v1/hosts/revoke")
.expect("static API path");
let mut req = self
.http
.post(url)
.bearer_auth(token)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(serde_json::to_vec(&serde_json::json!({
"rootId": root_id,
"purgeMirror": purge_mirror,
}))?);
if purge_mirror {
req = req.timeout(Duration::from_secs(60));
}
Ok(Self::json::<Revoked>(req).await?.revoked)
}
pub async fn revoke_device(&self, token: &str, peer_id: &str) -> Result<bool, ServerReadError> {
if !valid_relay_bearer(token) {
return Err(ServerReadError::InvalidToken);
}
#[derive(Deserialize)]
struct Revoked {
revoked: bool,
}
let url = self
.origin
.join("/api/v1/devices/revoke")
.expect("static API path");
let req = self
.http
.post(url)
.bearer_auth(token)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(serde_json::to_vec(&serde_json::json!({
"peerId": peer_id,
}))?);
Ok(Self::json::<Revoked>(req).await?.revoked)
}
async fn relays(&self) -> Result<Vec<RelayEndpoint>, ServerReadError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Health {
relay_urls: Vec<RelayEndpoint>,
}
let url = self.origin.join("/api/v1/health").expect("static API path");
Ok(Self::json::<Health>(self.http.get(url)).await?.relay_urls)
}
async fn json<T: DeserializeOwned + Send + 'static>(
request: RequestBuilder,
) -> Result<T, ServerReadError> {
let response = request.send().await.map_err(http_error)?;
if !response.status().is_success() {
return Err(ServerReadError::Status(response.status()));
}
let body = response.bytes().await.map_err(http_error)?;
Ok(tokio::task::spawn_blocking(move || serde_json::from_slice(&body)).await??)
}
}
fn http_error(error: reqwest::Error) -> ServerReadError {
ServerReadError::Http(error.without_url())
}
/// Credentials live in the private application support directory, outside
/// both the operation journal and the UI restoration snapshot.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Membership {
server_url: String,
device_token: String,
cert_sha256: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
allow_insecure_http: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerEnrollment {
pub server_url: String,
pub invite_token: String,
pub cert_sha256: Option<String>,
pub device_name: String,
#[serde(default)]
pub allow_insecure_http: bool,
}
#[derive(Clone)]
pub struct ServerConnection {
client: MakaServerReadClient,
token: std::sync::Arc<str>,
}
#[derive(Deserialize)]
#[serde(
rename_all = "camelCase",
rename_all_fields = "camelCase",
tag = "kind"
)]
pub enum MirrorRequest {
Projects,
Sessions {
root_id: Option<RootId>,
repo_identity: Option<String>,
cursor: Option<Value>,
},
Transcript {
root_id: RootId,
session_id: String,
cursor: Option<Value>,
},
Search {
query: String,
},
}
pub struct ServerDirectory {
pub hosts: Vec<ServerHostEntry>,
pub revoked: Vec<RootId>,
relays: Vec<RelayEndpoint>,
relay_token: Option<String>,
}
impl ServerConnection {
pub fn server_url(&self) -> &str {
self.client.origin.as_str()
}
pub async fn load(path: &Path) -> Result<Option<Self>, ServerReadError> {
let path = path.to_owned();
let membership = tokio::task::spawn_blocking(move || match std::fs::File::open(path) {
Ok(file) => Ok(Some(serde_json::from_reader::<_, Membership>(
io::BufReader::new(file),
)?)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(ServerReadError::Storage(error)),
})
.await??;
membership
.map(|membership| {
Ok(Self {
client: client(
&membership.server_url,
membership.cert_sha256.as_deref(),
membership.allow_insecure_http,
)?,
token: membership.device_token.into(),
})
})
.transpose()
}
pub async fn enroll(
path: &Path,
identity: &DeviceIdentity,
input: ServerEnrollment,
) -> Result<Self, ServerReadError> {
let client = client(
&input.server_url,
input.cert_sha256.as_deref(),
input.allow_insecure_http,
)?;
let token = client
.enroll(identity, &input.invite_token, &input.device_name)
.await?;
Self::persist_membership(
path,
client,
token,
input.cert_sha256,
input.allow_insecure_http,
)
.await
}
/// Enroll in memory without modifying persisted external server membership on disk.
/// Used to auto-attach Desktop Workbench to its own running Built-in Maka Server.
pub async fn enroll_ephemeral(
identity: &DeviceIdentity,
input: ServerEnrollment,
) -> Result<Self, ServerReadError> {
let client = client(
&input.server_url,
input.cert_sha256.as_deref(),
input.allow_insecure_http,
)?;
let token = client
.enroll(identity, &input.invite_token, &input.device_name)
.await?;
Ok(Self {
client,
token: token.into(),
})
}
/// Persist a device token obtained atomically from companion Host+Device enrollment.
pub async fn save_membership(
path: &Path,
server_url: &str,
cert_sha256: Option<String>,
device_token: String,
allow_insecure_http: bool,
) -> Result<Self, ServerReadError> {
let client = client(server_url, cert_sha256.as_deref(), allow_insecure_http)?;
Self::persist_membership(path, client, device_token, cert_sha256, allow_insecure_http).await
}
async fn persist_membership(
path: &Path,
client: MakaServerReadClient,
token: String,
cert_sha256: Option<String>,
allow_insecure_http: bool,
) -> Result<Self, ServerReadError> {
let membership = Membership {
server_url: client.origin.to_string(),
device_token: token.clone(),
cert_sha256,
allow_insecure_http,
};
let path = path.to_owned();
tokio::task::spawn_blocking(move || {
let parent = path.parent().expect("membership path has a parent");
std::fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
serde_json::to_writer(&mut file, &membership)?;
file.as_file().sync_all()?;
file.persist(&path).map_err(|error| error.error)?;
Ok::<_, ServerReadError>(())
})
.await??;
Ok(Self {
client,
token: token.into(),
})
}
pub async fn remove(path: &Path) -> Result<(), ServerReadError> {
let path = path.to_owned();
tokio::task::spawn_blocking(move || match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(ServerReadError::Storage(error)),
})
.await??;
Ok(())
}
pub async fn snapshot(&self) -> Result<ServerDirectorySnapshot, ServerReadError> {
self.client.directory(&self.token).await
}
pub async fn revoke_host(
&self,
root_id: &str,
purge_mirror: bool,
) -> Result<bool, ServerReadError> {
self.client
.revoke_host(&self.token, root_id, purge_mirror)
.await
}
pub async fn revoke_device(&self, peer_id: &str) -> Result<bool, ServerReadError> {
self.client.revoke_device(&self.token, peer_id).await
}
pub async fn directory(&self) -> Result<ServerDirectory, ServerReadError> {
let (snapshot, relays) =
tokio::try_join!(self.client.directory(&self.token), self.client.relays(),)?;
let revoked = snapshot
.revoked_hosts
.into_iter()
.map(|host| RootId::from(host.root_id))
.collect::<Vec<_>>();
let hosts = snapshot
.hosts
.into_iter()
.filter(|host| {
host.revoked_at_ms.is_none()
&& !revoked
.iter()
.any(|root| root.as_str() == host.root_id.as_str())
})
.collect();
Ok(ServerDirectory {
hosts,
revoked,
relays,
relay_token: snapshot.relay_auth_token,
})
}
/// Return a discriminated status across the native/JS boundary so clients
/// can restart an expired page without parsing error messages.
pub async fn mirror(&self, request: MirrorRequest) -> Result<Value, ServerReadError> {
let result = match request {
MirrorRequest::Projects => self.client.mirror_projects(&self.token).await,
MirrorRequest::Sessions {
root_id,
repo_identity,
cursor,
} => {
let root = root_id
.map(TryInto::try_into)
.transpose()
.map_err(|_| ServerReadError::InvalidSessionId)?;
self.client
.mirror_sessions(
&self.token,
MirrorReadFilter {
root_id: root.as_ref(),
repo_identity: repo_identity.as_deref(),
cursor: cursor.as_ref(),
limit: Some(100),
},
)
.await
}
MirrorRequest::Transcript {
root_id,
session_id,
cursor,
} => {
let root = root_id
.try_into()
.map_err(|_| ServerReadError::InvalidSessionId)?;
self.client
.mirror_transcript(&self.token, &root, &session_id, cursor.as_ref(), Some(100))
.await
}
MirrorRequest::Search { query } => {
self.client
.mirror_search(&self.token, &query, Some(50))
.await
}
};
match result {
Ok(value) => Ok(serde_json::json!({"kind":"ready","value":value})),
Err(ServerReadError::Status(StatusCode::CONFLICT)) => {
Ok(serde_json::json!({"kind":"changed"}))
}
Err(ServerReadError::Status(StatusCode::PAYLOAD_TOO_LARGE)) => {
Ok(serde_json::json!({"kind":"too_large"}))
}
Err(error) => Err(error),
}
}
}
impl ServerDirectory {
pub async fn connect(
&self,
identity: &DeviceIdentity,
host: &ServerHostEntry,
) -> Result<RemoteHostConnection, RemoteClientError> {
let dial = async {
let key = parse_peer_id(host.peer_id.as_str())?;
let relays = host
.relay_urls
.iter()
.map(|route| {
let token = self
.relays
.iter()
.any(|relay| relay == route)
.then(|| self.relay_token.clone())
.flatten();
Relay::new(route, None, token).map_err(RemoteClientError::Transport)
})
.collect::<Result<Vec<_>, _>>()?;
if relays.is_empty() {
return Err(RemoteClientError::NoNativeRoute);
}
let endpoint = PeerEndpoint::bind(identity, &relays, false)
.await
.map_err(RemoteClientError::Transport)?;
let peer = endpoint
.connect(&key)
.await
.map_err(RemoteClientError::Transport)?;
RemoteHostConnection::connect(
Link::peer(endpoint, peer),
host.root_id.as_str(),
identity.public_key().to_string().into(),
)
.await
};
tokio::time::timeout(Duration::from_secs(5), dial)
.await
.map_err(|error| {
RemoteClientError::Io(io::Error::new(io::ErrorKind::TimedOut, error))
})?
}
}
fn client(
url: &str,
pin: Option<&str>,
allow_insecure_http: bool,
) -> Result<MakaServerReadClient, ServerReadError> {
let trust = match pin {
Some(pin) => {
let mut digest = [0; 32];
hex::decode_to_slice(pin, &mut digest).map_err(|_| ServerReadError::InvalidPin)?;
TlsTrust::LeafSha256(digest)
}
None => TlsTrust::System,
};
MakaServerReadClient::new_with_insecure_http(url, trust, allow_insecure_http)
}
/// Sign a Maka Server device enrollment proof for atomic companion Host+Device enrollment.
pub fn sign_device_enrollment_proof(identity: &DeviceIdentity, invite: &str) -> String {
hex::encode(
identity.sign_enrollment(
format!(
"device
{invite}"
)
.as_bytes(),
),
)
}