lexe/unstable/provision.rs
1//! Provision-related helpers and utilities.
2
3use std::{
4 collections::{BTreeMap, BTreeSet},
5 sync::LazyLock,
6};
7
8use anyhow::Context;
9use lexe_api::def::UserNodeProvisionApi;
10use lexe_common::{
11 api::{provision::NodeProvisionRequest, version::NodeEnclave},
12 constants,
13 releases::Release,
14};
15use lexe_enclave::enclave;
16use lexe_node_client::client::NodeClient;
17use lexe_tokio::task::LxTask;
18use serde::Deserialize;
19use tracing::{debug, info, info_span, warn};
20
21use crate::{config::WalletEnv, types::auth::RootSeed};
22
23/// The contents of `public/releases.json`.
24pub static RELEASES_JSON: &str = include_str!("../../data/releases.json");
25
26/// The measurements of the `RELEASE_WINDOW_SIZE` latest trusted node releases.
27/// This is the set of measurements that we want to provision.
28/// There is no need to provision anything older than this.
29pub static LATEST_TRUSTED_MEASUREMENTS: LazyLock<
30 BTreeSet<enclave::Measurement>,
31> = LazyLock::new(|| {
32 trusted_node_releases()
33 .values()
34 .rev()
35 .take(constants::RELEASE_WINDOW_SIZE)
36 .map(|release| release.measurement)
37 .collect()
38});
39
40/// Models the structure of a releases.json file.
41#[derive(Deserialize)]
42pub struct ReleasesJson(
43 pub BTreeMap<String, BTreeMap<semver::Version, Release>>,
44);
45
46/// The set of trusted node releases (populated from releases.json).
47///
48/// The user trusts these releases simply by installing the open-source app or
49/// SDK library which has these values hard-coded. This prevents Lexe from
50/// pushing out unilateral node updates without the user's consent.
51pub fn trusted_node_releases() -> BTreeMap<semver::Version, Release> {
52 releases_json().0.remove("node").unwrap_or_default()
53}
54
55/// The latest trusted node release and its version.
56pub fn latest_trusted_node_release() -> (semver::Version, Release) {
57 trusted_node_releases()
58 .pop_last()
59 .expect("No node releases")
60}
61
62/// Parses [`RELEASES_JSON`] into a [`ReleasesJson`].
63pub fn releases_json() -> ReleasesJson {
64 serde_json::from_str(RELEASES_JSON).expect("Invalid releases.json")
65}
66
67// TODO(max): Questionable whether it's actually OK to spawn tokio tasks here.
68// Does it complicate app FFI for downstream devs? Python SDK?
69// Maybe we should just provision everything inline, especially once we
70// implement server-side calculation of enclaves_to_provision, as
71// `LexeWallet`s without persistence won't need to always try to provision
72// everything returned by `current_enclaves()`.
73
74/// Helper to provision to the given enclaves.
75///
76/// - `allow_gvfs_access`: See [`NodeProvisionRequest::allow_gvfs_access`].
77/// - `google_auth_code`: See [`NodeProvisionRequest::google_auth_code`].
78/// - `maybe_encrypted_seed`: See [`NodeProvisionRequest::encrypted_seed`].
79pub(crate) async fn provision_all(
80 node_client: NodeClient,
81 enclaves_to_provision: BTreeSet<NodeEnclave>,
82 root_seed: RootSeed,
83 wallet_env: WalletEnv,
84 google_auth_code: Option<String>,
85 allow_gvfs_access: bool,
86 encrypted_seed: Option<Vec<u8>>,
87) -> anyhow::Result<()> {
88 debug!("Starting provisioning: {enclaves_to_provision:?}");
89
90 // Make sure all enclaves corresponding to the latest release in
91 // `trusted_node_releases()` are provisioned before we return, so that when
92 // we make our first request which runs the node, we are generally running
93 // the latest trusted release.
94 //
95 // All other enclaves returned by the backend are provisioned in a detached
96 // background task which doesn't block app / client startup.
97 let latest_measurement = if wallet_env.deploy_env.is_staging_or_prod() {
98 trusted_node_releases()
99 .into_values()
100 .next_back()
101 .map(|release| release.measurement)
102 } else {
103 // No releases.json for dev, so just consider the latest enclave
104 // returned by the backend as the "latest trusted" release.
105 enclaves_to_provision.last().map(|e| e.measurement)
106 };
107 let (latest_enclaves, secondary_enclaves): (BTreeSet<_>, BTreeSet<_>) =
108 enclaves_to_provision
109 .into_iter()
110 .partition(|e| Some(e.measurement) == latest_measurement);
111
112 // Provision the latest trusted enclaves inline.
113 // NOTE: We provision enclaves serially (here and in the secondary task)
114 // because each provision updates the approved versions list, and we don't
115 // currently have a locking mechanism.
116 for enclave in latest_enclaves {
117 let root_seed_clone = clone_root_seed(&root_seed);
118 provision_one(
119 &node_client,
120 enclave,
121 root_seed_clone,
122 wallet_env,
123 google_auth_code.clone(),
124 allow_gvfs_access,
125 encrypted_seed.clone(),
126 )
127 .await?;
128 }
129
130 // Early return if no work left to do
131 if secondary_enclaves.is_empty() {
132 return Ok(());
133 }
134
135 // Provision remaining versions asynchronously so that we don't block
136 // app startup.
137
138 // TODO(max): In the future we may want to drive the secondary
139 // provisioning in function calls instead of background tasks. Some sage
140 // advice from wizard Philip:
141 //
142 // """
143 // I've found that structuring everything as function calls driven by
144 // the flutter frontend to the app-rs library ends up being the
145 // best approach in the end.
146 //
147 // - The flutter frontend owns the page and app lifecycle, best understands
148 // what calls and services are relevant, and trying to keep that in sync
149 // with Rust is cumbersome.
150 // - It's much easier to mock out RPC-style fn calls for design work.
151 // - Reporting errors to the user is also easy, since the error gets bubbled
152 // up to the frontend to display.
153 // - If a background task has an error, there's no clear way to report to
154 // the user, so you just log and things are silently broken.
155 // """
156 const SPAN_NAME: &str = "(secondary-provision)";
157 let task =
158 LxTask::spawn_with_span(SPAN_NAME, info_span!(SPAN_NAME), async move {
159 for enclave in secondary_enclaves {
160 let root_seed_clone = clone_root_seed(&root_seed);
161 let provision_result = provision_one(
162 &node_client,
163 enclave.clone(),
164 root_seed_clone,
165 wallet_env,
166 google_auth_code.clone(),
167 allow_gvfs_access,
168 encrypted_seed.clone(),
169 )
170 .await;
171
172 if let Err(e) = provision_result {
173 warn!(
174 version = %enclave.version,
175 measurement = %enclave.measurement,
176 machine_id = %enclave.machine_id,
177 "Secondary provision failed: {e:#}"
178 );
179 }
180 }
181
182 debug!("Secondary provisioning complete");
183 });
184
185 // TODO(max): Ideally, we could await on this ephemeral task somewhere
186 // for structured concurrency. But not sure if it even matters, as the
187 // mobile OS will often just kill the app.
188 task.detach();
189
190 Ok(())
191}
192
193/// Provisions a single enclave.
194async fn provision_one(
195 node_client: &NodeClient,
196 enclave: NodeEnclave,
197 root_seed: RootSeed,
198 wallet_env: WalletEnv,
199 google_auth_code: Option<String>,
200 allow_gvfs_access: bool,
201 // TODO(max): We could have cheaper cloning by using Bytes here
202 encrypted_seed: Option<Vec<u8>>,
203) -> anyhow::Result<()> {
204 let provision_req = NodeProvisionRequest {
205 root_seed: root_seed.into_unstable(),
206 deploy_env: wallet_env.deploy_env,
207 network: wallet_env.network,
208 google_auth_code,
209 allow_gvfs_access,
210 encrypted_seed,
211 };
212 node_client
213 .provision(&enclave, provision_req)
214 .await
215 .context("Failed to provision node")?;
216
217 info!(
218 version = %enclave.version,
219 measurement = %enclave.measurement,
220 machine_id = %enclave.machine_id,
221 "Provision success:"
222 );
223
224 Ok(())
225}
226
227/// Clone a RootSeed reference into a new RootSeed instance.
228// TODO(phlip9): we should get rid of this helper eventually. We could
229// use something like a `Cow<'a, &RootSeed>` in `NodeProvisionRequest`. Ofc
230// we still have the seed serialized in a heap-allocated json blob when we
231// make the request, which is much harder for us to zeroize...
232pub fn clone_root_seed(root_seed_ref: &RootSeed) -> RootSeed {
233 RootSeed::from_bytes(root_seed_ref.as_bytes())
234 .expect("RootSeed always contains 32 bytes")
235}
236
237#[cfg(test)]
238mod test {
239 use super::*;
240
241 /// Test that [`LATEST_TRUSTED_MEASUREMENTS`] doesn't panic and contains an
242 /// entry. Implicitly tests [`trusted_releases`] and [`releases_json`].
243 #[test]
244 fn test_trusted_measurements() {
245 assert!(!LATEST_TRUSTED_MEASUREMENTS.is_empty());
246 }
247}