| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | use crate::bucket::Bucket; |
| 4 | use crate::protocol::{asset_blob_key, AssetIndex, DeployPointer, Manifest}; |
| 5 | use anyhow::{anyhow, Context}; |
| 6 | use celld_logic::PresenceSnapshot; |
| 7 | use fastwebsockets::{FragmentCollector, Frame, OpCode}; |
| 8 | use hyper::header::HeaderMap; |
| 9 | use rand::RngCore; |
| 10 | use rusqlite::{types::ValueRef, Connection, OpenFlags, OptionalExtension}; |
| 11 | use serde::{Deserialize, Serialize}; |
| 12 | use sha2::{Digest, Sha256}; |
| 13 | use std::fs::File; |
| 14 | use std::future::Future; |
| 15 | use std::path::{Path, PathBuf}; |
| 16 | use std::pin::Pin; |
| 17 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 18 | use std::sync::{Arc, Mutex, OnceLock}; |
| 19 | use std::time::{Duration, Instant}; |
| 20 | use tracing::{info, warn}; |
| 21 | |
| 22 | const DEFAULT_CONTROL_URL: &str = "https://celld.dev"; |
| 23 | const DEFAULT_ENVIRONMENT: &str = "prod"; |
| 24 | const MAX_PRESENCE_CELLS: usize = 50; |
| 25 | const MAX_PRESENCE_CELL_ID_BYTES: usize = 200; |
| 26 | const MAX_EXPLORER_CELL_PAGE: usize = 100; |
| 27 | const MAX_EXPLORER_TABLES: usize = 100; |
| 28 | const MAX_EXPLORER_COLUMNS: usize = 32; |
| 29 | const MAX_EXPLORER_ROWS: usize = 25; |
| 30 | const MAX_EXPLORER_VALUE_BYTES: usize = 2 * 1024; |
| 31 | const MAX_EXPLORER_RESPONSE_BYTES: usize = 96 * 1024; |
| 32 | const MAX_MANAGED_MODULES: usize = 64; |
| 33 | const MAX_MANAGED_MODULE_BYTES: usize = 25 * 1024 * 1024; |
| 34 | |
| 35 | fn restart_on_deployment_enabled() -> bool { |
| 36 | !std::env::var("CELLD_CLOUD_RESTART_ON_DEPLOY") |
| 37 | .is_ok_and(|value| value.eq_ignore_ascii_case("off")) |
| 38 | } |
| 39 | |
| 40 | #[cfg(unix)] |
| 41 | fn restart_process(trigger: &'static str) -> ! { |
| 42 | use std::os::unix::process::CommandExt; |
| 43 | use std::process::Command; |
| 44 | |
| 45 | let executable = match std::env::current_exe() { |
| 46 | Ok(executable) => executable, |
| 47 | Err(error) => { |
| 48 | warn!( |
| 49 | event = "control_plane_restart_exec_failed", |
| 50 | trigger, |
| 51 | %error, |
| 52 | "could not locate celld for process reload; exiting for an external supervisor" |
| 53 | ); |
| 54 | std::process::exit(75); |
| 55 | } |
| 56 | }; |
| 57 | let signer = match crate::peer_probe::reexec_signer_secret() { |
| 58 | Ok(signer) => signer, |
| 59 | Err(error) => { |
| 60 | warn!( |
| 61 | event = "control_plane_restart_exec_failed", |
| 62 | trigger, |
| 63 | %error, |
| 64 | "could not preserve process probe identity; exiting for an external supervisor" |
| 65 | ); |
| 66 | std::process::exit(75); |
| 67 | } |
| 68 | }; |
| 69 | let mut command = Command::new(executable); |
| 70 | command |
| 71 | .args(std::env::args_os().skip(1)) |
| 72 | .env(crate::peer_probe::REEXEC_SIGNER_ENV, signer); |
| 73 | if let Some(node) = REEXEC_NODE_SESSION_ID.get() { |
| 74 | command.env("CELLD_NODE", node); |
| 75 | } |
| 76 | let error = command.exec(); |
| 77 | warn!( |
| 78 | event = "control_plane_restart_exec_failed", |
| 79 | trigger, |
| 80 | %error, |
| 81 | "could not re-exec celld for process reload; exiting for an external supervisor" |
| 82 | ); |
| 83 | std::process::exit(75); |
| 84 | } |
| 85 | |
| 86 | #[cfg(not(unix))] |
| 87 | fn restart_process(_trigger: &'static str) -> ! { |
| 88 | std::process::exit(75); |
| 89 | } |
| 90 | |
| 91 | fn restart_for_deployment() -> ! { |
| 92 | restart_process("deployment") |
| 93 | } |
| 94 | |
| 95 | static REEXEC_NODE_SESSION_ID: OnceLock<String> = OnceLock::new(); |
| 96 | |
| 97 | pub fn install_reexec_node_session_id(node: &str) -> anyhow::Result<()> { |
| 98 | REEXEC_NODE_SESSION_ID |
| 99 | .set(node.to_string()) |
| 100 | .map_err(|_| anyhow!("re-exec node-session identity is already installed")) |
| 101 | } |
| 102 | |
| 103 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 104 | pub enum ManagedRuntimeState { |
| 105 | Connected, |
| 106 | ControlPlaneUnavailable, |
| 107 | BucketUnavailable, |
| 108 | CredentialRevoked, |
| 109 | } |
| 110 | |
| 111 | impl ManagedRuntimeState { |
| 112 | fn as_str(self) -> &'static str { |
| 113 | match self { |
| 114 | Self::Connected => "connected", |
| 115 | Self::ControlPlaneUnavailable => "control_plane_unavailable", |
| 116 | Self::BucketUnavailable => "bucket_unavailable", |
| 117 | Self::CredentialRevoked => "credential_revoked", |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | static MANAGED_RUNTIME_STATE: OnceLock<Mutex<Option<ManagedRuntimeState>>> = OnceLock::new(); |
| 123 | |
| 124 | pub fn report_managed_runtime_state(state: ManagedRuntimeState) { |
| 125 | let mut current = MANAGED_RUNTIME_STATE |
| 126 | .get_or_init(|| Mutex::new(None)) |
| 127 | .lock() |
| 128 | .unwrap(); |
| 129 | if *current == Some(state) { |
| 130 | return; |
| 131 | } |
| 132 | *current = Some(state); |
| 133 | drop(current); |
| 134 | let managed_state = state.as_str(); |
| 135 | match state { |
| 136 | ManagedRuntimeState::Connected => info!( |
| 137 | event = "managed_runtime_state", |
| 138 | managed_state, "Managed Control Plane connected" |
| 139 | ), |
| 140 | ManagedRuntimeState::ControlPlaneUnavailable => info!( |
| 141 | event = "managed_runtime_state", |
| 142 | managed_state, "Managed Control Plane unavailable; bucket-backed serving continues" |
| 143 | ), |
| 144 | ManagedRuntimeState::BucketUnavailable => warn!( |
| 145 | event = "managed_runtime_state", |
| 146 | managed_state, "fleet bucket unavailable; serving cannot start" |
| 147 | ), |
| 148 | // Name the remedy: this condition can be cleared by a restart or an |
| 149 | // explicit credential refresh. |
| 150 | ManagedRuntimeState::CredentialRevoked => warn!( |
| 151 | event = "managed_runtime_state", |
| 152 | managed_state, |
| 153 | "managed storage credential was rejected; restart celld to fetch a \ |
| 154 | fresh one, or run `celld credentials refresh` if a rotation is pending" |
| 155 | ), |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | #[derive(Debug)] |
| 160 | struct ManagedControlCredentialRevoked; |
| 161 | |
| 162 | impl std::fmt::Display for ManagedControlCredentialRevoked { |
| 163 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 164 | formatter.write_str( |
| 165 | "Managed Control Plane credential was rejected or revoked.\n\ |
| 166 | Restart celld to fetch a fresh credential. If that does not help, \ |
| 167 | run `celld credentials refresh`, and `celld diagnose` to check \ |
| 168 | bucket access.", |
| 169 | ) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | impl std::error::Error for ManagedControlCredentialRevoked {} |
| 174 | |
| 175 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 176 | struct ConnectOptions { |
| 177 | control_url: String, |
| 178 | environment: String, |
| 179 | force: bool, |
| 180 | byo_storage: Option<ByoStorageConfig>, |
| 181 | } |
| 182 | |
| 183 | #[derive(Clone, Deserialize, Serialize)] |
| 184 | struct CloudConfig { |
| 185 | #[serde(default = "installation_schema_version")] |
| 186 | version: u32, |
| 187 | #[serde(alias = "instance_id")] |
| 188 | installation_id: String, |
| 189 | #[serde(alias = "instance_token")] |
| 190 | installation_token: Option<String>, |
| 191 | #[serde(default = "initial_credential_version")] |
| 192 | credential_version: u64, |
| 193 | fleet_id: Option<String>, |
| 194 | environment_id: Option<String>, |
| 195 | control_url: String, |
| 196 | environment: String, |
| 197 | #[serde(default)] |
| 198 | storage: Option<ManagedStorageConfig>, |
| 199 | #[serde(default)] |
| 200 | byo_storage: Option<ByoStorageConfig>, |
| 201 | #[serde(default)] |
| 202 | credential_handoff_id: Option<String>, |
| 203 | #[serde(default)] |
| 204 | previous_credential: Option<PreviousCredential>, |
| 205 | #[serde(default)] |
| 206 | pending_claim: Option<PendingClaim>, |
| 207 | } |
| 208 | |
| 209 | #[derive(Clone, Deserialize, Serialize)] |
| 210 | struct PreviousCredential { |
| 211 | installation_token: String, |
| 212 | credential_version: u64, |
| 213 | storage: ManagedStorageConfig, |
| 214 | } |
| 215 | |
| 216 | #[derive(Clone, Deserialize, Serialize)] |
| 217 | struct PendingClaim { |
| 218 | verification_uri_complete: String, |
| 219 | expires_at_ms: u64, |
| 220 | } |
| 221 | |
| 222 | #[derive(Clone, Deserialize, Serialize)] |
| 223 | pub struct ManagedStorageConfig { |
| 224 | pub bucket: String, |
| 225 | pub endpoint: String, |
| 226 | pub region: String, |
| 227 | pub access_key_id: String, |
| 228 | pub secret_access_key: String, |
| 229 | #[serde(default)] |
| 230 | pub session_token: Option<String>, |
| 231 | } |
| 232 | |
| 233 | #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] |
| 234 | pub struct ByoStorageConfig { |
| 235 | pub bucket: String, |
| 236 | #[serde(default)] |
| 237 | pub endpoint: Option<String>, |
| 238 | pub region: String, |
| 239 | } |
| 240 | |
| 241 | #[derive(Clone)] |
| 242 | pub enum InstallationStorageConfig { |
| 243 | Managed(ManagedStorageConfig), |
| 244 | Byo(ByoStorageConfig), |
| 245 | } |
| 246 | |
| 247 | #[derive(Serialize)] |
| 248 | struct CreateClaimRequest<'a> { |
| 249 | instance_id: &'a str, |
| 250 | instance_name: &'a str, |
| 251 | environment: &'a str, |
| 252 | version: &'static str, |
| 253 | platform: String, |
| 254 | storage_origin: &'static str, |
| 255 | #[serde(skip_serializing_if = "Option::is_none")] |
| 256 | bucket: Option<&'a str>, |
| 257 | #[serde(skip_serializing_if = "Option::is_none")] |
| 258 | endpoint: Option<&'a str>, |
| 259 | #[serde(skip_serializing_if = "Option::is_none")] |
| 260 | region: Option<&'a str>, |
| 261 | } |
| 262 | |
| 263 | #[derive(Deserialize)] |
| 264 | struct CreateClaimResponse { |
| 265 | device_code: String, |
| 266 | verification_uri_complete: String, |
| 267 | expires_in: u64, |
| 268 | interval: u64, |
| 269 | } |
| 270 | |
| 271 | #[derive(Serialize)] |
| 272 | struct PollClaimRequest<'a> { |
| 273 | device_code: &'a str, |
| 274 | } |
| 275 | |
| 276 | #[derive(Deserialize)] |
| 277 | struct PollClaimResponse { |
| 278 | status: String, |
| 279 | #[serde(default = "managed_storage_origin")] |
| 280 | storage_origin: String, |
| 281 | credential_handoff_id: Option<String>, |
| 282 | credential_version: Option<u64>, |
| 283 | instance_token: Option<String>, |
| 284 | fleet_id: Option<String>, |
| 285 | environment_id: Option<String>, |
| 286 | bucket: Option<String>, |
| 287 | endpoint: Option<String>, |
| 288 | region: Option<String>, |
| 289 | access_key_id: Option<String>, |
| 290 | secret_access_key: Option<String>, |
| 291 | session_token: Option<String>, |
| 292 | interval: Option<u64>, |
| 293 | } |
| 294 | |
| 295 | #[derive(Deserialize)] |
| 296 | struct CredentialRotationResponse { |
| 297 | status: String, |
| 298 | credential_handoff_id: String, |
| 299 | credential_version: u64, |
| 300 | instance_token: String, |
| 301 | bucket: String, |
| 302 | endpoint: String, |
| 303 | region: String, |
| 304 | access_key_id: String, |
| 305 | secret_access_key: String, |
| 306 | session_token: Option<String>, |
| 307 | } |
| 308 | |
| 309 | #[derive(Deserialize)] |
| 310 | struct AgentCommandEnvelope { |
| 311 | command: AgentCommand, |
| 312 | } |
| 313 | |
| 314 | #[derive(Deserialize)] |
| 315 | struct AgentCommand { |
| 316 | id: String, |
| 317 | #[serde(rename = "type")] |
| 318 | kind: String, |
| 319 | deployment: AgentDeployment, |
| 320 | } |
| 321 | |
| 322 | #[derive(Deserialize)] |
| 323 | struct AgentDeployment { |
| 324 | script_name: String, |
| 325 | version: String, |
| 326 | manifest: Manifest, |
| 327 | pointer: DeployPointer, |
| 328 | modules: Vec<AgentModule>, |
| 329 | #[serde(default)] |
| 330 | assets: Option<AgentAssets>, |
| 331 | } |
| 332 | |
| 333 | #[derive(Deserialize)] |
| 334 | struct AgentModule { |
| 335 | name: String, |
| 336 | sha256: String, |
| 337 | download_url: String, |
| 338 | } |
| 339 | |
| 340 | #[derive(Deserialize)] |
| 341 | struct AgentAssets { |
| 342 | index_download_url: String, |
| 343 | blob_download_base_url: String, |
| 344 | sha256: String, |
| 345 | file_count: u32, |
| 346 | total_bytes: u64, |
| 347 | } |
| 348 | |
| 349 | #[derive(Serialize)] |
| 350 | struct CompleteCommandRequest<'a> { |
| 351 | success: bool, |
| 352 | error: Option<&'a str>, |
| 353 | } |
| 354 | |
| 355 | struct AppliedDeployment { |
| 356 | id: String, |
| 357 | script_name: String, |
| 358 | } |
| 359 | |
| 360 | pub async fn handle_connect_command( |
| 361 | arguments: impl IntoIterator<Item = String>, |
| 362 | ) -> anyhow::Result<()> { |
| 363 | let mut options = options_from_env()?; |
| 364 | let mut args = arguments.into_iter(); |
| 365 | while let Some(argument) = args.next() { |
| 366 | match argument.as_str() { |
| 367 | "--env" => { |
| 368 | options.environment = args.next().context("--env requires a value")?; |
| 369 | } |
| 370 | "--control-url" => { |
| 371 | options.control_url = args.next().context("--control-url requires a value")?; |
| 372 | } |
| 373 | "--force" => options.force = true, |
| 374 | "--help" | "-h" => { |
| 375 | if let Some(argument) = args.next() { |
| 376 | return Err(anyhow!( |
| 377 | "unexpected argument after connect --help: {argument}" |
| 378 | )); |
| 379 | } |
| 380 | print_connect_help(); |
| 381 | return Ok(()); |
| 382 | } |
| 383 | _ => return Err(anyhow!("unknown connect option: {argument}")), |
| 384 | } |
| 385 | } |
| 386 | validate_environment(&options.environment)?; |
| 387 | connect(options, true).await |
| 388 | } |
| 389 | |
| 390 | /// `celld token` — print the fleet's deploy token and the exact commands to |
| 391 | /// use it. |
| 392 | /// |
| 393 | /// Wrangler expects deployment credentials in environment variables, so this |
| 394 | /// command exposes the connected fleet's short-lived token in a shell-friendly |
| 395 | /// form. |
| 396 | pub async fn handle_token_command( |
| 397 | arguments: impl IntoIterator<Item = String>, |
| 398 | ) -> anyhow::Result<()> { |
| 399 | let arguments = arguments.into_iter().collect::<Vec<_>>(); |
| 400 | if matches!(arguments.as_slice(), [a] if a == "--help" || a == "-h") { |
| 401 | println!( |
| 402 | "Print this fleet's deploy token, and how to deploy with it.\n\n\ |
| 403 | USAGE:\n celld token [--format shell]\n\n\ |
| 404 | OPTIONS:\n --format shell Print only shell exports, suitable for `eval`.\n" |
| 405 | ); |
| 406 | return Ok(()); |
| 407 | } |
| 408 | let shell_only = match arguments.as_slice() { |
| 409 | [] => false, |
| 410 | [format, value] if format == "--format" && value == "shell" => true, |
| 411 | _ => { |
| 412 | return Err(anyhow!( |
| 413 | "expected `celld token` or `celld token --format shell`; \ |
| 414 | run `celld token --help` for usage" |
| 415 | )) |
| 416 | } |
| 417 | }; |
| 418 | let path = config_path()?; |
| 419 | let contents = std::fs::read_to_string(&path).with_context(|| { |
| 420 | format!( |
| 421 | "read {}. This celld installation is not enrolled yet — run `celld` \ |
| 422 | and approve the link it prints.", |
| 423 | path.display() |
| 424 | ) |
| 425 | })?; |
| 426 | let config: CloudConfig = |
| 427 | serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?; |
| 428 | let token = config.installation_token.as_deref().context( |
| 429 | "this celld installation is not enrolled in the Managed Control Plane — \ |
| 430 | run `celld` and approve the link it prints", |
| 431 | )?; |
| 432 | let client = reqwest::Client::new(); |
| 433 | let response = client |
| 434 | .post(format!("{}/api/agent/deploy-token", config.control_url)) |
| 435 | .bearer_auth(token) |
| 436 | .send() |
| 437 | .await |
| 438 | .context("request a deploy token")?; |
| 439 | if !response.status().is_success() { |
| 440 | let status = response.status(); |
| 441 | let body = response.text().await.unwrap_or_default(); |
| 442 | return Err(anyhow!( |
| 443 | "could not get a deploy token ({status}): {body}\n\ |
| 444 | If this installation was disconnected, run `celld` to re-enrol." |
| 445 | )); |
| 446 | } |
| 447 | #[derive(serde::Deserialize)] |
| 448 | struct DeployTokenResponse { |
| 449 | token: String, |
| 450 | account_id: String, |
| 451 | api_base_url: String, |
| 452 | } |
| 453 | let issued: DeployTokenResponse = response.json().await.context("decode deploy token")?; |
| 454 | print!( |
| 455 | "{}", |
| 456 | render_deploy_token( |
| 457 | &issued.token, |
| 458 | &issued.account_id, |
| 459 | &issued.api_base_url, |
| 460 | shell_only, |
| 461 | ) |
| 462 | ); |
| 463 | Ok(()) |
| 464 | } |
| 465 | |
| 466 | fn render_deploy_token( |
| 467 | token: &str, |
| 468 | account_id: &str, |
| 469 | api_base_url: &str, |
| 470 | shell_only: bool, |
| 471 | ) -> String { |
| 472 | let exports = format!( |
| 473 | "export CLOUDFLARE_API_TOKEN={}\n\ |
| 474 | export CLOUDFLARE_ACCOUNT_ID={}\n\ |
| 475 | export CLOUDFLARE_API_BASE_URL={}\n", |
| 476 | shell_quote(token), |
| 477 | shell_quote(account_id), |
| 478 | shell_quote(api_base_url), |
| 479 | ); |
| 480 | if shell_only { |
| 481 | return exports; |
| 482 | } |
| 483 | // Say what to do next, not merely what happened. |
| 484 | format!( |
| 485 | "Deploy token for this fleet:\n\n {token}\n\n\ |
| 486 | Deploy your app with:\n\n{exports}npx wrangler@4 deploy\n" |
| 487 | ) |
| 488 | } |
| 489 | |
| 490 | fn shell_quote(value: &str) -> String { |
| 491 | format!("'{}'", value.replace('\'', "'\"'\"'")) |
| 492 | } |
| 493 | |
| 494 | pub async fn handle_credentials_command( |
| 495 | arguments: impl IntoIterator<Item = String>, |
| 496 | ) -> anyhow::Result<()> { |
| 497 | let arguments = arguments.into_iter().collect::<Vec<_>>(); |
| 498 | if matches!(arguments.as_slice(), [argument] if argument == "--help" || argument == "-h") { |
| 499 | print_credentials_help(); |
| 500 | return Ok(()); |
| 501 | } |
| 502 | if !matches!(arguments.as_slice(), [command] if command == "refresh") { |
| 503 | return Err(anyhow!( |
| 504 | "expected `celld credentials refresh`; run `celld credentials --help` for usage" |
| 505 | )); |
| 506 | } |
| 507 | refresh_credentials().await |
| 508 | } |
| 509 | |
| 510 | pub async fn handle_disconnect_command( |
| 511 | arguments: impl IntoIterator<Item = String>, |
| 512 | ) -> anyhow::Result<()> { |
| 513 | let arguments = arguments.into_iter().collect::<Vec<_>>(); |
| 514 | if matches!(arguments.as_slice(), [argument] if argument == "--help" || argument == "-h") { |
| 515 | print_disconnect_help(); |
| 516 | return Ok(()); |
| 517 | } |
| 518 | if !matches!(arguments.as_slice(), [confirmation] if confirmation == "--yes") { |
| 519 | return Err(anyhow!( |
| 520 | "disconnect revokes every process sharing this installation; rerun `celld disconnect --yes` to confirm" |
| 521 | )); |
| 522 | } |
| 523 | let path = config_path()?; |
| 524 | let client = reqwest::Client::builder() |
| 525 | .timeout(Duration::from_secs(15)) |
| 526 | .build()?; |
| 527 | let archive = disconnect_at_path(path, &client).await?; |
| 528 | println!( |
| 529 | "Disconnected this installation from the Managed Control Plane.\nArchived its revoked local record at {}.", |
| 530 | archive.display() |
| 531 | ); |
| 532 | Ok(()) |
| 533 | } |
| 534 | |
| 535 | async fn disconnect_at_path(path: PathBuf, client: &reqwest::Client) -> anyhow::Result<PathBuf> { |
| 536 | let _lock = acquire_enrollment_lock(&path).await?; |
| 537 | let contents = |
| 538 | std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?; |
| 539 | let config: CloudConfig = |
| 540 | serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?; |
| 541 | let token = config |
| 542 | .installation_token |
| 543 | .as_deref() |
| 544 | .context("this celld installation is not enrolled in the Managed Control Plane")?; |
| 545 | let response = client |
| 546 | .post(format!( |
| 547 | "{}/api/agent/credentials/revoke", |
| 548 | config.control_url |
| 549 | )) |
| 550 | .bearer_auth(token) |
| 551 | .json(&serde_json::json!({ "installation_id": config.installation_id })) |
| 552 | .send() |
| 553 | .await |
| 554 | .context("revoke managed installation")?; |
| 555 | if !response.status().is_success() { |
| 556 | return Err(anyhow!( |
| 557 | "managed installation revocation returned {}", |
| 558 | response.status() |
| 559 | )); |
| 560 | } |
| 561 | |
| 562 | // Keep a recoverable, permission-preserving record rather than deleting |
| 563 | // secrets in place. The provider credential is already revoked, and bare |
| 564 | // `celld` will create a fresh installation record on its next start. |
| 565 | let file_name = path |
| 566 | .file_name() |
| 567 | .and_then(|value| value.to_str()) |
| 568 | .context("managed installation path has no UTF-8 file name")?; |
| 569 | let archive = path.with_file_name(format!("{file_name}.disconnected-{}", current_time_ms())); |
| 570 | std::fs::rename(&path, &archive).with_context(|| { |
| 571 | format!( |
| 572 | "archive revoked installation record as {}", |
| 573 | archive.display() |
| 574 | ) |
| 575 | })?; |
| 576 | Ok(archive) |
| 577 | } |
| 578 | |
| 579 | async fn refresh_credentials() -> anyhow::Result<()> { |
| 580 | let path = config_path()?; |
| 581 | let client = reqwest::Client::builder() |
| 582 | .timeout(Duration::from_secs(15)) |
| 583 | .build()?; |
| 584 | refresh_credentials_at_path(path, &client).await |
| 585 | } |
| 586 | |
| 587 | async fn refresh_credentials_at_path( |
| 588 | path: PathBuf, |
| 589 | client: &reqwest::Client, |
| 590 | ) -> anyhow::Result<()> { |
| 591 | let _lock = acquire_enrollment_lock(&path).await?; |
| 592 | let contents = |
| 593 | std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?; |
| 594 | let mut config: CloudConfig = |
| 595 | serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?; |
| 596 | let token = config |
| 597 | .installation_token |
| 598 | .as_deref() |
| 599 | .context("this celld installation is not enrolled in the Managed Control Plane")?; |
| 600 | let current_storage = config |
| 601 | .storage |
| 602 | .as_ref() |
| 603 | .context("managed installation record has no storage credentials")?; |
| 604 | |
| 605 | if let Some(handoff_id) = config.credential_handoff_id.clone() { |
| 606 | acknowledge_credential_handoff(client, &config, &handoff_id) |
| 607 | .await |
| 608 | .context("finish previously saved credential refresh")?; |
| 609 | config.credential_handoff_id = None; |
| 610 | config.previous_credential = None; |
| 611 | save_config(&path, &config)?; |
| 612 | println!( |
| 613 | "Managed credential refresh completed (version {}).", |
| 614 | config.credential_version |
| 615 | ); |
| 616 | return Ok(()); |
| 617 | } |
| 618 | |
| 619 | let response = client |
| 620 | .post(format!("{}/api/agent/credentials/next", config.control_url)) |
| 621 | .bearer_auth(token) |
| 622 | .json(&serde_json::json!({})) |
| 623 | .send() |
| 624 | .await |
| 625 | .context("request staged managed credential")?; |
| 626 | if response.status() == reqwest::StatusCode::NO_CONTENT { |
| 627 | println!("No managed credential rotation is pending."); |
| 628 | return Ok(()); |
| 629 | } |
| 630 | if response.status() == reqwest::StatusCode::UNAUTHORIZED { |
| 631 | return Err(anyhow!( |
| 632 | "this installation credential is revoked; enroll a new installation" |
| 633 | )); |
| 634 | } |
| 635 | if !response.status().is_success() { |
| 636 | return Err(anyhow!( |
| 637 | "credential refresh endpoint returned {}", |
| 638 | response.status() |
| 639 | )); |
| 640 | } |
| 641 | let replacement: CredentialRotationResponse = response |
| 642 | .json() |
| 643 | .await |
| 644 | .context("decode staged managed credential")?; |
| 645 | validate_credential_rotation(&replacement, &config, current_storage)?; |
| 646 | |
| 647 | config.previous_credential = Some(PreviousCredential { |
| 648 | installation_token: token.to_string(), |
| 649 | credential_version: config.credential_version, |
| 650 | storage: current_storage.clone(), |
| 651 | }); |
| 652 | config.installation_token = Some(replacement.instance_token); |
| 653 | config.credential_version = replacement.credential_version; |
| 654 | config.storage = Some(ManagedStorageConfig { |
| 655 | bucket: replacement.bucket, |
| 656 | endpoint: replacement.endpoint, |
| 657 | region: replacement.region, |
| 658 | access_key_id: replacement.access_key_id, |
| 659 | secret_access_key: replacement.secret_access_key, |
| 660 | session_token: replacement.session_token, |
| 661 | }); |
| 662 | config.credential_handoff_id = Some(replacement.credential_handoff_id.clone()); |
| 663 | |
| 664 | // The replacement is persisted before acknowledgement. If this process is |
| 665 | // killed after the rename, the marker makes the acknowledgement retryable. |
| 666 | // The managed control plane keeps both token hashes valid until this |
| 667 | // acknowledgement succeeds. |
| 668 | save_config(&path, &config)?; |
| 669 | acknowledge_credential_handoff(client, &config, &replacement.credential_handoff_id) |
| 670 | .await |
| 671 | .context( |
| 672 | "replacement credential is saved, but acknowledgement is pending; rerun `celld credentials refresh`", |
| 673 | )?; |
| 674 | config.credential_handoff_id = None; |
| 675 | config.previous_credential = None; |
| 676 | save_config(&path, &config)?; |
| 677 | println!( |
| 678 | "Managed credential refresh completed (version {}).", |
| 679 | config.credential_version |
| 680 | ); |
| 681 | Ok(()) |
| 682 | } |
| 683 | |
| 684 | fn validate_credential_rotation( |
| 685 | replacement: &CredentialRotationResponse, |
| 686 | config: &CloudConfig, |
| 687 | current: &ManagedStorageConfig, |
| 688 | ) -> anyhow::Result<()> { |
| 689 | if replacement.status != "rotation_pending" { |
| 690 | return Err(anyhow!( |
| 691 | "unexpected credential refresh status: {}", |
| 692 | replacement.status |
| 693 | )); |
| 694 | } |
| 695 | if replacement.credential_version != config.credential_version.saturating_add(1) { |
| 696 | return Err(anyhow!( |
| 697 | "credential refresh version is not the next installation version" |
| 698 | )); |
| 699 | } |
| 700 | if replacement.bucket != current.bucket |
| 701 | || replacement.endpoint != current.endpoint |
| 702 | || replacement.region != current.region |
| 703 | { |
| 704 | return Err(anyhow!( |
| 705 | "credential refresh attempted to change the installation storage target" |
| 706 | )); |
| 707 | } |
| 708 | for (name, value) in [ |
| 709 | ( |
| 710 | "credential handoff", |
| 711 | replacement.credential_handoff_id.as_str(), |
| 712 | ), |
| 713 | ("installation token", replacement.instance_token.as_str()), |
| 714 | ("storage access key", replacement.access_key_id.as_str()), |
| 715 | ("storage secret key", replacement.secret_access_key.as_str()), |
| 716 | ] { |
| 717 | if value.is_empty() || value.len() > 500 { |
| 718 | return Err(anyhow!("credential refresh returned an invalid {name}")); |
| 719 | } |
| 720 | } |
| 721 | Ok(()) |
| 722 | } |
| 723 | |
| 724 | pub async fn connect_on_startup_with_storage( |
| 725 | byo_storage: Option<ByoStorageConfig>, |
| 726 | ) -> anyhow::Result<()> { |
| 727 | let mut options = options_from_env()?; |
| 728 | options.byo_storage = byo_storage; |
| 729 | validate_environment(&options.environment)?; |
| 730 | connect(options, true).await |
| 731 | } |
| 732 | |
| 733 | pub fn installation_storage() -> anyhow::Result<InstallationStorageConfig> { |
| 734 | installation_storage_with_version().map(|(storage, _)| storage) |
| 735 | } |
| 736 | |
| 737 | pub fn installation_storage_with_version() -> anyhow::Result<(InstallationStorageConfig, u64)> { |
| 738 | let config = connected_config()?.context("managed installation is not connected")?; |
| 739 | let credential_version = config.credential_version; |
| 740 | let storage = match (config.storage, config.byo_storage) { |
| 741 | (Some(storage), None) => InstallationStorageConfig::Managed(storage), |
| 742 | (None, Some(storage)) => InstallationStorageConfig::Byo(storage), |
| 743 | (None, None) => { |
| 744 | return Err(anyhow!("managed installation record has no storage target")); |
| 745 | } |
| 746 | (Some(_), Some(_)) => { |
| 747 | return Err(anyhow!( |
| 748 | "managed installation record contains conflicting storage targets" |
| 749 | )); |
| 750 | } |
| 751 | }; |
| 752 | Ok((storage, credential_version)) |
| 753 | } |
| 754 | |
| 755 | pub type PresenceSnapshotFuture = Pin<Box<dyn Future<Output = Option<PresenceSnapshot>> + Send>>; |
| 756 | pub type PresenceSnapshotSource = Arc<dyn Fn() -> PresenceSnapshotFuture + Send + Sync>; |
| 757 | |
| 758 | /// Production WebSocket transport around a read-only projection supplied by |
| 759 | /// celld-logic. The control-plane adapter cannot mutate lifecycle state or |
| 760 | /// maintain its own resident inventory. |
| 761 | pub struct PresenceRuntime { |
| 762 | pub s3: Bucket, |
| 763 | pub replication: Option<crate::runtime::Replication>, |
| 764 | pub node_session_id: String, |
| 765 | pub advertise: String, |
| 766 | pub listen: String, |
| 767 | /// Credential version used to construct S3, lease, replication, explorer, |
| 768 | /// and deployment adapters. This intentionally comes from the same config |
| 769 | /// snapshot as those credentials, not from a later presence-agent read. |
| 770 | pub credential_version: u64, |
| 771 | pub snapshot: PresenceSnapshotSource, |
| 772 | } |
| 773 | |
| 774 | pub fn start_presence_agent(runtime: PresenceRuntime) -> bool { |
| 775 | let config = match connected_config() { |
| 776 | Ok(Some(config)) => config, |
| 777 | Ok(None) => return false, |
| 778 | Err(error) => { |
| 779 | warn!(event = "control_plane_presence_configuration_error", %error); |
| 780 | return false; |
| 781 | } |
| 782 | }; |
| 783 | let hostname = machine_hostname(); |
| 784 | tokio::spawn(async move { |
| 785 | let mut consecutive_failures = 0_u32; |
| 786 | loop { |
| 787 | let started = Instant::now(); |
| 788 | let result = tokio::select! { |
| 789 | result = presence_session(&config, &runtime, &hostname) => result, |
| 790 | credential_version = wait_for_credential_rotation(runtime.credential_version) => { |
| 791 | restart_for_credential_rotation(runtime.credential_version, credential_version); |
| 792 | } |
| 793 | }; |
| 794 | if started.elapsed() >= Duration::from_secs(30) { |
| 795 | consecutive_failures = 0; |
| 796 | } |
| 797 | match result { |
| 798 | Ok(()) => {} |
| 799 | Err(error) if consecutive_failures == 0 => { |
| 800 | report_managed_runtime_state( |
| 801 | if error.is::<ManagedControlCredentialRevoked>() { |
| 802 | ManagedRuntimeState::CredentialRevoked |
| 803 | } else { |
| 804 | ManagedRuntimeState::ControlPlaneUnavailable |
| 805 | }, |
| 806 | ); |
| 807 | info!( |
| 808 | event = "control_plane_presence_unavailable", |
| 809 | %error, |
| 810 | "Managed Control Plane presence unavailable; bucket-backed serving continues" |
| 811 | ); |
| 812 | } |
| 813 | Err(_) => {} |
| 814 | } |
| 815 | consecutive_failures = consecutive_failures.saturating_add(1); |
| 816 | let exponent = consecutive_failures.saturating_sub(1).min(5); |
| 817 | let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60); |
| 818 | let jitter_ms = (rand::random::<u16>() as u64) % 1000; |
| 819 | tokio::select! { |
| 820 | _ = tokio::time::sleep(Duration::from_millis(seconds * 1000 + jitter_ms)) => {} |
| 821 | credential_version = wait_for_credential_rotation(runtime.credential_version) => { |
| 822 | restart_for_credential_rotation(runtime.credential_version, credential_version); |
| 823 | } |
| 824 | } |
| 825 | } |
| 826 | }); |
| 827 | true |
| 828 | } |
| 829 | |
| 830 | fn restart_for_credential_rotation(previous_version: u64, credential_version: u64) -> ! { |
| 831 | info!( |
| 832 | event = "control_plane_restart_for_credentials", |
| 833 | previous_credential_version = previous_version, |
| 834 | credential_version, |
| 835 | "managed credential changed; restarting celld to rebuild every credentialed adapter" |
| 836 | ); |
| 837 | restart_process("credential_rotation") |
| 838 | } |
| 839 | |
| 840 | /// Watch the durable installation record for the lifetime of the advisory |
| 841 | /// presence agent. `celld credentials refresh` persists the replacement before |
| 842 | /// acknowledging its handoff; seeing that version is therefore enough to |
| 843 | /// rebuild the complete adapter graph. Replacing only one S3 client here would |
| 844 | /// leave the lease pool, replication, explorer, or deploy agent on revoked |
| 845 | /// credentials. |
| 846 | async fn wait_for_credential_rotation(current_version: u64) -> u64 { |
| 847 | let mut tick = tokio::time::interval(Duration::from_secs(1)); |
| 848 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 849 | let mut unavailable = false; |
| 850 | loop { |
| 851 | tick.tick().await; |
| 852 | match connected_config() { |
| 853 | Ok(Some(config)) => { |
| 854 | if unavailable { |
| 855 | info!( |
| 856 | event = "control_plane_credential_watch_recovered", |
| 857 | "managed installation record is readable again" |
| 858 | ); |
| 859 | unavailable = false; |
| 860 | } |
| 861 | if config.credential_version != current_version { |
| 862 | return config.credential_version; |
| 863 | } |
| 864 | } |
| 865 | Ok(None) => { |
| 866 | if !unavailable { |
| 867 | warn!( |
| 868 | event = "control_plane_credential_watch_unavailable", |
| 869 | reason = "installation_not_connected", |
| 870 | "cannot observe managed credential rotation" |
| 871 | ); |
| 872 | unavailable = true; |
| 873 | } |
| 874 | } |
| 875 | Err(error) => { |
| 876 | if !unavailable { |
| 877 | warn!( |
| 878 | event = "control_plane_credential_watch_unavailable", |
| 879 | reason = "installation_read_failed", |
| 880 | %error, |
| 881 | "cannot observe managed credential rotation" |
| 882 | ); |
| 883 | unavailable = true; |
| 884 | } |
| 885 | } |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | async fn presence_session( |
| 891 | config: &CloudConfig, |
| 892 | runtime: &PresenceRuntime, |
| 893 | hostname: &str, |
| 894 | ) -> anyhow::Result<()> { |
| 895 | let (url, headers) = presence_request( |
| 896 | config, |
| 897 | &runtime.node_session_id, |
| 898 | &runtime.advertise, |
| 899 | &runtime.listen, |
| 900 | hostname, |
| 901 | )?; |
| 902 | let mut socket = match crate::ws_client::connect(&url, headers).await { |
| 903 | Ok(connection) => FragmentCollector::new(connection.socket), |
| 904 | Err(crate::ws_client::Error::Declined(declined)) |
| 905 | if matches!(declined.status.as_u16(), 401 | 403) => |
| 906 | { |
| 907 | return Err(ManagedControlCredentialRevoked.into()); |
| 908 | } |
| 909 | Err(error) => { |
| 910 | return Err(anyhow!("{error}")).context("connect Managed Control Plane presence"); |
| 911 | } |
| 912 | }; |
| 913 | report_managed_runtime_state(ManagedRuntimeState::Connected); |
| 914 | info!( |
| 915 | event = "control_plane_presence_connected", |
| 916 | node_session_id = %runtime.node_session_id, |
| 917 | advertise = %runtime.advertise, |
| 918 | "node session connected to the Managed Control Plane" |
| 919 | ); |
| 920 | let heartbeat_period = std::env::var("CELLD_PRESENCE_HEARTBEAT_MS") |
| 921 | .ok() |
| 922 | .and_then(|value| value.parse::<u64>().ok()) |
| 923 | .filter(|value| (50..=30_000).contains(value)) |
| 924 | .map(Duration::from_millis) |
| 925 | .unwrap_or(Duration::from_secs(30)); |
| 926 | let mut heartbeat = tokio::time::interval(heartbeat_period); |
| 927 | heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 928 | let shadow_presence = std::env::var("CELLD_PRESENCE_SHADOW").as_deref() == Ok("on"); |
| 929 | loop { |
| 930 | tokio::select! { |
| 931 | _ = heartbeat.tick() => { |
| 932 | let snapshot = (runtime.snapshot)() |
| 933 | .await |
| 934 | .context("celld core stopped before presence snapshot")?; |
| 935 | let lease_shadow = if shadow_presence { |
| 936 | Some(lease_shadow_observation(runtime).await) |
| 937 | } else { |
| 938 | None |
| 939 | }; |
| 940 | let mut cells = snapshot |
| 941 | .cells |
| 942 | .iter() |
| 943 | .filter(|cell| { |
| 944 | !cell.id.is_empty() |
| 945 | && cell.id.len() <= MAX_PRESENCE_CELL_ID_BYTES |
| 946 | && !cell.id.chars().any(char::is_control) |
| 947 | }) |
| 948 | .map(|cell| serde_json::json!({ |
| 949 | "id": cell.id, |
| 950 | "epoch": cell.epoch, |
| 951 | })) |
| 952 | .collect::<Vec<_>>(); |
| 953 | let cells_truncated = cells.len() < snapshot.cells.len() |
| 954 | || cells.len() > MAX_PRESENCE_CELLS; |
| 955 | cells.truncate(MAX_PRESENCE_CELLS); |
| 956 | let mut message = serde_json::json!({ |
| 957 | "serving": snapshot.serving, |
| 958 | "owned_cells": snapshot.owned_cells(), |
| 959 | "cells": cells, |
| 960 | "cells_truncated": cells_truncated, |
| 961 | "activity": { |
| 962 | "acquired": snapshot.activity.acquired, |
| 963 | "proxied": snapshot.activity.proxied, |
| 964 | "expired_owner_leases": snapshot.activity.expired_owner_leases, |
| 965 | "restored": snapshot.activity.restored, |
| 966 | "advanced_epochs": snapshot.activity.advanced_epochs, |
| 967 | }, |
| 968 | }); |
| 969 | if let Some(observation) = lease_shadow { |
| 970 | message["lease_shadow"] = observation; |
| 971 | } |
| 972 | if !snapshot.lazy_lease_shadow.decisions.is_empty() |
| 973 | || snapshot.lazy_lease_shadow.dropped > 0 |
| 974 | { |
| 975 | message["lazy_lease_shadow"] = |
| 976 | lazy_lease_shadow_json(&snapshot.lazy_lease_shadow); |
| 977 | } |
| 978 | socket |
| 979 | .write_frame(Frame::text(message.to_string().into_bytes().into())) |
| 980 | .await?; |
| 981 | } |
| 982 | // Ping and Close are answered by the collector's auto-pong and |
| 983 | // auto-close; only Text carries anything to act on. |
| 984 | frame = socket.read_frame() => { |
| 985 | match frame { |
| 986 | Ok(frame) if frame.opcode == OpCode::Text => { |
| 987 | let text = String::from_utf8_lossy(&frame.payload); |
| 988 | let message = serde_json::from_str::<serde_json::Value>(&text).ok(); |
| 989 | let message_type = message.as_ref() |
| 990 | .and_then(|value| value.get("type")) |
| 991 | .and_then(|value| value.as_str()) |
| 992 | .map(str::to_string); |
| 993 | match message_type.as_deref() { |
| 994 | Some("explorer_request") => { |
| 995 | let response = handle_explorer_request( |
| 996 | message.as_ref().unwrap(), |
| 997 | runtime, |
| 998 | ).await; |
| 999 | socket |
| 1000 | .write_frame(Frame::text( |
| 1001 | response.to_string().into_bytes().into(), |
| 1002 | )) |
| 1003 | .await?; |
| 1004 | } |
| 1005 | Some("deployment") => { |
| 1006 | let client = reqwest::Client::builder() |
| 1007 | .timeout(Duration::from_secs(30)) |
| 1008 | .build()?; |
| 1009 | if poll_and_apply( |
| 1010 | &client, |
| 1011 | config, |
| 1012 | &runtime.s3, |
| 1013 | ).await?.is_some() && restart_on_deployment_enabled() { |
| 1014 | restart_for_deployment(); |
| 1015 | } |
| 1016 | } |
| 1017 | Some("deployment_current") if restart_on_deployment_enabled() => { |
| 1018 | restart_for_deployment(); |
| 1019 | } |
| 1020 | _ => {} |
| 1021 | } |
| 1022 | } |
| 1023 | Ok(frame) if frame.opcode == OpCode::Close => { |
| 1024 | return Err(anyhow!("Managed Control Plane closed presence")); |
| 1025 | } |
| 1026 | Ok(_) => {} |
| 1027 | Err(error) => return Err(anyhow!("{error}")) |
| 1028 | .context("read Managed Control Plane presence"), |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | fn lazy_lease_shadow_json(batch: &celld_logic::LeaseLifecycleShadowBatch) -> serde_json::Value { |
| 1036 | let decisions = batch |
| 1037 | .decisions |
| 1038 | .iter() |
| 1039 | .map(|decision| { |
| 1040 | let snapshot = &decision.snapshot; |
| 1041 | let mode = match snapshot.mode { |
| 1042 | celld_logic::NodeLeaseMode::Continuous => "continuous", |
| 1043 | celld_logic::NodeLeaseMode::Shadow => "shadow", |
| 1044 | celld_logic::NodeLeaseMode::Lazy => "lazy", |
| 1045 | }; |
| 1046 | let authority_action = match decision.expected.authority_action { |
| 1047 | celld_logic::NodeLeaseAuthorityAction::Hold => "hold", |
| 1048 | celld_logic::NodeLeaseAuthorityAction::Renew => "renew", |
| 1049 | }; |
| 1050 | serde_json::json!({ |
| 1051 | "sequence": decision.sequence, |
| 1052 | "observed_at_ms": decision.observed_at_ms, |
| 1053 | "snapshot": { |
| 1054 | "mode": mode, |
| 1055 | "active_cells": snapshot.active_cells, |
| 1056 | "serving_cells": snapshot.serving_cells, |
| 1057 | "idle_ms": snapshot.idle_ms, |
| 1058 | "linger_ms": snapshot.linger_ms, |
| 1059 | "lease_active": snapshot.lease_active, |
| 1060 | "elapsed_since_ok_ms": snapshot.elapsed_since_ok_ms, |
| 1061 | "elapsed_since_renew_ms": snapshot.elapsed_since_renew_ms, |
| 1062 | "ttl_ms": snapshot.ttl_ms, |
| 1063 | "shadow_release_reported": snapshot.shadow_release_reported, |
| 1064 | }, |
| 1065 | "expected": { |
| 1066 | "shadow_release": decision.expected.shadow_release, |
| 1067 | "authority_action": authority_action, |
| 1068 | }, |
| 1069 | }) |
| 1070 | }) |
| 1071 | .collect::<Vec<_>>(); |
| 1072 | serde_json::json!({ |
| 1073 | "dropped": batch.dropped, |
| 1074 | "decisions": decisions, |
| 1075 | }) |
| 1076 | } |
| 1077 | |
| 1078 | /// Independently observe bucket truth for rollout comparison. This is an |
| 1079 | /// off-by-default management diagnostic: it never feeds the lease record back |
| 1080 | /// into the core or changes whether the node serves. |
| 1081 | async fn lease_shadow_observation(runtime: &PresenceRuntime) -> serde_json::Value { |
| 1082 | let checked_at_ms = crate::ownership_store::now_ms(); |
| 1083 | let ownership = crate::ownership_store::S3Ownership::new( |
| 1084 | runtime.s3.clone(), |
| 1085 | runtime.node_session_id.clone(), |
| 1086 | ); |
| 1087 | match ownership.read_node_lease(&runtime.node_session_id).await { |
| 1088 | Ok(Some(record)) => serde_json::json!({ |
| 1089 | "bucket_status": if record.expires_ms > checked_at_ms { "live" } else { "expired" }, |
| 1090 | "node": record.node, |
| 1091 | "advertise": record.addr, |
| 1092 | "expires_ms": record.expires_ms, |
| 1093 | "checked_at_ms": checked_at_ms, |
| 1094 | }), |
| 1095 | Ok(None) => serde_json::json!({ |
| 1096 | "bucket_status": "missing", |
| 1097 | "node": null, |
| 1098 | "advertise": null, |
| 1099 | "expires_ms": null, |
| 1100 | "checked_at_ms": checked_at_ms, |
| 1101 | }), |
| 1102 | Err(_) => serde_json::json!({ |
| 1103 | "bucket_status": "unavailable", |
| 1104 | "node": null, |
| 1105 | "advertise": null, |
| 1106 | "expires_ms": null, |
| 1107 | "checked_at_ms": checked_at_ms, |
| 1108 | }), |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | async fn handle_explorer_request( |
| 1113 | message: &serde_json::Value, |
| 1114 | runtime: &PresenceRuntime, |
| 1115 | ) -> serde_json::Value { |
| 1116 | let request_id = message |
| 1117 | .get("request_id") |
| 1118 | .and_then(|value| value.as_str()) |
| 1119 | .filter(|value| { |
| 1120 | !value.is_empty() |
| 1121 | && value.len() <= 64 |
| 1122 | && value |
| 1123 | .bytes() |
| 1124 | .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') |
| 1125 | }) |
| 1126 | .unwrap_or(""); |
| 1127 | let operation = message.get("operation").and_then(|value| value.as_str()); |
| 1128 | let result = match operation { |
| 1129 | Some("list_cells") => { |
| 1130 | let cursor = match message.get("cursor") { |
| 1131 | None | Some(serde_json::Value::Null) => None, |
| 1132 | Some(serde_json::Value::String(cursor)) if cursor.len() <= 2_048 => { |
| 1133 | Some(cursor.as_str()) |
| 1134 | } |
| 1135 | _ => return explorer_error(request_id, "invalid_request"), |
| 1136 | }; |
| 1137 | list_durable_cells(&runtime.s3, cursor).await |
| 1138 | } |
| 1139 | Some("inspect_cell") => { |
| 1140 | let Some(cell) = message |
| 1141 | .get("cell_id") |
| 1142 | .and_then(|value| value.as_str()) |
| 1143 | .filter(|cell| valid_explorer_cell_id(cell)) |
| 1144 | else { |
| 1145 | return explorer_error(request_id, "invalid_request"); |
| 1146 | }; |
| 1147 | let table = match message.get("table") { |
| 1148 | None | Some(serde_json::Value::Null) => None, |
| 1149 | Some(serde_json::Value::String(table)) |
| 1150 | if !table.is_empty() && table.len() <= 200 => |
| 1151 | { |
| 1152 | Some(table.clone()) |
| 1153 | } |
| 1154 | _ => return explorer_error(request_id, "invalid_request"), |
| 1155 | }; |
| 1156 | let Some(replication) = runtime.replication.clone() else { |
| 1157 | return explorer_error(request_id, "snapshot_not_found"); |
| 1158 | }; |
| 1159 | let Some(snapshot) = (runtime.snapshot)().await else { |
| 1160 | return explorer_error(request_id, "node_transport_unavailable"); |
| 1161 | }; |
| 1162 | let active_epoch = snapshot |
| 1163 | .cells |
| 1164 | .iter() |
| 1165 | .find(|candidate| candidate.id == cell) |
| 1166 | .map(|candidate| candidate.epoch); |
| 1167 | if let Some(epoch) = active_epoch { |
| 1168 | let cell = cell.to_string(); |
| 1169 | match tokio::task::spawn_blocking(move || { |
| 1170 | let Some(snapshot) = replication.snapshot_active(&cell, epoch)? else { |
| 1171 | return Ok(None); |
| 1172 | }; |
| 1173 | inspect_snapshot(snapshot, &cell, table.as_deref(), "active").map(Some) |
| 1174 | }) |
| 1175 | .await |
| 1176 | { |
| 1177 | Ok(Ok(Some(result))) => Ok(result), |
| 1178 | Ok(Ok(None)) => { |
| 1179 | return explorer_error(request_id, "active_snapshot_unavailable"); |
| 1180 | } |
| 1181 | Ok(Err(error)) => Err(error.context("inspect active cell snapshot")), |
| 1182 | Err(error) => Err(anyhow!("active inspection task failed: {error}")), |
| 1183 | } |
| 1184 | } else { |
| 1185 | match replication.restore_snapshot(cell).await { |
| 1186 | Ok(Some(snapshot)) => { |
| 1187 | let cell = cell.to_string(); |
| 1188 | match tokio::task::spawn_blocking(move || { |
| 1189 | inspect_snapshot(snapshot, &cell, table.as_deref(), "replicated") |
| 1190 | }) |
| 1191 | .await |
| 1192 | { |
| 1193 | Ok(result) => result, |
| 1194 | Err(error) => Err(anyhow!("inspection task failed: {error}")), |
| 1195 | } |
| 1196 | } |
| 1197 | Ok(None) => return explorer_error(request_id, "snapshot_not_found"), |
| 1198 | Err(error) => Err(error.context("restore replicated snapshot")), |
| 1199 | } |
| 1200 | } |
| 1201 | } |
| 1202 | _ => return explorer_error(request_id, "invalid_request"), |
| 1203 | }; |
| 1204 | match result { |
| 1205 | Ok(result) => serde_json::json!({ |
| 1206 | "type": "explorer_response", |
| 1207 | "request_id": request_id, |
| 1208 | "ok": true, |
| 1209 | "result": result, |
| 1210 | }), |
| 1211 | Err(error) => { |
| 1212 | let stable_error = if error |
| 1213 | .chain() |
| 1214 | .any(|cause| cause.to_string() == "table_not_found") |
| 1215 | { |
| 1216 | "table_not_found" |
| 1217 | } else if error |
| 1218 | .chain() |
| 1219 | .any(|cause| cause.to_string() == "table_not_previewable") |
| 1220 | { |
| 1221 | "table_not_previewable" |
| 1222 | } else { |
| 1223 | "inspection_failed" |
| 1224 | }; |
| 1225 | warn!( |
| 1226 | event = "control_plane_explorer_request_failed", |
| 1227 | request_id, |
| 1228 | %error, |
| 1229 | "read-only cell inspection failed" |
| 1230 | ); |
| 1231 | explorer_error(request_id, stable_error) |
| 1232 | } |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | fn explorer_error(request_id: &str, error: &str) -> serde_json::Value { |
| 1237 | serde_json::json!({ |
| 1238 | "type": "explorer_response", |
| 1239 | "request_id": request_id, |
| 1240 | "ok": false, |
| 1241 | "error": error, |
| 1242 | }) |
| 1243 | } |
| 1244 | |
| 1245 | fn valid_explorer_cell_id(cell: &str) -> bool { |
| 1246 | !cell.is_empty() |
| 1247 | && cell.len() <= MAX_PRESENCE_CELL_ID_BYTES |
| 1248 | && !cell.contains('/') |
| 1249 | && !cell.contains('\\') |
| 1250 | && !cell.contains('?') |
| 1251 | && !cell.contains('#') |
| 1252 | && !cell.contains("..") |
| 1253 | && cell.bytes().all(|byte| byte.is_ascii_graphic()) |
| 1254 | } |
| 1255 | |
| 1256 | async fn list_durable_cells( |
| 1257 | bucket: &Bucket, |
| 1258 | cursor: Option<&str>, |
| 1259 | ) -> anyhow::Result<serde_json::Value> { |
| 1260 | // object_store exposes no server-side cursor, so paging is client-side |
| 1261 | // over the full delimiter listing (bounded by the fleet's cell count). |
| 1262 | let mut cells = bucket |
| 1263 | .common_prefixes("cells/") |
| 1264 | .await? |
| 1265 | .into_iter() |
| 1266 | .filter_map(|prefix| prefix.strip_prefix("cells/").map(str::to_string)) |
| 1267 | .filter(|cell| valid_explorer_cell_id(cell)) |
| 1268 | .collect::<Vec<_>>(); |
| 1269 | cells.sort(); |
| 1270 | if let Some(cursor) = cursor { |
| 1271 | cells.retain(|cell| cell.as_str() > cursor); |
| 1272 | } |
| 1273 | let mut next_cursor = None; |
| 1274 | if cells.len() > MAX_EXPLORER_CELL_PAGE { |
| 1275 | cells.truncate(MAX_EXPLORER_CELL_PAGE); |
| 1276 | next_cursor = cells.last().cloned(); |
| 1277 | } |
| 1278 | Ok(serde_json::json!({ |
| 1279 | "cells": cells, |
| 1280 | "next_cursor": next_cursor, |
| 1281 | })) |
| 1282 | } |
| 1283 | |
| 1284 | fn inspect_snapshot( |
| 1285 | snapshot: crate::replication::RestoredSnapshot, |
| 1286 | cell: &str, |
| 1287 | selected_table: Option<&str>, |
| 1288 | source: &str, |
| 1289 | ) -> anyhow::Result<serde_json::Value> { |
| 1290 | let connection = Connection::open_with_flags( |
| 1291 | snapshot.path(), |
| 1292 | OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, |
| 1293 | )?; |
| 1294 | let mut schema = connection.prepare( |
| 1295 | "SELECT name, type, sql |
| 1296 | FROM sqlite_schema |
| 1297 | WHERE type IN ('table', 'view') |
| 1298 | AND name NOT LIKE 'sqlite_%' |
| 1299 | ORDER BY name |
| 1300 | LIMIT ?1", |
| 1301 | )?; |
| 1302 | let mut rows = schema.query([i64::try_from(MAX_EXPLORER_TABLES + 1)?])?; |
| 1303 | let mut tables = Vec::new(); |
| 1304 | let mut schema_bytes = 0_usize; |
| 1305 | let mut tables_truncated = false; |
| 1306 | while let Some(row) = rows.next()? { |
| 1307 | if tables.len() >= MAX_EXPLORER_TABLES { |
| 1308 | tables_truncated = true; |
| 1309 | break; |
| 1310 | } |
| 1311 | let name: String = row.get(0)?; |
| 1312 | let kind: String = row.get(1)?; |
| 1313 | let sql: Option<String> = row.get(2)?; |
| 1314 | let entry = serde_json::json!({ |
| 1315 | "name": name, |
| 1316 | "kind": kind, |
| 1317 | "sql": sql.map(|sql| truncate_utf8(&sql, 4 * 1024).0), |
| 1318 | }); |
| 1319 | let entry_bytes = serde_json::to_vec(&entry)?.len(); |
| 1320 | if schema_bytes + entry_bytes > MAX_EXPLORER_RESPONSE_BYTES / 2 { |
| 1321 | tables_truncated = true; |
| 1322 | break; |
| 1323 | } |
| 1324 | schema_bytes += entry_bytes; |
| 1325 | tables.push(entry); |
| 1326 | } |
| 1327 | drop(rows); |
| 1328 | drop(schema); |
| 1329 | let preview = match selected_table { |
| 1330 | Some(table) => Some(preview_table(&connection, table)?), |
| 1331 | None => None, |
| 1332 | }; |
| 1333 | Ok(serde_json::json!({ |
| 1334 | "cell_id": cell, |
| 1335 | "epoch": snapshot.epoch, |
| 1336 | "source": source, |
| 1337 | "tables": tables, |
| 1338 | "tables_truncated": tables_truncated, |
| 1339 | "preview": preview, |
| 1340 | })) |
| 1341 | } |
| 1342 | |
| 1343 | fn preview_table(connection: &Connection, table: &str) -> anyhow::Result<serde_json::Value> { |
| 1344 | let kind = connection |
| 1345 | .query_row( |
| 1346 | "SELECT type FROM sqlite_schema WHERE name = ?1 AND type IN ('table', 'view')", |
| 1347 | [table], |
| 1348 | |row| row.get::<_, String>(0), |
| 1349 | ) |
| 1350 | .optional()? |
| 1351 | .context("table_not_found")?; |
| 1352 | if kind != "table" { |
| 1353 | anyhow::bail!("table_not_previewable"); |
| 1354 | } |
| 1355 | let quoted = table.replace('"', "\"\""); |
| 1356 | let mut statement = connection.prepare(&format!( |
| 1357 | "SELECT * FROM \"{quoted}\" LIMIT {}", |
| 1358 | MAX_EXPLORER_ROWS + 1, |
| 1359 | ))?; |
| 1360 | let columns = statement |
| 1361 | .column_names() |
| 1362 | .iter() |
| 1363 | .take(MAX_EXPLORER_COLUMNS) |
| 1364 | .map(|name| truncate_utf8(name, 200).0) |
| 1365 | .collect::<Vec<_>>(); |
| 1366 | let column_count = columns.len(); |
| 1367 | let all_column_count = statement.column_count(); |
| 1368 | let mut query = statement.query([])?; |
| 1369 | let mut rows = Vec::new(); |
| 1370 | let mut response_bytes = 0_usize; |
| 1371 | let mut truncated = all_column_count > MAX_EXPLORER_COLUMNS; |
| 1372 | while let Some(row) = query.next()? { |
| 1373 | if rows.len() >= MAX_EXPLORER_ROWS { |
| 1374 | truncated = true; |
| 1375 | break; |
| 1376 | } |
| 1377 | let mut values = Vec::with_capacity(column_count); |
| 1378 | for index in 0..column_count { |
| 1379 | values.push(explorer_value(row.get_ref(index)?)); |
| 1380 | } |
| 1381 | let row_bytes = serde_json::to_vec(&values)?.len(); |
| 1382 | if response_bytes + row_bytes > MAX_EXPLORER_RESPONSE_BYTES / 2 { |
| 1383 | truncated = true; |
| 1384 | break; |
| 1385 | } |
| 1386 | response_bytes += row_bytes; |
| 1387 | rows.push(values); |
| 1388 | } |
| 1389 | Ok(serde_json::json!({ |
| 1390 | "table": table, |
| 1391 | "columns": columns, |
| 1392 | "rows": rows, |
| 1393 | "truncated": truncated, |
| 1394 | })) |
| 1395 | } |
| 1396 | |
| 1397 | fn explorer_value(value: ValueRef<'_>) -> serde_json::Value { |
| 1398 | match value { |
| 1399 | ValueRef::Null => serde_json::json!({ "type": "null", "value": null }), |
| 1400 | ValueRef::Integer(value) => { |
| 1401 | serde_json::json!({ "type": "integer", "value": value.to_string() }) |
| 1402 | } |
| 1403 | ValueRef::Real(value) => { |
| 1404 | serde_json::json!({ "type": "real", "value": value.to_string() }) |
| 1405 | } |
| 1406 | ValueRef::Text(value) => { |
| 1407 | let text = String::from_utf8_lossy(value); |
| 1408 | let (text, truncated) = truncate_utf8(&text, MAX_EXPLORER_VALUE_BYTES); |
| 1409 | serde_json::json!({ |
| 1410 | "type": "text", |
| 1411 | "value": text, |
| 1412 | "bytes": value.len(), |
| 1413 | "truncated": truncated, |
| 1414 | }) |
| 1415 | } |
| 1416 | ValueRef::Blob(value) => { |
| 1417 | let shown = &value[..value.len().min(MAX_EXPLORER_VALUE_BYTES)]; |
| 1418 | serde_json::json!({ |
| 1419 | "type": "blob", |
| 1420 | "value": hex(shown), |
| 1421 | "bytes": value.len(), |
| 1422 | "truncated": shown.len() < value.len(), |
| 1423 | }) |
| 1424 | } |
| 1425 | } |
| 1426 | } |
| 1427 | |
| 1428 | fn truncate_utf8(value: &str, max_bytes: usize) -> (String, bool) { |
| 1429 | if value.len() <= max_bytes { |
| 1430 | return (value.to_string(), false); |
| 1431 | } |
| 1432 | let mut end = max_bytes; |
| 1433 | while !value.is_char_boundary(end) { |
| 1434 | end -= 1; |
| 1435 | } |
| 1436 | (value[..end].to_string(), true) |
| 1437 | } |
| 1438 | |
| 1439 | fn hex(value: &[u8]) -> String { |
| 1440 | const DIGITS: &[u8; 16] = b"0123456789abcdef"; |
| 1441 | let mut encoded = String::with_capacity(value.len() * 2); |
| 1442 | for byte in value { |
| 1443 | encoded.push(DIGITS[(byte >> 4) as usize] as char); |
| 1444 | encoded.push(DIGITS[(byte & 0x0f) as usize] as char); |
| 1445 | } |
| 1446 | encoded |
| 1447 | } |
| 1448 | |
| 1449 | fn presence_request( |
| 1450 | config: &CloudConfig, |
| 1451 | node_session_id: &str, |
| 1452 | advertise: &str, |
| 1453 | listen: &str, |
| 1454 | hostname: &str, |
| 1455 | ) -> anyhow::Result<(String, HeaderMap)> { |
| 1456 | use hyper::header::{HeaderName, HeaderValue, AUTHORIZATION}; |
| 1457 | |
| 1458 | let token = config |
| 1459 | .installation_token |
| 1460 | .as_deref() |
| 1461 | .context("managed installation has no token")?; |
| 1462 | let mut url = url::Url::parse(&config.control_url)?; |
| 1463 | url.set_scheme(if url.scheme() == "https" { "wss" } else { "ws" }) |
| 1464 | .map_err(|_| anyhow!("invalid Managed Control Plane WebSocket scheme"))?; |
| 1465 | url.set_path("/api/agent/presence"); |
| 1466 | url.query_pairs_mut() |
| 1467 | .append_pair("node_session_id", node_session_id) |
| 1468 | .append_pair("advertise", advertise) |
| 1469 | .append_pair("listen", listen); |
| 1470 | let mut headers = HeaderMap::new(); |
| 1471 | headers.insert( |
| 1472 | AUTHORIZATION, |
| 1473 | HeaderValue::from_str(&format!("Bearer {token}"))?, |
| 1474 | ); |
| 1475 | headers.insert( |
| 1476 | HeaderName::from_static("x-cells-version"), |
| 1477 | HeaderValue::from_static(env!("CARGO_PKG_VERSION")), |
| 1478 | ); |
| 1479 | headers.insert( |
| 1480 | HeaderName::from_static("x-cells-capabilities"), |
| 1481 | HeaderValue::from_static("assets-v1,sqlite-explorer-v1,sqlite-explorer-v2"), |
| 1482 | ); |
| 1483 | headers.insert( |
| 1484 | HeaderName::from_static("x-cells-hostname"), |
| 1485 | HeaderValue::from_str(hostname)?, |
| 1486 | ); |
| 1487 | headers.insert( |
| 1488 | HeaderName::from_static("x-cells-os"), |
| 1489 | HeaderValue::from_static(std::env::consts::OS), |
| 1490 | ); |
| 1491 | headers.insert( |
| 1492 | HeaderName::from_static("x-cells-arch"), |
| 1493 | HeaderValue::from_static(std::env::consts::ARCH), |
| 1494 | ); |
| 1495 | Ok((url.into(), headers)) |
| 1496 | } |
| 1497 | |
| 1498 | pub fn start_deploy_agent(bucket: Bucket, runtime_ready: Arc<AtomicBool>) -> bool { |
| 1499 | let config = match connected_config() { |
| 1500 | Ok(Some(config)) => config, |
| 1501 | Ok(None) => return false, |
| 1502 | Err(error) => { |
| 1503 | warn!(event = "control_plane_agent_configuration_error", %error); |
| 1504 | return false; |
| 1505 | } |
| 1506 | }; |
| 1507 | tokio::spawn(async move { |
| 1508 | let client = match reqwest::Client::builder() |
| 1509 | .timeout(Duration::from_secs(30)) |
| 1510 | .build() |
| 1511 | { |
| 1512 | Ok(client) => client, |
| 1513 | Err(error) => { |
| 1514 | warn!(event = "control_plane_agent_client_error", %error); |
| 1515 | return; |
| 1516 | } |
| 1517 | }; |
| 1518 | let mut consecutive_failures = 0_u32; |
| 1519 | loop { |
| 1520 | let mut delay = Duration::from_secs(60); |
| 1521 | match poll_and_apply(&client, &config, &bucket).await { |
| 1522 | Ok(Some(applied)) => { |
| 1523 | if consecutive_failures > 0 { |
| 1524 | info!( |
| 1525 | event = "control_plane_agent_reconnected", |
| 1526 | failures = consecutive_failures, |
| 1527 | "Managed Control Plane connection restored" |
| 1528 | ); |
| 1529 | } |
| 1530 | consecutive_failures = 0; |
| 1531 | if runtime_ready.load(Ordering::SeqCst) && restart_on_deployment_enabled() { |
| 1532 | info!( |
| 1533 | event = "control_plane_restart_for_deploy", |
| 1534 | deployment_id = %applied.id, |
| 1535 | script_name = %applied.script_name, |
| 1536 | "deployment applied; restarting celld to load it" |
| 1537 | ); |
| 1538 | restart_for_deployment(); |
| 1539 | } |
| 1540 | } |
| 1541 | Ok(None) => { |
| 1542 | if consecutive_failures > 0 { |
| 1543 | info!( |
| 1544 | event = "control_plane_agent_reconnected", |
| 1545 | failures = consecutive_failures, |
| 1546 | "Managed Control Plane connection restored" |
| 1547 | ); |
| 1548 | } |
| 1549 | consecutive_failures = 0; |
| 1550 | } |
| 1551 | Err(error) => { |
| 1552 | if error.is::<ManagedControlCredentialRevoked>() { |
| 1553 | report_managed_runtime_state(ManagedRuntimeState::CredentialRevoked); |
| 1554 | } |
| 1555 | consecutive_failures = consecutive_failures.saturating_add(1); |
| 1556 | if consecutive_failures == 1 { |
| 1557 | info!( |
| 1558 | event = "control_plane_agent_unavailable", |
| 1559 | %error, |
| 1560 | "Managed Control Plane unavailable; bucket-backed serving continues" |
| 1561 | ); |
| 1562 | } |
| 1563 | let exponent = consecutive_failures.saturating_sub(1).min(5); |
| 1564 | let seconds = 2_u64.saturating_mul(1_u64 << exponent).min(60); |
| 1565 | let jitter_ms = (rand::random::<u16>() as u64) % 1000; |
| 1566 | delay = Duration::from_millis(seconds * 1000 + jitter_ms); |
| 1567 | } |
| 1568 | } |
| 1569 | tokio::time::sleep(delay).await; |
| 1570 | } |
| 1571 | }); |
| 1572 | true |
| 1573 | } |
| 1574 | |
| 1575 | pub async fn wait_for_initial_deployment(bucket: &Bucket) -> anyhow::Result<()> { |
| 1576 | let config = connected_config()?.context("managed installation is not connected")?; |
| 1577 | let client = reqwest::Client::builder() |
| 1578 | .timeout(Duration::from_secs(30)) |
| 1579 | .build()?; |
| 1580 | println!("Waiting for the first Managed Control Plane deployment..."); |
| 1581 | println!( |
| 1582 | "Deploy from {}/control; this process will start automatically.", |
| 1583 | config.control_url.trim_end_matches('/') |
| 1584 | ); |
| 1585 | loop { |
| 1586 | if deployment_exists(bucket).await? { |
| 1587 | return Ok(()); |
| 1588 | } |
| 1589 | if poll_and_apply(&client, &config, bucket).await?.is_some() { |
| 1590 | return Ok(()); |
| 1591 | } |
| 1592 | tokio::time::sleep(Duration::from_secs(2)).await; |
| 1593 | } |
| 1594 | } |
| 1595 | |
| 1596 | async fn deployment_exists(bucket: &Bucket) -> anyhow::Result<bool> { |
| 1597 | let objects = bucket |
| 1598 | .list("deploy/") |
| 1599 | .await |
| 1600 | .context("discover managed deployment")?; |
| 1601 | Ok(objects |
| 1602 | .iter() |
| 1603 | .map(|object| object.location.as_ref()) |
| 1604 | .any(|key| { |
| 1605 | key == "deploy/current.json" |
| 1606 | || key |
| 1607 | .strip_prefix("deploy/") |
| 1608 | .is_some_and(is_named_current_pointer) |
| 1609 | })) |
| 1610 | } |
| 1611 | |
| 1612 | fn is_named_current_pointer(key: &str) -> bool { |
| 1613 | let mut parts = key.split('/'); |
| 1614 | matches!( |
| 1615 | (parts.next(), parts.next(), parts.next()), |
| 1616 | (Some(_), Some("current.json"), None) |
| 1617 | ) |
| 1618 | } |
| 1619 | |
| 1620 | fn connected_config() -> anyhow::Result<Option<CloudConfig>> { |
| 1621 | let path = config_path()?; |
| 1622 | if !path.exists() { |
| 1623 | return Ok(None); |
| 1624 | } |
| 1625 | let contents = |
| 1626 | std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?; |
| 1627 | let config: CloudConfig = |
| 1628 | serde_json::from_str(&contents).with_context(|| format!("decode {}", path.display()))?; |
| 1629 | if config.installation_token.is_some() { |
| 1630 | Ok(Some(config)) |
| 1631 | } else { |
| 1632 | Ok(None) |
| 1633 | } |
| 1634 | } |
| 1635 | |
| 1636 | async fn poll_and_apply( |
| 1637 | client: &reqwest::Client, |
| 1638 | config: &CloudConfig, |
| 1639 | bucket: &Bucket, |
| 1640 | ) -> anyhow::Result<Option<AppliedDeployment>> { |
| 1641 | let token = config |
| 1642 | .installation_token |
| 1643 | .as_deref() |
| 1644 | .context("cloud config has no instance token")?; |
| 1645 | let response = client |
| 1646 | .post(format!("{}/api/agent/commands/next", config.control_url)) |
| 1647 | .bearer_auth(token) |
| 1648 | .json(&serde_json::json!({})) |
| 1649 | .send() |
| 1650 | .await |
| 1651 | .context("poll deployment command")?; |
| 1652 | if response.status() == reqwest::StatusCode::NO_CONTENT { |
| 1653 | return Ok(None); |
| 1654 | } |
| 1655 | if matches!(response.status().as_u16(), 401 | 403) { |
| 1656 | return Err(ManagedControlCredentialRevoked.into()); |
| 1657 | } |
| 1658 | if !response.status().is_success() { |
| 1659 | let status = response.status(); |
| 1660 | let body = response.text().await.unwrap_or_default(); |
| 1661 | return Err(anyhow!("deployment poll returned {status}: {body}")); |
| 1662 | } |
| 1663 | let envelope: AgentCommandEnvelope = |
| 1664 | response.json().await.context("decode deployment command")?; |
| 1665 | let command = envelope.command; |
| 1666 | if command.kind != "deploy" { |
| 1667 | return Err(anyhow!( |
| 1668 | "unsupported control-plane command: {}", |
| 1669 | command.kind |
| 1670 | )); |
| 1671 | } |
| 1672 | |
| 1673 | let result = apply_deployment(client, token, bucket, &command.deployment).await; |
| 1674 | let failure = result.as_ref().err().map(|error| format!("{error:#}")); |
| 1675 | let completion = client |
| 1676 | .post(format!( |
| 1677 | "{}/api/agent/commands/{}/complete", |
| 1678 | config.control_url, command.id |
| 1679 | )) |
| 1680 | .bearer_auth(token) |
| 1681 | .json(&CompleteCommandRequest { |
| 1682 | success: result.is_ok(), |
| 1683 | error: failure.as_deref(), |
| 1684 | }) |
| 1685 | .send() |
| 1686 | .await |
| 1687 | .context("report deployment completion")?; |
| 1688 | if !completion.status().is_success() { |
| 1689 | let status = completion.status(); |
| 1690 | let body = completion.text().await.unwrap_or_default(); |
| 1691 | return Err(anyhow!("deployment completion returned {status}: {body}")); |
| 1692 | } |
| 1693 | result?; |
| 1694 | Ok(Some(AppliedDeployment { |
| 1695 | id: command.id, |
| 1696 | script_name: command.deployment.script_name, |
| 1697 | })) |
| 1698 | } |
| 1699 | |
| 1700 | async fn apply_deployment( |
| 1701 | client: &reqwest::Client, |
| 1702 | token: &str, |
| 1703 | bucket: &Bucket, |
| 1704 | deployment: &AgentDeployment, |
| 1705 | ) -> anyhow::Result<()> { |
| 1706 | if deployment.pointer.version != deployment.version |
| 1707 | || deployment.manifest.version != deployment.version |
| 1708 | || deployment.manifest.script_name != deployment.script_name |
| 1709 | { |
| 1710 | return Err(anyhow!("control-plane deployment metadata is inconsistent")); |
| 1711 | } |
| 1712 | validate_managed_module_envelope(deployment)?; |
| 1713 | validate_managed_class_migrations(&deployment.manifest)?; |
| 1714 | for feature in &deployment.manifest.required_features { |
| 1715 | if feature != "assets-v1" { |
| 1716 | return Err(anyhow!("unsupported deployment feature: {feature}")); |
| 1717 | } |
| 1718 | } |
| 1719 | |
| 1720 | let mut asset_files = 0_u32; |
| 1721 | let mut asset_bytes = 0_u64; |
| 1722 | let mut asset_blobs = 0_usize; |
| 1723 | if let Some(reference) = &deployment.manifest.assets { |
| 1724 | let assets = deployment |
| 1725 | .assets |
| 1726 | .as_ref() |
| 1727 | .context("asset manifest has no control-plane transport")?; |
| 1728 | if reference.index != "assets.json" |
| 1729 | || reference.sha256 != assets.sha256 |
| 1730 | || reference.file_count != assets.file_count |
| 1731 | || reference.total_bytes != assets.total_bytes |
| 1732 | { |
| 1733 | return Err(anyhow!("control-plane asset metadata is inconsistent")); |
| 1734 | } |
| 1735 | let response = client |
| 1736 | .get(&assets.index_download_url) |
| 1737 | .bearer_auth(token) |
| 1738 | .send() |
| 1739 | .await |
| 1740 | .context("download asset index")?; |
| 1741 | if !response.status().is_success() { |
| 1742 | return Err(anyhow!( |
| 1743 | "asset index download returned {}", |
| 1744 | response.status() |
| 1745 | )); |
| 1746 | } |
| 1747 | let index_bytes = response.bytes().await?; |
| 1748 | let index_hash = format!("{:x}", Sha256::digest(&index_bytes)); |
| 1749 | if index_hash != assets.sha256 { |
| 1750 | return Err(anyhow!("asset index checksum mismatch")); |
| 1751 | } |
| 1752 | let index: AssetIndex = |
| 1753 | serde_json::from_slice(&index_bytes).context("decode asset index")?; |
| 1754 | if index.schema_version != 1 |
| 1755 | || index.entries.len() != assets.file_count as usize |
| 1756 | || index.entries.values().map(|entry| entry.bytes).sum::<u64>() != assets.total_bytes |
| 1757 | { |
| 1758 | return Err(anyhow!("asset index counts do not match deployment")); |
| 1759 | } |
| 1760 | |
| 1761 | let mut unique = std::collections::BTreeMap::<String, u64>::new(); |
| 1762 | for (path, entry) in &index.entries { |
| 1763 | validate_asset_index_entry(path, &entry.sha256, entry.bytes)?; |
| 1764 | if let Some(previous) = unique.insert(entry.sha256.clone(), entry.bytes) { |
| 1765 | if previous != entry.bytes { |
| 1766 | return Err(anyhow!( |
| 1767 | "asset digest has conflicting sizes: {}", |
| 1768 | entry.sha256 |
| 1769 | )); |
| 1770 | } |
| 1771 | } |
| 1772 | } |
| 1773 | for (sha256, bytes) in &unique { |
| 1774 | let key = |
| 1775 | asset_blob_key(sha256).ok_or_else(|| anyhow!("invalid asset digest: {sha256}"))?; |
| 1776 | if let Ok(Some((size, meta))) = bucket.head_with_meta(&key, "sha256").await { |
| 1777 | if size == *bytes && meta.as_deref() == Some(sha256.as_str()) { |
| 1778 | continue; |
| 1779 | } |
| 1780 | tracing::warn!( |
| 1781 | event = "asset_blob_repair_required", |
| 1782 | %sha256, |
| 1783 | "asset blob exists with an invalid size or checksum metadata" |
| 1784 | ); |
| 1785 | } |
| 1786 | |
| 1787 | let response = client |
| 1788 | .get(format!( |
| 1789 | "{}/{}", |
| 1790 | assets.blob_download_base_url.trim_end_matches('/'), |
| 1791 | sha256 |
| 1792 | )) |
| 1793 | .bearer_auth(token) |
| 1794 | .send() |
| 1795 | .await |
| 1796 | .with_context(|| format!("download asset blob {sha256}"))?; |
| 1797 | if !response.status().is_success() { |
| 1798 | return Err(anyhow!( |
| 1799 | "asset blob {sha256} download returned {}", |
| 1800 | response.status() |
| 1801 | )); |
| 1802 | } |
| 1803 | let body = response.bytes().await?; |
| 1804 | if body.len() as u64 != *bytes { |
| 1805 | return Err(anyhow!("asset blob {sha256} size mismatch")); |
| 1806 | } |
| 1807 | let hash = format!("{:x}", Sha256::digest(&body)); |
| 1808 | if hash != *sha256 { |
| 1809 | return Err(anyhow!("asset blob {sha256} checksum mismatch")); |
| 1810 | } |
| 1811 | bucket |
| 1812 | .put_with_meta(&key, body.to_vec(), &[("sha256", sha256)]) |
| 1813 | .await?; |
| 1814 | } |
| 1815 | bucket |
| 1816 | .put( |
| 1817 | &format!("{}/assets.json", deployment.pointer.prefix), |
| 1818 | index_bytes.to_vec(), |
| 1819 | ) |
| 1820 | .await?; |
| 1821 | asset_files = assets.file_count; |
| 1822 | asset_bytes = assets.total_bytes; |
| 1823 | asset_blobs = unique.len(); |
| 1824 | } else if deployment.assets.is_some() { |
| 1825 | return Err(anyhow!( |
| 1826 | "control-plane sent asset transport for a manifest without assets" |
| 1827 | )); |
| 1828 | } |
| 1829 | |
| 1830 | for module in &deployment.modules { |
| 1831 | let response = client |
| 1832 | .get(&module.download_url) |
| 1833 | .bearer_auth(token) |
| 1834 | .send() |
| 1835 | .await |
| 1836 | .with_context(|| format!("download module {}", module.name))?; |
| 1837 | if !response.status().is_success() { |
| 1838 | return Err(anyhow!( |
| 1839 | "module {} download returned {}", |
| 1840 | module.name, |
| 1841 | response.status() |
| 1842 | )); |
| 1843 | } |
| 1844 | let bytes = response.bytes().await?; |
| 1845 | let expected_bytes = deployment |
| 1846 | .manifest |
| 1847 | .modules |
| 1848 | .iter() |
| 1849 | .find(|reference| reference.name == module.name) |
| 1850 | .expect("managed module envelope validated above") |
| 1851 | .bytes; |
| 1852 | if bytes.len() != expected_bytes { |
| 1853 | return Err(anyhow!("module {} size mismatch", module.name)); |
| 1854 | } |
| 1855 | let hash = format!("{:x}", Sha256::digest(&bytes)); |
| 1856 | if hash != module.sha256 { |
| 1857 | return Err(anyhow!("module {} checksum mismatch", module.name)); |
| 1858 | } |
| 1859 | bucket |
| 1860 | .put( |
| 1861 | &format!("{}/{}", deployment.pointer.prefix, module.name), |
| 1862 | bytes.to_vec(), |
| 1863 | ) |
| 1864 | .await?; |
| 1865 | } |
| 1866 | bucket |
| 1867 | .put( |
| 1868 | &format!("{}/manifest.json", deployment.pointer.prefix), |
| 1869 | serde_json::to_vec_pretty(&deployment.manifest)?, |
| 1870 | ) |
| 1871 | .await?; |
| 1872 | bucket |
| 1873 | .put( |
| 1874 | &format!("deploy/{}/current.json", deployment.script_name), |
| 1875 | serde_json::to_vec_pretty(&deployment.pointer)?, |
| 1876 | ) |
| 1877 | .await?; |
| 1878 | // This fleet-wide pointer is the sole application selector. The named |
| 1879 | // pointer above remains only for resolving service-binding components and |
| 1880 | // for migrating buckets written by older celld releases. |
| 1881 | bucket |
| 1882 | .put( |
| 1883 | "deploy/current.json", |
| 1884 | serde_json::to_vec_pretty(&deployment.pointer)?, |
| 1885 | ) |
| 1886 | .await?; |
| 1887 | info!( |
| 1888 | event = "control_plane_deployment_applied", |
| 1889 | script_name = %deployment.script_name, |
| 1890 | version = %deployment.version, |
| 1891 | modules = deployment.modules.len(), |
| 1892 | asset_files, |
| 1893 | asset_bytes, |
| 1894 | asset_blobs, |
| 1895 | bucket = %bucket.name, |
| 1896 | "deployment artifacts written to fleet bucket" |
| 1897 | ); |
| 1898 | Ok(()) |
| 1899 | } |
| 1900 | |
| 1901 | fn validate_managed_module_envelope(deployment: &AgentDeployment) -> anyhow::Result<()> { |
| 1902 | let expected_prefix = format!("deploy/{}/{}", deployment.script_name, deployment.version); |
| 1903 | if deployment.pointer.script_name.as_deref() != Some(deployment.script_name.as_str()) |
| 1904 | || deployment.pointer.prefix != expected_prefix |
| 1905 | || deployment.pointer.rollout.percent != 100 |
| 1906 | { |
| 1907 | return Err(anyhow!( |
| 1908 | "control-plane deployment pointer is inconsistent with its identity" |
| 1909 | )); |
| 1910 | } |
| 1911 | let expected_schema = if deployment.manifest.assets.is_some() { |
| 1912 | 2 |
| 1913 | } else { |
| 1914 | 1 |
| 1915 | }; |
| 1916 | if deployment.manifest.schema_version != expected_schema { |
| 1917 | return Err(anyhow!( |
| 1918 | "control-plane manifest schema does not match its features" |
| 1919 | )); |
| 1920 | } |
| 1921 | if deployment.manifest.modules.len() > MAX_MANAGED_MODULES |
| 1922 | || deployment.modules.len() > MAX_MANAGED_MODULES |
| 1923 | { |
| 1924 | return Err(anyhow!("control-plane deployment has too many modules")); |
| 1925 | } |
| 1926 | |
| 1927 | let mut manifest_modules = std::collections::BTreeMap::new(); |
| 1928 | let mut total_bytes = 0_usize; |
| 1929 | for module in &deployment.manifest.modules { |
| 1930 | if !valid_managed_module_name(&module.name) || !valid_lower_hex(&module.sha256, 16) { |
| 1931 | return Err(anyhow!( |
| 1932 | "control-plane manifest has an invalid module reference: {:?}", |
| 1933 | module.name |
| 1934 | )); |
| 1935 | } |
| 1936 | total_bytes = total_bytes |
| 1937 | .checked_add(module.bytes) |
| 1938 | .filter(|bytes| *bytes <= MAX_MANAGED_MODULE_BYTES) |
| 1939 | .ok_or_else(|| anyhow!("control-plane deployment modules are too large"))?; |
| 1940 | if manifest_modules |
| 1941 | .insert(module.name.as_str(), module) |
| 1942 | .is_some() |
| 1943 | { |
| 1944 | return Err(anyhow!( |
| 1945 | "control-plane manifest repeats module {:?}", |
| 1946 | module.name |
| 1947 | )); |
| 1948 | } |
| 1949 | } |
| 1950 | match deployment.manifest.main_module.as_deref() { |
| 1951 | Some(main) if !manifest_modules.contains_key(main) => { |
| 1952 | return Err(anyhow!( |
| 1953 | "control-plane manifest main module is not in its module list" |
| 1954 | )); |
| 1955 | } |
| 1956 | None if deployment.manifest.assets.is_none() => { |
| 1957 | return Err(anyhow!( |
| 1958 | "control-plane manifest has neither a main module nor assets" |
| 1959 | )); |
| 1960 | } |
| 1961 | _ => {} |
| 1962 | } |
| 1963 | |
| 1964 | let mut transport_modules = std::collections::BTreeMap::new(); |
| 1965 | for module in &deployment.modules { |
| 1966 | if !valid_managed_module_name(&module.name) || !valid_lower_hex(&module.sha256, 64) { |
| 1967 | return Err(anyhow!( |
| 1968 | "control-plane transport has an invalid module reference: {:?}", |
| 1969 | module.name |
| 1970 | )); |
| 1971 | } |
| 1972 | if transport_modules |
| 1973 | .insert(module.name.as_str(), module) |
| 1974 | .is_some() |
| 1975 | { |
| 1976 | return Err(anyhow!( |
| 1977 | "control-plane transport repeats module {:?}", |
| 1978 | module.name |
| 1979 | )); |
| 1980 | } |
| 1981 | } |
| 1982 | if manifest_modules.keys().ne(transport_modules.keys()) { |
| 1983 | return Err(anyhow!( |
| 1984 | "control-plane transport modules do not match the manifest" |
| 1985 | )); |
| 1986 | } |
| 1987 | for (name, manifest) in manifest_modules { |
| 1988 | let transport = transport_modules |
| 1989 | .get(name) |
| 1990 | .expect("module name sets compared above"); |
| 1991 | if !transport.sha256.starts_with(&manifest.sha256) { |
| 1992 | return Err(anyhow!( |
| 1993 | "control-plane transport checksum does not match manifest module {name:?}" |
| 1994 | )); |
| 1995 | } |
| 1996 | } |
| 1997 | Ok(()) |
| 1998 | } |
| 1999 | |
| 2000 | fn valid_managed_module_name(name: &str) -> bool { |
| 2001 | !name.is_empty() |
| 2002 | && name.len() <= 240 |
| 2003 | && !name.starts_with('/') |
| 2004 | && !name.contains('\\') |
| 2005 | && name |
| 2006 | .split('/') |
| 2007 | .all(|segment| !segment.is_empty() && segment != "." && segment != "..") |
| 2008 | } |
| 2009 | |
| 2010 | fn valid_lower_hex(value: &str, length: usize) -> bool { |
| 2011 | value.len() == length |
| 2012 | && value |
| 2013 | .bytes() |
| 2014 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) |
| 2015 | } |
| 2016 | |
| 2017 | fn validate_managed_class_migrations(manifest: &Manifest) -> anyhow::Result<()> { |
| 2018 | let do_classes = manifest |
| 2019 | .do_classes |
| 2020 | .iter() |
| 2021 | .map(|class| { |
| 2022 | if class.is_empty() { |
| 2023 | Err(anyhow!( |
| 2024 | "managed manifest has an empty Durable Object class" |
| 2025 | )) |
| 2026 | } else { |
| 2027 | Ok(class.as_str()) |
| 2028 | } |
| 2029 | }) |
| 2030 | .collect::<anyhow::Result<std::collections::BTreeSet<_>>>()?; |
| 2031 | let mut declared_sqlite = std::collections::BTreeSet::new(); |
| 2032 | for class in &manifest.sqlite_classes { |
| 2033 | if class.is_empty() { |
| 2034 | return Err(anyhow!("managed manifest has an empty SQLite class")); |
| 2035 | } |
| 2036 | if !do_classes.contains(class.as_str()) { |
| 2037 | return Err(anyhow!( |
| 2038 | "managed manifest SQLite class {class:?} is not a Durable Object class" |
| 2039 | )); |
| 2040 | } |
| 2041 | if !declared_sqlite.insert(class.as_str()) { |
| 2042 | return Err(anyhow!( |
| 2043 | "managed manifest declares SQLite class {class:?} more than once" |
| 2044 | )); |
| 2045 | } |
| 2046 | } |
| 2047 | |
| 2048 | let metadata = manifest |
| 2049 | .raw_metadata |
| 2050 | .as_object() |
| 2051 | .context("managed manifest raw_metadata must be an object")?; |
| 2052 | let Some(migrations) = metadata.get("migrations") else { |
| 2053 | if declared_sqlite.is_empty() { |
| 2054 | return Ok(()); |
| 2055 | } |
| 2056 | return Err(anyhow!( |
| 2057 | "managed manifest SQLite classes do not match its migration metadata" |
| 2058 | )); |
| 2059 | }; |
| 2060 | let migrations = migrations |
| 2061 | .as_object() |
| 2062 | .context("managed manifest migrations must be an object")?; |
| 2063 | let unsupported = migrations |
| 2064 | .keys() |
| 2065 | .filter(|key| !matches!(key.as_str(), "old_tag" | "new_tag" | "steps")) |
| 2066 | .cloned() |
| 2067 | .collect::<Vec<_>>(); |
| 2068 | if !unsupported.is_empty() { |
| 2069 | return Err(anyhow!( |
| 2070 | "unsupported managed migration keys: {}. Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment", |
| 2071 | unsupported.join(", ") |
| 2072 | )); |
| 2073 | } |
| 2074 | for tag in ["old_tag", "new_tag"] { |
| 2075 | if let Some(value) = migrations.get(tag) { |
| 2076 | if !value.is_null() && !value.as_str().is_some_and(|value| !value.is_empty()) { |
| 2077 | return Err(anyhow!( |
| 2078 | "managed manifest migrations.{tag} must be null or a non-empty string" |
| 2079 | )); |
| 2080 | } |
| 2081 | } |
| 2082 | } |
| 2083 | let steps = migrations |
| 2084 | .get("steps") |
| 2085 | .and_then(serde_json::Value::as_array) |
| 2086 | .context("managed manifest migrations.steps must be an array")?; |
| 2087 | let mut migrated_sqlite = std::collections::BTreeSet::new(); |
| 2088 | for (index, step) in steps.iter().enumerate() { |
| 2089 | let step = step.as_object().with_context(|| { |
| 2090 | format!("managed manifest migrations.steps[{index}] must be an object") |
| 2091 | })?; |
| 2092 | let unsupported = step |
| 2093 | .keys() |
| 2094 | .filter(|key| key.as_str() != "new_sqlite_classes") |
| 2095 | .cloned() |
| 2096 | .collect::<Vec<_>>(); |
| 2097 | if !unsupported.is_empty() { |
| 2098 | return Err(anyhow!( |
| 2099 | "unsupported managed migration keys: {}. Class rename, delete, transfer, and non-SQLite migration semantics need an explicit persisted-state contract before deployment", |
| 2100 | unsupported.join(", ") |
| 2101 | )); |
| 2102 | } |
| 2103 | let classes = step |
| 2104 | .get("new_sqlite_classes") |
| 2105 | .and_then(serde_json::Value::as_array) |
| 2106 | .with_context(|| { |
| 2107 | format!( |
| 2108 | "managed manifest migrations.steps[{index}].new_sqlite_classes must be an array" |
| 2109 | ) |
| 2110 | })?; |
| 2111 | for (class_index, class) in classes.iter().enumerate() { |
| 2112 | let class = class.as_str().filter(|class| !class.is_empty()).with_context(|| { |
| 2113 | format!( |
| 2114 | "managed manifest migrations.steps[{index}].new_sqlite_classes[{class_index}] must be a non-empty string" |
| 2115 | ) |
| 2116 | })?; |
| 2117 | if !migrated_sqlite.insert(class) { |
| 2118 | return Err(anyhow!( |
| 2119 | "managed migration introduces SQLite class {class:?} more than once" |
| 2120 | )); |
| 2121 | } |
| 2122 | } |
| 2123 | } |
| 2124 | if migrated_sqlite != declared_sqlite { |
| 2125 | return Err(anyhow!( |
| 2126 | "managed manifest SQLite classes do not match its migration metadata" |
| 2127 | )); |
| 2128 | } |
| 2129 | Ok(()) |
| 2130 | } |
| 2131 | |
| 2132 | fn validate_asset_index_entry(path: &str, sha256: &str, bytes: u64) -> anyhow::Result<()> { |
| 2133 | if !path.starts_with('/') |
| 2134 | || path.len() > 1024 |
| 2135 | || path.contains('\\') |
| 2136 | || path.contains('\0') |
| 2137 | || path |
| 2138 | .split('/') |
| 2139 | .skip(1) |
| 2140 | .any(|segment| segment.is_empty() || segment == "." || segment == "..") |
| 2141 | { |
| 2142 | return Err(anyhow!("invalid asset path in index: {path:?}")); |
| 2143 | } |
| 2144 | if asset_blob_key(sha256).is_none() { |
| 2145 | return Err(anyhow!("invalid asset digest in index: {sha256:?}")); |
| 2146 | } |
| 2147 | if bytes > 25 * 1024 * 1024 { |
| 2148 | return Err(anyhow!("asset exceeds runtime size limit: {path:?}")); |
| 2149 | } |
| 2150 | Ok(()) |
| 2151 | } |
| 2152 | |
| 2153 | async fn connect(options: ConnectOptions, wait: bool) -> anyhow::Result<()> { |
| 2154 | let path = config_path()?; |
| 2155 | connect_at_path(path, options, wait).await |
| 2156 | } |
| 2157 | |
| 2158 | async fn connect_at_path(path: PathBuf, options: ConnectOptions, wait: bool) -> anyhow::Result<()> { |
| 2159 | let _lock = match try_acquire_enrollment_lock(&path).await? { |
| 2160 | Some(lock) => lock, |
| 2161 | None => wait_for_shared_enrollment(&path).await?, |
| 2162 | }; |
| 2163 | let mut config = load_or_create_config(&path, &options)?; |
| 2164 | let enrollment_byo = match ( |
| 2165 | config.storage.as_ref(), |
| 2166 | config.byo_storage.as_ref(), |
| 2167 | options.byo_storage.as_ref(), |
| 2168 | ) { |
| 2169 | (Some(_), None, Some(_)) => { |
| 2170 | return Err(anyhow!( |
| 2171 | "this installation is enrolled with managed storage; disconnect before changing storage origin" |
| 2172 | )); |
| 2173 | } |
| 2174 | (None, Some(current), Some(requested)) if current != requested => { |
| 2175 | return Err(anyhow!( |
| 2176 | "the requested BYO bucket does not match this installation enrollment" |
| 2177 | )); |
| 2178 | } |
| 2179 | (None, Some(current), _) => Some(current.clone()), |
| 2180 | (None, None, requested) => requested.cloned(), |
| 2181 | (Some(_), None, None) => None, |
| 2182 | _ => { |
| 2183 | return Err(anyhow!( |
| 2184 | "managed installation record contains an invalid storage target" |
| 2185 | )); |
| 2186 | } |
| 2187 | }; |
| 2188 | if config.installation_token.is_some() |
| 2189 | && (config.storage.is_some() || config.byo_storage.is_some()) |
| 2190 | && !options.force |
| 2191 | { |
| 2192 | validate_requested_storage(&config, options.byo_storage.as_ref())?; |
| 2193 | retry_credential_handoff_ack(path.clone(), config.clone()); |
| 2194 | info!( |
| 2195 | event = "control_plane_already_connected", |
| 2196 | installation_id = %config.installation_id, |
| 2197 | environment = %config.environment, |
| 2198 | control_url = %config.control_url, |
| 2199 | "celld is already connected to the Managed Control Plane" |
| 2200 | ); |
| 2201 | return Ok(()); |
| 2202 | } |
| 2203 | |
| 2204 | config.control_url = normalized_control_url(&options.control_url)?; |
| 2205 | config.environment = options.environment.clone(); |
| 2206 | config.installation_token = None; |
| 2207 | config.fleet_id = None; |
| 2208 | config.environment_id = None; |
| 2209 | config.credential_handoff_id = None; |
| 2210 | config.pending_claim = None; |
| 2211 | config.storage = None; |
| 2212 | config.byo_storage = enrollment_byo; |
| 2213 | save_config(&path, &config)?; |
| 2214 | |
| 2215 | let client = reqwest::Client::builder() |
| 2216 | .timeout(Duration::from_secs(if wait { 15 } else { 3 })) |
| 2217 | .build()?; |
| 2218 | let claim_url = format!("{}/api/instances/claims", config.control_url); |
| 2219 | let instance_name = instance_name(); |
| 2220 | let response = client |
| 2221 | .post(claim_url) |
| 2222 | .json(&CreateClaimRequest { |
| 2223 | instance_id: &config.installation_id, |
| 2224 | instance_name: &instance_name, |
| 2225 | environment: &config.environment, |
| 2226 | version: env!("CARGO_PKG_VERSION"), |
| 2227 | platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH), |
| 2228 | storage_origin: if config.byo_storage.is_some() { |
| 2229 | "byo" |
| 2230 | } else { |
| 2231 | "managed_r2" |
| 2232 | }, |
| 2233 | bucket: config |
| 2234 | .byo_storage |
| 2235 | .as_ref() |
| 2236 | .map(|storage| storage.bucket.as_str()), |
| 2237 | endpoint: config |
| 2238 | .byo_storage |
| 2239 | .as_ref() |
| 2240 | .and_then(|storage| storage.endpoint.as_deref()), |
| 2241 | region: config |
| 2242 | .byo_storage |
| 2243 | .as_ref() |
| 2244 | .map(|storage| storage.region.as_str()), |
| 2245 | }) |
| 2246 | .send() |
| 2247 | .await |
| 2248 | .context("request activation link")?; |
| 2249 | if !response.status().is_success() { |
| 2250 | let status = response.status(); |
| 2251 | let body = response.text().await.unwrap_or_default(); |
| 2252 | return Err(anyhow!("activation endpoint returned {status}: {body}")); |
| 2253 | } |
| 2254 | let claim: CreateClaimResponse = response.json().await.context("decode activation link")?; |
| 2255 | config.pending_claim = Some(PendingClaim { |
| 2256 | verification_uri_complete: claim.verification_uri_complete.clone(), |
| 2257 | expires_at_ms: current_time_ms().saturating_add(claim.expires_in.saturating_mul(1000)), |
| 2258 | }); |
| 2259 | save_config(&path, &config)?; |
| 2260 | |
| 2261 | info!( |
| 2262 | event = "control_plane_claim_pending", |
| 2263 | installation_id = %config.installation_id, |
| 2264 | environment = %config.environment, |
| 2265 | verification_url = %claim.verification_uri_complete, |
| 2266 | expires_in_seconds = claim.expires_in, |
| 2267 | "authenticate to connect this celld instance" |
| 2268 | ); |
| 2269 | println!( |
| 2270 | "\nConnect this celld instance to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n", |
| 2271 | claim.verification_uri_complete, config.environment |
| 2272 | ); |
| 2273 | |
| 2274 | if wait { |
| 2275 | wait_for_approval(client, path, config, claim).await |
| 2276 | } else { |
| 2277 | tokio::spawn(async move { |
| 2278 | if let Err(error) = wait_for_approval(client, path, config, claim).await { |
| 2279 | warn!(event = "control_plane_claim_failed", %error); |
| 2280 | } |
| 2281 | }); |
| 2282 | Ok(()) |
| 2283 | } |
| 2284 | } |
| 2285 | |
| 2286 | async fn wait_for_approval( |
| 2287 | client: reqwest::Client, |
| 2288 | path: PathBuf, |
| 2289 | mut config: CloudConfig, |
| 2290 | claim: CreateClaimResponse, |
| 2291 | ) -> anyhow::Result<()> { |
| 2292 | let deadline = Instant::now() + Duration::from_secs(claim.expires_in); |
| 2293 | let poll_url = format!("{}/api/instances/claims/token", config.control_url); |
| 2294 | let mut interval = claim.interval.max(1); |
| 2295 | while Instant::now() < deadline { |
| 2296 | tokio::time::sleep(Duration::from_secs(interval)).await; |
| 2297 | let response = client |
| 2298 | .post(&poll_url) |
| 2299 | .json(&PollClaimRequest { |
| 2300 | device_code: &claim.device_code, |
| 2301 | }) |
| 2302 | .send() |
| 2303 | .await |
| 2304 | .context("poll activation")?; |
| 2305 | if response.status() == reqwest::StatusCode::GONE { |
| 2306 | return Err(anyhow!("activation link expired")); |
| 2307 | } |
| 2308 | if !response.status().is_success() { |
| 2309 | let status = response.status(); |
| 2310 | let body = response.text().await.unwrap_or_default(); |
| 2311 | return Err(anyhow!("activation poll returned {status}: {body}")); |
| 2312 | } |
| 2313 | let result: PollClaimResponse = |
| 2314 | response.json().await.context("decode activation status")?; |
| 2315 | if result.status == "pending" { |
| 2316 | interval = result.interval.unwrap_or(interval).max(1); |
| 2317 | continue; |
| 2318 | } |
| 2319 | if result.status != "connected" { |
| 2320 | return Err(anyhow!("unexpected activation status: {}", result.status)); |
| 2321 | } |
| 2322 | config.installation_token = Some( |
| 2323 | result |
| 2324 | .instance_token |
| 2325 | .context("activation response omitted instance token")?, |
| 2326 | ); |
| 2327 | config.credential_version = result.credential_version.unwrap_or(1); |
| 2328 | config.fleet_id = Some( |
| 2329 | result |
| 2330 | .fleet_id |
| 2331 | .context("activation response omitted fleet")?, |
| 2332 | ); |
| 2333 | config.environment_id = Some( |
| 2334 | result |
| 2335 | .environment_id |
| 2336 | .context("activation response omitted environment")?, |
| 2337 | ); |
| 2338 | let bucket = result |
| 2339 | .bucket |
| 2340 | .context("activation response omitted bucket")?; |
| 2341 | let region = result |
| 2342 | .region |
| 2343 | .context("activation response omitted bucket region")?; |
| 2344 | match result.storage_origin.as_str() { |
| 2345 | "managed_r2" => { |
| 2346 | if config.byo_storage.is_some() { |
| 2347 | return Err(anyhow!( |
| 2348 | "activation changed the requested BYO bucket to managed storage" |
| 2349 | )); |
| 2350 | } |
| 2351 | config.storage = Some(ManagedStorageConfig { |
| 2352 | bucket, |
| 2353 | endpoint: result |
| 2354 | .endpoint |
| 2355 | .context("activation response omitted bucket endpoint")?, |
| 2356 | region, |
| 2357 | access_key_id: result |
| 2358 | .access_key_id |
| 2359 | .context("activation response omitted storage access key")?, |
| 2360 | secret_access_key: result |
| 2361 | .secret_access_key |
| 2362 | .context("activation response omitted storage secret key")?, |
| 2363 | session_token: result.session_token, |
| 2364 | }); |
| 2365 | config.credential_handoff_id = Some( |
| 2366 | result |
| 2367 | .credential_handoff_id |
| 2368 | .context("activation response omitted credential handoff")?, |
| 2369 | ); |
| 2370 | } |
| 2371 | "byo" => { |
| 2372 | let storage = ByoStorageConfig { |
| 2373 | bucket, |
| 2374 | endpoint: result.endpoint, |
| 2375 | region, |
| 2376 | }; |
| 2377 | if config.byo_storage.as_ref() != Some(&storage) { |
| 2378 | return Err(anyhow!( |
| 2379 | "activation returned a different BYO storage target" |
| 2380 | )); |
| 2381 | } |
| 2382 | if result.credential_handoff_id.is_some() |
| 2383 | || result.access_key_id.is_some() |
| 2384 | || result.secret_access_key.is_some() |
| 2385 | || result.session_token.is_some() |
| 2386 | { |
| 2387 | return Err(anyhow!( |
| 2388 | "activation returned managed credentials for a BYO bucket" |
| 2389 | )); |
| 2390 | } |
| 2391 | config.storage = None; |
| 2392 | config.byo_storage = Some(storage); |
| 2393 | config.credential_handoff_id = None; |
| 2394 | } |
| 2395 | origin => { |
| 2396 | return Err(anyhow!( |
| 2397 | "activation returned unknown storage origin: {origin}" |
| 2398 | )) |
| 2399 | } |
| 2400 | } |
| 2401 | config.pending_claim = None; |
| 2402 | save_config(&path, &config)?; |
| 2403 | if let Some(handoff_id) = config.credential_handoff_id.clone() { |
| 2404 | match acknowledge_credential_handoff(&client, &config, &handoff_id).await { |
| 2405 | Ok(()) => { |
| 2406 | config.credential_handoff_id = None; |
| 2407 | save_config(&path, &config)?; |
| 2408 | } |
| 2409 | Err(error) => { |
| 2410 | info!( |
| 2411 | event = "control_plane_credential_ack_deferred", |
| 2412 | %error, |
| 2413 | "managed credential is saved; delivery acknowledgement will retry in the background" |
| 2414 | ); |
| 2415 | retry_credential_handoff_ack(path.clone(), config.clone()); |
| 2416 | } |
| 2417 | } |
| 2418 | } |
| 2419 | info!( |
| 2420 | event = "control_plane_connected", |
| 2421 | installation_id = %config.installation_id, |
| 2422 | fleet_id = %config.fleet_id.as_deref().unwrap_or_default(), |
| 2423 | environment_id = %config.environment_id.as_deref().unwrap_or_default(), |
| 2424 | environment = %config.environment, |
| 2425 | "celld connected to the Managed Control Plane" |
| 2426 | ); |
| 2427 | println!( |
| 2428 | "Connected to the Managed Control Plane ({}).\n\ |
| 2429 | Keep celld running. In your app directory, run `celld token`, apply the \ |
| 2430 | exports it prints, then run `npx wrangler@4 deploy`.", |
| 2431 | config.environment |
| 2432 | ); |
| 2433 | return Ok(()); |
| 2434 | } |
| 2435 | // Make expiry visible so an unattended process cannot keep displaying a |
| 2436 | // dead approval URL. |
| 2437 | println!( |
| 2438 | "\nThe activation link expired before it was approved.\n\ |
| 2439 | Restart celld to get a new one.\n" |
| 2440 | ); |
| 2441 | Err(anyhow!( |
| 2442 | "activation link expired before approval; restart celld for a new link" |
| 2443 | )) |
| 2444 | } |
| 2445 | |
| 2446 | fn options_from_env() -> anyhow::Result<ConnectOptions> { |
| 2447 | Ok(ConnectOptions { |
| 2448 | control_url: std::env::var("CELLD_CONTROL_URL") |
| 2449 | .unwrap_or_else(|_| DEFAULT_CONTROL_URL.to_string()), |
| 2450 | environment: std::env::var("CELLD_ENV").unwrap_or_else(|_| DEFAULT_ENVIRONMENT.to_string()), |
| 2451 | force: false, |
| 2452 | byo_storage: None, |
| 2453 | }) |
| 2454 | } |
| 2455 | |
| 2456 | fn config_path() -> anyhow::Result<PathBuf> { |
| 2457 | let base = if let Some(path) = std::env::var_os("CELLD_CONFIG_DIR") { |
| 2458 | PathBuf::from(path) |
| 2459 | } else if let Some(path) = std::env::var_os("XDG_CONFIG_HOME") { |
| 2460 | PathBuf::from(path).join("celld") |
| 2461 | } else if let Some(path) = std::env::var_os("HOME") { |
| 2462 | PathBuf::from(path).join(".config").join("celld") |
| 2463 | } else { |
| 2464 | std::env::current_dir()?.join(".celld") |
| 2465 | }; |
| 2466 | Ok(base.join("cloud.json")) |
| 2467 | } |
| 2468 | |
| 2469 | fn load_or_create_config(path: &Path, options: &ConnectOptions) -> anyhow::Result<CloudConfig> { |
| 2470 | if path.exists() { |
| 2471 | let contents = |
| 2472 | std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?; |
| 2473 | return serde_json::from_str(&contents) |
| 2474 | .with_context(|| format!("decode {}", path.display())); |
| 2475 | } |
| 2476 | let config = CloudConfig { |
| 2477 | version: installation_schema_version(), |
| 2478 | installation_id: random_instance_id(), |
| 2479 | installation_token: None, |
| 2480 | credential_version: initial_credential_version(), |
| 2481 | fleet_id: None, |
| 2482 | environment_id: None, |
| 2483 | control_url: normalized_control_url(&options.control_url)?, |
| 2484 | environment: options.environment.clone(), |
| 2485 | storage: None, |
| 2486 | byo_storage: None, |
| 2487 | credential_handoff_id: None, |
| 2488 | previous_credential: None, |
| 2489 | pending_claim: None, |
| 2490 | }; |
| 2491 | save_config(path, &config)?; |
| 2492 | Ok(config) |
| 2493 | } |
| 2494 | |
| 2495 | fn retry_credential_handoff_ack(path: PathBuf, config: CloudConfig) { |
| 2496 | let Some(handoff_id) = config.credential_handoff_id.clone() else { |
| 2497 | return; |
| 2498 | }; |
| 2499 | tokio::spawn(async move { |
| 2500 | let client = match reqwest::Client::builder() |
| 2501 | .timeout(Duration::from_secs(5)) |
| 2502 | .build() |
| 2503 | { |
| 2504 | Ok(client) => client, |
| 2505 | Err(_) => return, |
| 2506 | }; |
| 2507 | if acknowledge_credential_handoff(&client, &config, &handoff_id) |
| 2508 | .await |
| 2509 | .is_err() |
| 2510 | { |
| 2511 | return; |
| 2512 | } |
| 2513 | let Ok(_lock) = acquire_enrollment_lock(&path).await else { |
| 2514 | return; |
| 2515 | }; |
| 2516 | let Ok(contents) = std::fs::read_to_string(&path) else { |
| 2517 | return; |
| 2518 | }; |
| 2519 | let Ok(mut current) = serde_json::from_str::<CloudConfig>(&contents) else { |
| 2520 | return; |
| 2521 | }; |
| 2522 | if current.credential_handoff_id.as_deref() != Some(&handoff_id) { |
| 2523 | return; |
| 2524 | } |
| 2525 | current.credential_handoff_id = None; |
| 2526 | current.previous_credential = None; |
| 2527 | if let Err(error) = save_config(&path, ¤t) { |
| 2528 | warn!( |
| 2529 | event = "control_plane_credential_ack_save_failed", |
| 2530 | %error, |
| 2531 | "credential delivery was acknowledged but the local marker could not be cleared" |
| 2532 | ); |
| 2533 | } |
| 2534 | }); |
| 2535 | } |
| 2536 | |
| 2537 | async fn acknowledge_credential_handoff( |
| 2538 | client: &reqwest::Client, |
| 2539 | config: &CloudConfig, |
| 2540 | handoff_id: &str, |
| 2541 | ) -> anyhow::Result<()> { |
| 2542 | let token = config |
| 2543 | .installation_token |
| 2544 | .as_deref() |
| 2545 | .context("managed installation has no token")?; |
| 2546 | let response = client |
| 2547 | .post(format!("{}/api/agent/credentials/ack", config.control_url)) |
| 2548 | .bearer_auth(token) |
| 2549 | .json(&serde_json::json!({ "handoff_id": handoff_id })) |
| 2550 | .send() |
| 2551 | .await |
| 2552 | .context("acknowledge managed credential delivery")?; |
| 2553 | if !response.status().is_success() { |
| 2554 | return Err(anyhow!( |
| 2555 | "credential acknowledgement returned {}", |
| 2556 | response.status() |
| 2557 | )); |
| 2558 | } |
| 2559 | Ok(()) |
| 2560 | } |
| 2561 | |
| 2562 | fn save_config(path: &Path, config: &CloudConfig) -> anyhow::Result<()> { |
| 2563 | let parent = path |
| 2564 | .parent() |
| 2565 | .context("cloud config has no parent directory")?; |
| 2566 | std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?; |
| 2567 | let temporary = path.with_extension("json.tmp"); |
| 2568 | std::fs::write(&temporary, serde_json::to_vec_pretty(config)?) |
| 2569 | .with_context(|| format!("write {}", temporary.display()))?; |
| 2570 | restrict_permissions(&temporary)?; |
| 2571 | std::fs::rename(&temporary, path).with_context(|| format!("replace {}", path.display()))?; |
| 2572 | Ok(()) |
| 2573 | } |
| 2574 | |
| 2575 | #[cfg(unix)] |
| 2576 | fn restrict_permissions(path: &Path) -> anyhow::Result<()> { |
| 2577 | use std::os::unix::fs::PermissionsExt; |
| 2578 | std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; |
| 2579 | Ok(()) |
| 2580 | } |
| 2581 | |
| 2582 | #[cfg(not(unix))] |
| 2583 | fn restrict_permissions(_path: &Path) -> anyhow::Result<()> { |
| 2584 | Ok(()) |
| 2585 | } |
| 2586 | |
| 2587 | fn random_instance_id() -> String { |
| 2588 | let mut bytes = [0_u8; 16]; |
| 2589 | rand::rngs::OsRng.fill_bytes(&mut bytes); |
| 2590 | let suffix = bytes |
| 2591 | .iter() |
| 2592 | .map(|byte| format!("{byte:02x}")) |
| 2593 | .collect::<String>(); |
| 2594 | format!("inst_{suffix}") |
| 2595 | } |
| 2596 | |
| 2597 | fn installation_schema_version() -> u32 { |
| 2598 | 1 |
| 2599 | } |
| 2600 | |
| 2601 | fn initial_credential_version() -> u64 { |
| 2602 | 1 |
| 2603 | } |
| 2604 | |
| 2605 | fn managed_storage_origin() -> String { |
| 2606 | "managed_r2".to_string() |
| 2607 | } |
| 2608 | |
| 2609 | fn validate_requested_storage( |
| 2610 | config: &CloudConfig, |
| 2611 | requested: Option<&ByoStorageConfig>, |
| 2612 | ) -> anyhow::Result<()> { |
| 2613 | match (config.storage.as_ref(), config.byo_storage.as_ref(), requested) { |
| 2614 | (Some(_), None, None) | (None, Some(_), None) => Ok(()), |
| 2615 | (Some(_), None, Some(_)) => Err(anyhow!( |
| 2616 | "this installation is enrolled with managed storage; disconnect before changing storage origin" |
| 2617 | )), |
| 2618 | (None, Some(current), Some(requested)) if current == requested => Ok(()), |
| 2619 | (None, Some(_), Some(_)) => Err(anyhow!( |
| 2620 | "the requested BYO bucket does not match this installation enrollment" |
| 2621 | )), |
| 2622 | _ => Err(anyhow!( |
| 2623 | "managed installation record contains an invalid storage target" |
| 2624 | )), |
| 2625 | } |
| 2626 | } |
| 2627 | |
| 2628 | struct EnrollmentLock { |
| 2629 | _file: File, |
| 2630 | } |
| 2631 | |
| 2632 | async fn try_acquire_enrollment_lock(config: &Path) -> anyhow::Result<Option<EnrollmentLock>> { |
| 2633 | let (file, lock_path) = open_enrollment_lock(config).await?; |
| 2634 | tokio::task::spawn_blocking(move || match fs2::FileExt::try_lock_exclusive(&file) { |
| 2635 | Ok(()) => Ok(Some(EnrollmentLock { _file: file })), |
| 2636 | Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(None), |
| 2637 | Err(error) => Err(error).with_context(|| format!("lock {}", lock_path.display())), |
| 2638 | }) |
| 2639 | .await |
| 2640 | .context("join enrollment try-lock task")? |
| 2641 | } |
| 2642 | |
| 2643 | async fn acquire_enrollment_lock(config: &Path) -> anyhow::Result<EnrollmentLock> { |
| 2644 | let (file, lock_path) = open_enrollment_lock(config).await?; |
| 2645 | tokio::task::spawn_blocking(move || { |
| 2646 | fs2::FileExt::lock_exclusive(&file) |
| 2647 | .with_context(|| format!("lock {}", lock_path.display()))?; |
| 2648 | Ok(EnrollmentLock { _file: file }) |
| 2649 | }) |
| 2650 | .await |
| 2651 | .context("join enrollment lock task")? |
| 2652 | } |
| 2653 | |
| 2654 | async fn open_enrollment_lock(config: &Path) -> anyhow::Result<(File, PathBuf)> { |
| 2655 | let lock_path = config.with_extension("lock"); |
| 2656 | let parent = lock_path |
| 2657 | .parent() |
| 2658 | .context("managed installation lock has no parent directory")? |
| 2659 | .to_path_buf(); |
| 2660 | tokio::task::spawn_blocking(move || { |
| 2661 | std::fs::create_dir_all(&parent).with_context(|| format!("create {}", parent.display()))?; |
| 2662 | let file = File::options() |
| 2663 | .read(true) |
| 2664 | .write(true) |
| 2665 | .create(true) |
| 2666 | .truncate(false) |
| 2667 | .open(&lock_path) |
| 2668 | .with_context(|| format!("open {}", lock_path.display()))?; |
| 2669 | Ok((file, lock_path)) |
| 2670 | }) |
| 2671 | .await |
| 2672 | .context("join enrollment lock open task")? |
| 2673 | } |
| 2674 | |
| 2675 | async fn wait_for_shared_enrollment(path: &Path) -> anyhow::Result<EnrollmentLock> { |
| 2676 | loop { |
| 2677 | if let Ok(contents) = std::fs::read_to_string(path) { |
| 2678 | if let Ok(config) = serde_json::from_str::<CloudConfig>(&contents) { |
| 2679 | if config.installation_token.is_some() |
| 2680 | && (config.storage.is_some() || config.byo_storage.is_some()) |
| 2681 | { |
| 2682 | return acquire_enrollment_lock(path).await; |
| 2683 | } |
| 2684 | if let Some(pending) = config.pending_claim { |
| 2685 | if pending.expires_at_ms > current_time_ms() { |
| 2686 | println!( |
| 2687 | "\nConnect this celld installation to the Managed Control Plane:\n\n {}\n\nEnvironment: {}\n", |
| 2688 | pending.verification_uri_complete, config.environment |
| 2689 | ); |
| 2690 | return acquire_enrollment_lock(path).await; |
| 2691 | } |
| 2692 | } |
| 2693 | } |
| 2694 | } |
| 2695 | if let Some(lock) = try_acquire_enrollment_lock(path).await? { |
| 2696 | return Ok(lock); |
| 2697 | } |
| 2698 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 2699 | } |
| 2700 | } |
| 2701 | |
| 2702 | fn current_time_ms() -> u64 { |
| 2703 | std::time::SystemTime::now() |
| 2704 | .duration_since(std::time::UNIX_EPOCH) |
| 2705 | .unwrap_or_default() |
| 2706 | .as_millis() as u64 |
| 2707 | } |
| 2708 | |
| 2709 | fn normalized_control_url(value: &str) -> anyhow::Result<String> { |
| 2710 | let value = value.trim_end_matches('/'); |
| 2711 | let url = url::Url::parse(value).context("invalid control plane URL")?; |
| 2712 | if url.scheme() != "https" |
| 2713 | && !(url.scheme() == "http" && matches!(url.host_str(), Some("localhost" | "127.0.0.1"))) |
| 2714 | { |
| 2715 | return Err(anyhow!("control plane URL must use HTTPS")); |
| 2716 | } |
| 2717 | if url.path() != "/" || url.query().is_some() || url.fragment().is_some() { |
| 2718 | return Err(anyhow!( |
| 2719 | "control plane URL must not contain a path, query, or fragment" |
| 2720 | )); |
| 2721 | } |
| 2722 | Ok(value.to_string()) |
| 2723 | } |
| 2724 | |
| 2725 | fn validate_environment(value: &str) -> anyhow::Result<()> { |
| 2726 | if value.is_empty() || value.len() > 32 { |
| 2727 | return Err(anyhow!("environment must be 1–32 characters")); |
| 2728 | } |
| 2729 | let mut characters = value.chars(); |
| 2730 | if !characters |
| 2731 | .next() |
| 2732 | .is_some_and(|character| character.is_ascii_lowercase()) |
| 2733 | || !characters.all(|character| { |
| 2734 | character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-' |
| 2735 | }) |
| 2736 | { |
| 2737 | return Err(anyhow!( |
| 2738 | "environment must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens" |
| 2739 | )); |
| 2740 | } |
| 2741 | Ok(()) |
| 2742 | } |
| 2743 | |
| 2744 | fn instance_name() -> String { |
| 2745 | std::env::var("CELLD_INSTANCE_NAME").unwrap_or_else(|_| machine_hostname()) |
| 2746 | } |
| 2747 | |
| 2748 | fn machine_hostname() -> String { |
| 2749 | std::env::var("HOSTNAME") |
| 2750 | .or_else(|_| std::env::var("COMPUTERNAME")) |
| 2751 | .ok() |
| 2752 | .or_else(|| { |
| 2753 | std::process::Command::new("hostname") |
| 2754 | .output() |
| 2755 | .ok() |
| 2756 | .filter(|output| output.status.success()) |
| 2757 | .and_then(|output| String::from_utf8(output.stdout).ok()) |
| 2758 | }) |
| 2759 | .map(|value| value.trim().to_string()) |
| 2760 | .filter(|value| { |
| 2761 | !value.is_empty() |
| 2762 | && value.len() <= 100 |
| 2763 | && value.is_ascii() |
| 2764 | && !value.chars().any(char::is_control) |
| 2765 | }) |
| 2766 | .unwrap_or_else(|| "celld".to_string()) |
| 2767 | } |
| 2768 | |
| 2769 | fn print_connect_help() { |
| 2770 | println!( |
| 2771 | "Connect this celld installation to the Managed Control Plane.\n\nUSAGE:\n celld connect [--env prod] [--control-url https://celld.dev] [--force]" |
| 2772 | ); |
| 2773 | } |
| 2774 | |
| 2775 | fn print_credentials_help() { |
| 2776 | println!( |
| 2777 | "Refresh a staged Managed Control Plane credential.\n\nUSAGE:\n celld credentials refresh\n\nRunning celld processes sharing this installation automatically reload after the replacement is saved. Unix processes re-exec; other platforms exit 75 for their supervisor." |
| 2778 | ); |
| 2779 | } |
| 2780 | |
| 2781 | fn print_disconnect_help() { |
| 2782 | println!( |
| 2783 | "Revoke and disconnect this Managed Control Plane installation.\n\nUSAGE:\n celld disconnect --yes\n\nStop every celld process sharing this installation first. Other installations in the fleet are unaffected." |
| 2784 | ); |
| 2785 | } |