From b163656859da62972c2e960f68b0652b63b60224 Mon Sep 17 00:00:00 2001 From: Jean-Gabriel Gill-Couture Date: Mon, 11 May 2026 16:48:52 -0400 Subject: [PATCH 1/3] chore: cargo fmt --- brocade/src/network_operating_system.rs | 22 +++--- examples/fleet_auth_callout/src/lib.rs | 4 +- examples/fleet_load_test/src/main.rs | 5 +- examples/fleet_rpi_setup/src/main.rs | 7 +- examples/fleet_staging_install/src/main.rs | 4 +- examples/harmony_apply_deployment/src/main.rs | 4 +- examples/harmony_sso/src/main.rs | 4 +- examples/kube-rs/src/main.rs | 9 ++- examples/nats-supercluster/src/main.rs | 5 +- examples/penpot/src/main.rs | 2 - examples/zitadel/src/main.rs | 4 +- .../harmony-fleet-operator/src/controller.rs | 3 +- .../src/fleet_aggregator.rs | 8 ++ fleet/harmony-fleet-operator/src/main.rs | 18 +++++ harmony-k8s/src/domain.rs | 7 +- harmony-k8s/src/pod.rs | 7 +- harmony-k8s/src/resources.rs | 19 ++--- .../topology/k8s_anywhere/k8s_anywhere.rs | 15 ++-- harmony/src/infra/brocade.rs | 7 +- .../cert_manager/score_cert_management.rs | 2 +- harmony/src/modules/fleet/setup_score.rs | 8 +- .../src/modules/linux/ansible_configurator.rs | 35 +++------ harmony/src/modules/linux/ansible_venv.rs | 20 ++--- harmony/src/modules/linux/topology.rs | 12 +-- .../rhobs_application_monitoring_score.rs | 4 +- .../kube_prometheus/crd/crd_scrape_config.rs | 7 +- harmony/src/modules/nats/score_nats_k8s.rs | 4 +- harmony/src/modules/podman/mod.rs | 2 +- harmony/src/modules/zitadel/admin_auth.rs | 11 ++- harmony/src/modules/zitadel/mod.rs | 4 +- harmony/src/modules/zitadel/setup.rs | 57 +++++++------- harmony_agent/src/main.rs | 1 - harmony_agent/src/store/nats.rs | 19 ++--- harmony_agent/src/workflow/mod.rs | 1 - harmony_agent/src/workflow/replica.rs | 47 +++++------ harmony_assets/src/store/local.rs | 1 - harmony_cli/src/cli_reporter.rs | 19 +++-- harmony_composer/src/main.rs | 10 +-- harmony_inventory_agent/src/hwinfo.rs | 11 +-- harmony_node_readiness/src/main.rs | 1 - harmony_secret/src/store/zitadel.rs | 77 ++++++++++--------- harmony_tui/src/lib.rs | 19 ++--- harmony_tui/src/widget/score.rs | 19 ++--- nats/jwt/src/algorithm.rs | 5 +- nats/jwt/src/claims/user.rs | 4 +- opnsense-api/examples/firmware_update.rs | 7 +- opnsense-api/examples/install_and_wait.rs | 13 ++-- opnsense-api/tests/e2e_test.rs | 13 ++-- opnsense-codegen/src/codegen.rs | 7 +- opnsense-codegen/src/controller_parser.rs | 7 +- opnsense-codegen/src/lib.rs | 1 - opnsense-codegen/src/parser.rs | 41 +++++----- opnsense-config-xml/src/data/haproxy.rs | 6 +- 53 files changed, 324 insertions(+), 325 deletions(-) diff --git a/brocade/src/network_operating_system.rs b/brocade/src/network_operating_system.rs index 4e4701e3..b1e019bd 100644 --- a/brocade/src/network_operating_system.rs +++ b/brocade/src/network_operating_system.rs @@ -117,20 +117,20 @@ impl NetworkOperatingSystemClient { if let Error::CommandError(message) = &err && message.contains("switchport") - && message.contains("Cannot configure aggregator member") - { - let re = Regex::new(r"\(conf-if-([a-zA-Z]+)-([\d/]+)\)#").unwrap(); + && message.contains("Cannot configure aggregator member") + { + let re = Regex::new(r"\(conf-if-([a-zA-Z]+)-([\d/]+)\)#").unwrap(); - if let Some(caps) = re.captures(message) { - let interface_type = &caps[1]; - let port_location = &caps[2]; - let interface = format!("{interface_type} {port_location}"); + if let Some(caps) = re.captures(message) { + let interface_type = &caps[1]; + let port_location = &caps[2]; + let interface = format!("{interface_type} {port_location}"); - return Error::CommandError(format!( - "Cannot configure interface '{interface}', it is a member of a port-channel (LAG)" - )); - } + return Error::CommandError(format!( + "Cannot configure interface '{interface}', it is a member of a port-channel (LAG)" + )); } + } err } diff --git a/examples/fleet_auth_callout/src/lib.rs b/examples/fleet_auth_callout/src/lib.rs index 06234043..c2d4c9bf 100644 --- a/examples/fleet_auth_callout/src/lib.rs +++ b/examples/fleet_auth_callout/src/lib.rs @@ -430,8 +430,8 @@ pub async fn deploy_zitadel(topology: &K8sAnywhereTopology) -> Result<()> { // audience validation fails with `Errors.Internal` (the assertion // `aud` doesn't match the chart-default issuer at port 80). external_port: Some(HTTP_PORT), - ..Default::default() - }; + ..Default::default() + }; zitadel .interpret(&Inventory::autoload(), topology) .await diff --git a/examples/fleet_load_test/src/main.rs b/examples/fleet_load_test/src/main.rs index 7feeb232..1cfd09e7 100644 --- a/examples/fleet_load_test/src/main.rs +++ b/examples/fleet_load_test/src/main.rs @@ -28,10 +28,7 @@ use anyhow::{Context, Result}; use async_nats::jetstream::{self, kv}; use chrono::Utc; use clap::Parser; -use harmony::modules::fleet::operator::{ - Deployment, DeploymentSpec, Rollout, - RolloutStrategy, -}; +use harmony::modules::fleet::operator::{Deployment, DeploymentSpec, Rollout, RolloutStrategy}; use harmony::modules::podman::{PodmanService, PodmanV0Score, ReconcileScore}; use harmony_reconciler_contracts::{ BUCKET_DEVICE_HEARTBEAT, BUCKET_DEVICE_INFO, BUCKET_DEVICE_STATE, DeploymentName, diff --git a/examples/fleet_rpi_setup/src/main.rs b/examples/fleet_rpi_setup/src/main.rs index 0ca05c3b..5cbe0df3 100644 --- a/examples/fleet_rpi_setup/src/main.rs +++ b/examples/fleet_rpi_setup/src/main.rs @@ -264,8 +264,9 @@ fn parse_labels(raw: &str) -> Result> fn expand_tilde(p: &std::path::Path) -> PathBuf { let s = p.to_string_lossy(); if let Some(rest) = s.strip_prefix("~/") - && let Ok(home) = std::env::var("HOME") { - return PathBuf::from(home).join(rest); - } + && let Ok(home) = std::env::var("HOME") + { + return PathBuf::from(home).join(rest); + } p.to_path_buf() } diff --git a/examples/fleet_staging_install/src/main.rs b/examples/fleet_staging_install/src/main.rs index 4791438a..0d8ab3c5 100644 --- a/examples/fleet_staging_install/src/main.rs +++ b/examples/fleet_staging_install/src/main.rs @@ -255,9 +255,7 @@ async fn main() -> Result<()> { })? .clone(); log::info!("[2/6] project_id resolved: {project_id}"); - log::info!( - "[2/6] device-code client_id for '{cli_app_name}' resolved: {cli_client_id}" - ); + log::info!("[2/6] device-code client_id for '{cli_app_name}' resolved: {cli_client_id}"); // ---- 3. Issuer NKey + auth callout pieces --------------------------- // The callout signs user JWTs with this account NKey. NATS server diff --git a/examples/harmony_apply_deployment/src/main.rs b/examples/harmony_apply_deployment/src/main.rs index f82d5a1f..6c46cb49 100644 --- a/examples/harmony_apply_deployment/src/main.rs +++ b/examples/harmony_apply_deployment/src/main.rs @@ -38,11 +38,11 @@ use anyhow::{Context, Result}; use clap::Parser; -use harmony::modules::podman::{PodmanService, PodmanV0Score, ReconcileScore}; -use harmony::topology::{EnvVar, RestartPolicy, VolumeMount}; use harmony::modules::fleet::operator::crd::{ Deployment, DeploymentSpec, Rollout, RolloutStrategy, }; +use harmony::modules::podman::{PodmanService, PodmanV0Score, ReconcileScore}; +use harmony::topology::{EnvVar, RestartPolicy, VolumeMount}; use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector; use kube::Client; use kube::api::{Api, DeleteParams, Patch, PatchParams}; diff --git a/examples/harmony_sso/src/main.rs b/examples/harmony_sso/src/main.rs index 3f881729..8bd09a59 100644 --- a/examples/harmony_sso/src/main.rs +++ b/examples/harmony_sso/src/main.rs @@ -119,8 +119,8 @@ async fn deploy_zitadel(k3d: &K3d) -> anyhow::Result<()> { zitadel_version: "v4.12.1".to_string(), external_secure: false, external_port: None, - ..Default::default() - }; + ..Default::default() + }; let topology = create_topology(k3d); topology diff --git a/examples/kube-rs/src/main.rs b/examples/kube-rs/src/main.rs index 71760323..e9851ca9 100644 --- a/examples/kube-rs/src/main.rs +++ b/examples/kube-rs/src/main.rs @@ -67,10 +67,11 @@ async fn main() { Err(e) => { println!("Error creating deployment {}", e); if let kube::Error::Api(error_response) = &e - && error_response.code == http::StatusCode::CONFLICT.as_u16() { - println!("Already exists"); - return; - } + && error_response.code == http::StatusCode::CONFLICT.as_u16() + { + println!("Already exists"); + return; + } panic!("{}", e) } }; diff --git a/examples/nats-supercluster/src/main.rs b/examples/nats-supercluster/src/main.rs index 08d8eb7d..eb88b15e 100644 --- a/examples/nats-supercluster/src/main.rs +++ b/examples/nats-supercluster/src/main.rs @@ -253,10 +253,7 @@ async fn create_nats_certs( debug!("creating issuer '{}'", self_signed_issuer_name); topology - .create_issuer( - self_signed_issuer_name.to_string(), - self_signed_cert_config, - ) + .create_issuer(self_signed_issuer_name.to_string(), self_signed_cert_config) .await?; debug!("creating certificate {root_ca_cert_name}"); diff --git a/examples/penpot/src/main.rs b/examples/penpot/src/main.rs index 315ef55b..6c24972a 100644 --- a/examples/penpot/src/main.rs +++ b/examples/penpot/src/main.rs @@ -1,5 +1,3 @@ - - #[tokio::main] async fn main() { // let mut chart_values = HashMap::new(); diff --git a/examples/zitadel/src/main.rs b/examples/zitadel/src/main.rs index 7b492d48..a115f3b1 100644 --- a/examples/zitadel/src/main.rs +++ b/examples/zitadel/src/main.rs @@ -9,8 +9,8 @@ async fn main() { zitadel_version: "v4.12.1".to_string(), external_secure: true, external_port: None, - ..Default::default() - }; + ..Default::default() + }; harmony_cli::run( Inventory::autoload(), diff --git a/fleet/harmony-fleet-operator/src/controller.rs b/fleet/harmony-fleet-operator/src/controller.rs index 3e202ca3..2f54180a 100644 --- a/fleet/harmony-fleet-operator/src/controller.rs +++ b/fleet/harmony-fleet-operator/src/controller.rs @@ -28,7 +28,6 @@ use std::time::Duration; use async_nats::jetstream::kv::Store; use futures_util::StreamExt; use harmony_reconciler_contracts::DeploymentName; -use kube::runtime::Controller; use kube::runtime::controller::Action; use kube::runtime::finalizer::{Event as FinalizerEvent, finalizer}; use kube::runtime::watcher::Config as WatcherConfig; @@ -60,7 +59,7 @@ pub async fn run(client: Client, kv: Store) -> anyhow::Result<()> { let ctx = Arc::new(Context { client, kv }); tracing::info!("starting Deployment controller"); - Controller::new(api, WatcherConfig::default()) + kube::runtime::controller::Controller::new(api, WatcherConfig::default()) .run(reconcile, error_policy, ctx) .for_each(|res| async move { match res { diff --git a/fleet/harmony-fleet-operator/src/fleet_aggregator.rs b/fleet/harmony-fleet-operator/src/fleet_aggregator.rs index cedf157a..9eec10df 100644 --- a/fleet/harmony-fleet-operator/src/fleet_aggregator.rs +++ b/fleet/harmony-fleet-operator/src/fleet_aggregator.rs @@ -36,6 +36,7 @@ use tokio::sync::Mutex; use harmony::modules::fleet::operator::{ AggregateLastError, Deployment, DeploymentAggregate, Device, }; +use tracing::warn; const PATCH_TICK: Duration = Duration::from_secs(1); @@ -353,6 +354,7 @@ fn matching_deployment_keys(state: &FleetState, deployment: &DeploymentName) -> // Deployment CR watcher // --------------------------------------------------------------------------- +/// Watch Deployment CRD in k8s API and update nats desired state accordingly async fn run_deployment_watcher( api: Api, state: SharedFleetState, @@ -457,6 +459,10 @@ async fn on_deployment_delete(state: &SharedFleetState, desired: &Store, cr: Dep // Device CR watcher // --------------------------------------------------------------------------- +/// Watch k8s Device CRD and adjust desired state. +/// +/// For example, if a device adds or deletes a label, its desired state will contain deployments matching +/// the device's new set of labels. async fn run_device_watcher( api: Api, state: SharedFleetState, @@ -611,9 +617,11 @@ async fn seed_owned_targets(bucket: &Store, state: &SharedFleetState) -> anyhow: // no namespace — names are globally unique at this layer — // which is exactly why `owned_targets` keys by DeploymentName. let Some((device, deployment)) = key.split_once('.') else { + warn!("Could not read device.deployment for key {key}"); continue; }; let Ok(deployment_name) = DeploymentName::try_new(deployment) else { + warn!("Invalid deployment name for key {key}"); continue; }; guard diff --git a/fleet/harmony-fleet-operator/src/main.rs b/fleet/harmony-fleet-operator/src/main.rs index 0d175f7e..c54b88fa 100644 --- a/fleet/harmony-fleet-operator/src/main.rs +++ b/fleet/harmony-fleet-operator/src/main.rs @@ -116,6 +116,24 @@ async fn main() -> Result<()> { Ok(()) } } + + // TODO + // Launch a web server with frontend and possibly API. This frontend logs in using zitadel SSO + // then based on the user's credentials (check if fleet admin role), allow the user to view nats + // and k8s states. + // + // First page to develop it a dashboard with aggregated numbers for devices in each state + // (pending, healthy, stale (when no neetwork connection in over x minutes?), etc and aggregated deployment + // information (number of deployments, number in each state, etc). + // + // This frontend should be written in a separate crate but be initialized here (if possible? + // maybe cirtular dependency problem, in which case just write it in a subfolder of the opeartor + // itself). + // + // This frontend should leverage our existing data structures for the operator. + // + // I am open to using almost any rust web framework, my own default is leptos + // do this in app.rs, I want to cleanup main.rs as much as possible } async fn run(nats_url: &str, bucket: &str, credentials_toml: &str) -> Result<()> { diff --git a/harmony-k8s/src/domain.rs b/harmony-k8s/src/domain.rs index 9f03023e..ce2f3340 100644 --- a/harmony-k8s/src/domain.rs +++ b/harmony-k8s/src/domain.rs @@ -20,9 +20,10 @@ impl K8sClient { let distribution = self.get_k8s_distribution().await?; if matches!(distribution, KubernetesDistribution::OpenshiftFamily) - && let Some(domain) = self.try_openshift_ingress_domain().await? { - return Ok(format!("{service}.{domain}")); - } + && let Some(domain) = self.try_openshift_ingress_domain().await? + { + return Ok(format!("{service}.{domain}")); + } if let Some(domain) = self.try_nginx_lb_domain().await? { return Ok(format!("{service}.{domain}")); diff --git a/harmony-k8s/src/pod.rs b/harmony-k8s/src/pod.rs index 39984cde..5866b538 100644 --- a/harmony-k8s/src/pod.rs +++ b/harmony-k8s/src/pod.rs @@ -33,9 +33,10 @@ impl K8sClient { loop { if let Some(p) = self.get_pod(pod_name, namespace).await? && let Some(phase) = p.status.and_then(|s| s.phase) - && phase.to_lowercase() == "running" { - return Ok(()); - } + && phase.to_lowercase() == "running" + { + return Ok(()); + } if elapsed >= timeout_secs { return Err(Error::Discovery(DiscoveryError::MissingResource(format!( "Pod '{}' in '{}' did not become ready within {timeout_secs}s", diff --git a/harmony-k8s/src/resources.rs b/harmony-k8s/src/resources.rs index 4ae51962..d0d5562c 100644 --- a/harmony-k8s/src/resources.rs +++ b/harmony-k8s/src/resources.rs @@ -44,9 +44,9 @@ impl K8sClient { && conds .iter() .any(|c| c.type_ == "Available" && c.status == "True") - { - return Ok(true); - } + { + return Ok(true); + } } Ok(false) } @@ -104,9 +104,9 @@ impl K8sClient { .as_ref() .and_then(|s| s.template.spec.as_ref()) .and_then(|s| s.service_account_name.clone()) - { - return Ok(Some(sa)); - } + { + return Ok(Some(sa)); + } Ok(None) } @@ -395,9 +395,10 @@ impl K8sClient { match api.get_opt(name).await? { Some(ns) => { if let Some(status) = ns.status - && status.phase == Some("Active".to_string()) { - return Ok(()); - } + && status.phase == Some("Active".to_string()) + { + return Ok(()); + } } None => { return Err(Error::Api(ErrorResponse { diff --git a/harmony/src/domain/topology/k8s_anywhere/k8s_anywhere.rs b/harmony/src/domain/topology/k8s_anywhere/k8s_anywhere.rs index fbefab6c..7928519a 100644 --- a/harmony/src/domain/topology/k8s_anywhere/k8s_anywhere.rs +++ b/harmony/src/domain/topology/k8s_anywhere/k8s_anywhere.rs @@ -971,8 +971,7 @@ impl K8sAnywhereTopology { // early `return Ok(PreparationOutcome::Noop)`. Until that // dead branch is either deleted or wired up, mark the param // unused-but-named so the inner reference still resolves. - #[allow(unused_variables)] - sender: &RHOBObservability, + #[allow(unused_variables)] sender: &RHOBObservability, ) -> Result { let status = Command::new("sh") .args(["-c", "kubectl get crd -A | grep -i rhobs"]) @@ -992,13 +991,13 @@ impl K8sAnywhereTopology { // sketch of the intended install path. #[allow(unreachable_code)] { - debug!("installing cluster observability operator"); - todo!(); - let op_score = - prometheus_operator_helm_chart_score(sender.namespace.clone()); - let result = op_score.interpret(&Inventory::empty(), self).await; + debug!("installing cluster observability operator"); + todo!(); + let op_score = + prometheus_operator_helm_chart_score(sender.namespace.clone()); + let result = op_score.interpret(&Inventory::empty(), self).await; - return match result { + return match result { Ok(outcome) => match outcome.status { InterpretStatus::SUCCESS => Ok(PreparationOutcome::Success { details: "installed cluster observability operator".into(), diff --git a/harmony/src/infra/brocade.rs b/harmony/src/infra/brocade.rs index 3557243e..3d8623f2 100644 --- a/harmony/src/infra/brocade.rs +++ b/harmony/src/infra/brocade.rs @@ -391,7 +391,12 @@ mod tests { todo!() } - async fn enable_snmp(&self, _user_name: &str, _auth: &str, _des: &str) -> Result<(), Error> { + async fn enable_snmp( + &self, + _user_name: &str, + _auth: &str, + _des: &str, + ) -> Result<(), Error> { todo!() } } diff --git a/harmony/src/modules/cert_manager/score_cert_management.rs b/harmony/src/modules/cert_manager/score_cert_management.rs index 0a748113..ff5778e2 100644 --- a/harmony/src/modules/cert_manager/score_cert_management.rs +++ b/harmony/src/modules/cert_manager/score_cert_management.rs @@ -6,7 +6,7 @@ use crate::{ data::Version, interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome}, inventory::Inventory, - modules::cert_manager::capability::{CertificateManagement}, + modules::cert_manager::capability::CertificateManagement, score::Score, topology::Topology, }; diff --git a/harmony/src/modules/fleet/setup_score.rs b/harmony/src/modules/fleet/setup_score.rs index 65926114..1069614b 100644 --- a/harmony/src/modules/fleet/setup_score.rs +++ b/harmony/src/modules/fleet/setup_score.rs @@ -21,9 +21,7 @@ use crate::domain::topology::{ PackageInstaller, SystemdManager, SystemdScope, SystemdUnitSpec, Topology, UnixUserManager, UserSpec, }; -use crate::modules::zitadel::admin_auth::{ - self, ADMIN_API_SCOPES, DeviceCodeFlowConfig, -}; +use crate::modules::zitadel::admin_auth::{self, ADMIN_API_SCOPES, DeviceCodeFlowConfig}; use crate::modules::zitadel::setup::{ZitadelScheme, ZitadelSetupScore, mint_device_credentials}; use crate::score::Score; @@ -341,9 +339,7 @@ async fn resolve_zitadel_enroll( let admin_token = match admin { AdminAuth::Token(t) => t, AdminAuth::Sso { client_id } => { - info!( - "[FleetSetup/{device_id}] Zitadel SSO sign-in required (client_id={client_id})" - ); + info!("[FleetSetup/{device_id}] Zitadel SSO sign-in required (client_id={client_id})"); admin_auth::device_code_login(&DeviceCodeFlowConfig { host: host.clone(), scheme, diff --git a/harmony/src/modules/linux/ansible_configurator.rs b/harmony/src/modules/linux/ansible_configurator.rs index c7a0ccdb..57b0f0a1 100644 --- a/harmony/src/modules/linux/ansible_configurator.rs +++ b/harmony/src/modules/linux/ansible_configurator.rs @@ -77,9 +77,7 @@ async fn host_exec( stdin: Option<&str>, ) -> Result { match conn { - AnsibleConnection::Ssh { host, creds } => { - ssh_exec(*host, creds, command_line, stdin).await - } + AnsibleConnection::Ssh { host, creds } => ssh_exec(*host, creds, command_line, stdin).await, AnsibleConnection::Local { .. } => { use tokio::io::AsyncWriteExt; let mut cmd = Command::new("sh"); @@ -118,10 +116,7 @@ async fn host_exec( /// enable-linger`) is up and accepting bus connections. Times out /// after 5s with a clear error so a stuck logind doesn't hang the /// whole score forever. -async fn wait_for_user_bus( - conn: &AnsibleConnection<'_>, - user: &str, -) -> Result<(), ExecutorError> { +async fn wait_for_user_bus(conn: &AnsibleConnection<'_>, user: &str) -> Result<(), ExecutorError> { let id_out = host_exec(conn, &format!("id -u {user}"), None) .await? .into_successful()?; @@ -221,14 +216,8 @@ impl AnsibleHostConfigurator { spec: &UserSpec, ) -> Result { let args = AnsibleUserArgs::from(spec); - self.run_module( - conn, - "ansible.builtin.user", - to_value(&args)?, - true, - None, - ) - .await + self.run_module(conn, "ansible.builtin.user", to_value(&args)?, true, None) + .await } pub async fn ensure_file( @@ -261,14 +250,8 @@ impl AnsibleHostConfigurator { } let args = AnsibleCopyArgs::from(spec); - self.run_module( - conn, - "ansible.builtin.copy", - to_value(&args)?, - true, - None, - ) - .await + self.run_module(conn, "ansible.builtin.copy", to_value(&args)?, true, None) + .await } pub async fn fetch_file( @@ -390,7 +373,8 @@ impl AnsibleHostConfigurator { // logind needs to actually start the user manager; every // subsequent `systemctl --user …` then fails with "Failed // to connect to bus". `loginctl enable-linger` does both. - let check = host_exec(conn, + let check = host_exec( + conn, &format!("test -e /var/lib/systemd/linger/{user}"), None, ) @@ -440,7 +424,8 @@ impl AnsibleHostConfigurator { // and `is-active --quiet` exit 0 only when the unit is // both wanted and running, which is exactly the // post-condition `enable --now` establishes. - let probe = host_sudo_exec(conn, + let probe = host_sudo_exec( + conn, &format!( "{env_prefix} sh -c 'systemctl --user is-enabled --quiet {unit} \ && systemctl --user is-active --quiet {unit}'" diff --git a/harmony/src/modules/linux/ansible_venv.rs b/harmony/src/modules/linux/ansible_venv.rs index 9bb4a037..1cb7327b 100644 --- a/harmony/src/modules/linux/ansible_venv.rs +++ b/harmony/src/modules/linux/ansible_venv.rs @@ -163,20 +163,12 @@ async fn create_venv(python: &PathBuf, venv_dir: &PathBuf) -> Result<(), String> /// prints a "this is unstable" CLI warning and tries to interact; /// apt-get is the script-friendly variant. async fn apt_install_python3_venv() -> Result<(), String> { - run(Command::new("sudo").args([ - "apt-get", - "update", - ])) - .await - .map_err(|e| format!("apt-get update: {e}"))?; - run(Command::new("sudo").args([ - "apt-get", - "install", - "-y", - "python3-venv", - ])) - .await - .map_err(|e| format!("apt-get install python3-venv: {e}")) + run(Command::new("sudo").args(["apt-get", "update"])) + .await + .map_err(|e| format!("apt-get update: {e}"))?; + run(Command::new("sudo").args(["apt-get", "install", "-y", "python3-venv"])) + .await + .map_err(|e| format!("apt-get install python3-venv: {e}")) } async fn run(cmd: &mut Command) -> Result<(), String> { diff --git a/harmony/src/modules/linux/topology.rs b/harmony/src/modules/linux/topology.rs index d7d6ce7b..64fc717e 100644 --- a/harmony/src/modules/linux/topology.rs +++ b/harmony/src/modules/linux/topology.rs @@ -182,9 +182,7 @@ impl FileDelivery for LinuxHostTopology { #[async_trait] impl FileFetcher for LinuxHostTopology { async fn fetch_file(&self, path: &str) -> Result, ExecutorError> { - self.configurator - .fetch_file(&self.connection(), path) - .await + self.configurator.fetch_file(&self.connection(), path).await } } @@ -268,7 +266,9 @@ impl PackageInstaller for LinuxLocalhostTopology { #[async_trait] impl FileDelivery for LinuxLocalhostTopology { async fn ensure_file(&self, spec: &FileSpec) -> Result { - self.configurator.ensure_file(&self.connection(), spec).await + self.configurator + .ensure_file(&self.connection(), spec) + .await } } @@ -282,7 +282,9 @@ impl FileFetcher for LinuxLocalhostTopology { #[async_trait] impl UnixUserManager for LinuxLocalhostTopology { async fn ensure_user(&self, spec: &UserSpec) -> Result { - self.configurator.ensure_user(&self.connection(), spec).await + self.configurator + .ensure_user(&self.connection(), spec) + .await } async fn ensure_linger(&self, user: &str) -> Result { diff --git a/harmony/src/modules/monitoring/application_monitoring/rhobs_application_monitoring_score.rs b/harmony/src/modules/monitoring/application_monitoring/rhobs_application_monitoring_score.rs index 00e75974..a80b6ed0 100644 --- a/harmony/src/modules/monitoring/application_monitoring/rhobs_application_monitoring_score.rs +++ b/harmony/src/modules/monitoring/application_monitoring/rhobs_application_monitoring_score.rs @@ -9,9 +9,7 @@ use crate::{ inventory::Inventory, modules::{ application::Application, - monitoring::kube_prometheus::crd::{ - rhob_alertmanager_config::RHOBObservability, - }, + monitoring::kube_prometheus::crd::rhob_alertmanager_config::RHOBObservability, prometheus::prometheus::PrometheusMonitoring, }, score::Score, diff --git a/harmony/src/modules/monitoring/kube_prometheus/crd/crd_scrape_config.rs b/harmony/src/modules/monitoring/kube_prometheus/crd/crd_scrape_config.rs index be708d4f..20ad9836 100644 --- a/harmony/src/modules/monitoring/kube_prometheus/crd/crd_scrape_config.rs +++ b/harmony/src/modules/monitoring/kube_prometheus/crd/crd_scrape_config.rs @@ -1,13 +1,8 @@ - use kube::CustomResource; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::{ - modules::monitoring::kube_prometheus::crd::{ - crd_prometheuses::LabelSelector, - } -}; +use crate::modules::monitoring::kube_prometheus::crd::crd_prometheuses::LabelSelector; #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] #[kube( diff --git a/harmony/src/modules/nats/score_nats_k8s.rs b/harmony/src/modules/nats/score_nats_k8s.rs index d371140c..e3865927 100644 --- a/harmony/src/modules/nats/score_nats_k8s.rs +++ b/harmony/src/modules/nats/score_nats_k8s.rs @@ -664,7 +664,9 @@ mod tests { .split("FLEET:") .nth(1) .expect("FLEET account block present in rendered values"); - let next_account = fleet_block.find("\n SYS:").unwrap_or(fleet_block.len()); + let next_account = fleet_block + .find("\n SYS:") + .unwrap_or(fleet_block.len()); let fleet_only = &fleet_block[..next_account]; assert!( fleet_only.contains("jetstream: enabled"), diff --git a/harmony/src/modules/podman/mod.rs b/harmony/src/modules/podman/mod.rs index 7d449c30..f193d9d8 100644 --- a/harmony/src/modules/podman/mod.rs +++ b/harmony/src/modules/podman/mod.rs @@ -2,7 +2,7 @@ mod interpret; mod score; mod topology; -pub use interpret::PodmanV0Interpret; pub use crate::topology::EnvVar; +pub use interpret::PodmanV0Interpret; pub use score::{PodmanService, PodmanV0Score, ReconcileScore}; pub use topology::PodmanTopology; diff --git a/harmony/src/modules/zitadel/admin_auth.rs b/harmony/src/modules/zitadel/admin_auth.rs index 3606d701..236858db 100644 --- a/harmony/src/modules/zitadel/admin_auth.rs +++ b/harmony/src/modules/zitadel/admin_auth.rs @@ -118,7 +118,10 @@ fn http_client(skip_tls: bool) -> Result { .map_err(|e| DeviceCodeError::Http(format!("build client: {e}"))) } -fn add_host_header(rb: reqwest::RequestBuilder, cfg: &DeviceCodeFlowConfig) -> reqwest::RequestBuilder { +fn add_host_header( + rb: reqwest::RequestBuilder, + cfg: &DeviceCodeFlowConfig, +) -> reqwest::RequestBuilder { if cfg.endpoint.is_some() { rb.header("Host", &cfg.host) } else { @@ -133,8 +136,10 @@ pub async fn device_code_login(cfg: &DeviceCodeFlowConfig) -> Result Result, String> { let resp = self - .post(client, &format!( - "/management/v1/projects/{project_id}/apps/_search" - )) + .post( + client, + &format!("/management/v1/projects/{project_id}/apps/_search"), + ) .bearer_auth(pat) .json(&serde_json::json!({})) .send() @@ -746,7 +745,10 @@ impl ZitadelSetupInterpret { app_name: &str, ) -> Result { let resp = self - .post(client, &format!("/management/v1/projects/{project_id}/apps/oidc")) + .post( + client, + &format!("/management/v1/projects/{project_id}/apps/oidc"), + ) .bearer_auth(pat) .json(&serde_json::json!({ "name": app_name, @@ -829,7 +831,10 @@ impl ZitadelSetupInterpret { app_name: &str, ) -> Result<(), String> { let resp = self - .post(client, &format!("/management/v1/projects/{project_id}/apps/api")) + .post( + client, + &format!("/management/v1/projects/{project_id}/apps/api"), + ) .bearer_auth(pat) .json(&serde_json::json!({ "name": app_name, @@ -860,9 +865,10 @@ impl ZitadelSetupInterpret { app_name: &str, ) -> Result { let resp = self - .post(client, &format!( - "/management/v1/projects/{project_id}/apps/_search" - )) + .post( + client, + &format!("/management/v1/projects/{project_id}/apps/_search"), + ) .bearer_auth(pat) .json(&serde_json::json!({})) .send() @@ -920,9 +926,10 @@ impl ZitadelSetupInterpret { role_key: &str, ) -> Result { let resp = self - .post(client, &format!( - "/management/v1/projects/{project_id}/roles/_search" - )) + .post( + client, + &format!("/management/v1/projects/{project_id}/roles/_search"), + ) .bearer_auth(pat) .json(&serde_json::json!({})) .send() @@ -957,7 +964,10 @@ impl ZitadelSetupInterpret { } let resp = self - .post(client, &format!("/management/v1/projects/{project_id}/roles")) + .post( + client, + &format!("/management/v1/projects/{project_id}/roles"), + ) .bearer_auth(pat) .json(&body) .send() @@ -1570,7 +1580,10 @@ mod tests { let mut s = score("zitadel.public"); s.endpoint = Some("http://127.0.0.1:8080/".to_string()); let i = interp(s); - assert_eq!(i.api_url("/management/v1/x"), "http://127.0.0.1:8080/management/v1/x"); + assert_eq!( + i.api_url("/management/v1/x"), + "http://127.0.0.1:8080/management/v1/x" + ); } #[test] @@ -1579,11 +1592,7 @@ mod tests { // would be redundant and risks mismatching `:443` literal. let direct = interp(score("zitadel.example.com")); let req = direct - .request( - &reqwest::Client::new(), - reqwest::Method::POST, - "/x", - ) + .request(&reqwest::Client::new(), reqwest::Method::POST, "/x") .build() .unwrap(); assert_eq!(req.headers().get("Host"), None); @@ -1595,11 +1604,7 @@ mod tests { s.endpoint = Some("http://127.0.0.1:8080".to_string()); let proxied = interp(s); let req = proxied - .request( - &reqwest::Client::new(), - reqwest::Method::POST, - "/x", - ) + .request(&reqwest::Client::new(), reqwest::Method::POST, "/x") .build() .unwrap(); assert_eq!( diff --git a/harmony_agent/src/main.rs b/harmony_agent/src/main.rs index 4851dd97..3071c343 100644 --- a/harmony_agent/src/main.rs +++ b/harmony_agent/src/main.rs @@ -1,6 +1,5 @@ use std::{sync::Arc, time::Duration}; - use crate::{ agent::AgentRole, store::{ChaosKvStore, InMemoryKvStore, NatsKvStore}, diff --git a/harmony_agent/src/store/nats.rs b/harmony_agent/src/store/nats.rs index 01f9e19b..a136c5e5 100644 --- a/harmony_agent/src/store/nats.rs +++ b/harmony_agent/src/store/nats.rs @@ -53,9 +53,7 @@ impl KvStore for NatsKvStore { .await .map_err(|e| { error!("NATS get failed for key '{}': {}", key, e); - KvStoreError::Disconnect(std::io::Error::other( - e.to_string(), - )) + KvStoreError::Disconnect(std::io::Error::other(e.to_string())) })?; if entry.is_none() { @@ -88,9 +86,7 @@ impl KvStore for NatsKvStore { async fn get(&self, key: &str) -> Result { let entry = self.store.entry(key).await.map_err(|e| { error!("NATS get failed for key '{}': {}", key, e); - KvStoreError::Disconnect(std::io::Error::other( - e.to_string(), - )) + KvStoreError::Disconnect(std::io::Error::other(e.to_string())) })?; if entry.is_none() { @@ -126,10 +122,7 @@ impl KvStore for NatsKvStore { value: Value, expected_sequence: u64, ) -> Result { - trace!( - "Nats set strict {key} (#{expected_sequence}) : {}", - value - ); + trace!("Nats set strict {key} (#{expected_sequence}) : {}", value); let bytes = serde_json::to_vec(&value).map_err(|e| KvStoreError::DeserializationFailed { deserialization_error: e.to_string(), @@ -169,9 +162,9 @@ impl From for KvStoreError { async_nats::jetstream::kv::UpdateErrorKind::WrongLastRevision => { KvStoreError::WrongLastRevision } - async_nats::jetstream::kv::UpdateErrorKind::Other => KvStoreError::Disconnect( - std::io::Error::other("NATS update error"), - ), + async_nats::jetstream::kv::UpdateErrorKind::Other => { + KvStoreError::Disconnect(std::io::Error::other("NATS update error")) + } } } } diff --git a/harmony_agent/src/workflow/mod.rs b/harmony_agent/src/workflow/mod.rs index e6e15600..f1ff0e05 100644 --- a/harmony_agent/src/workflow/mod.rs +++ b/harmony_agent/src/workflow/mod.rs @@ -1,4 +1,3 @@ - use crate::agent::AgentConfig; use async_trait::async_trait; diff --git a/harmony_agent/src/workflow/replica.rs b/harmony_agent/src/workflow/replica.rs index a7079828..63c7fc50 100644 --- a/harmony_agent/src/workflow/replica.rs +++ b/harmony_agent/src/workflow/replica.rs @@ -119,33 +119,34 @@ impl ReplicaWorkflow { async fn is_primary_stale(&mut self) -> bool { if let Some(my_hb) = &self.last_my_heartbeat && let Some(my_metadata) = &my_hb.metadata - && let Some(primary_hb_ref) = self.last_primary_heartbeat.as_ref() { - let primary_hb = primary_hb_ref.read().await; - if let Some(primary_metadata) = &primary_hb.metadata { - // Calculate time difference: replica_timestamp - primary_timestamp - let time_diff_ms = my_metadata - .timestamp - .saturating_sub(primary_metadata.timestamp); - let failover_timeout_ms = self.failover_timeout.as_millis() as u64; + && let Some(primary_hb_ref) = self.last_primary_heartbeat.as_ref() + { + let primary_hb = primary_hb_ref.read().await; + if let Some(primary_metadata) = &primary_hb.metadata { + // Calculate time difference: replica_timestamp - primary_timestamp + let time_diff_ms = my_metadata + .timestamp + .saturating_sub(primary_metadata.timestamp); + let failover_timeout_ms = self.failover_timeout.as_millis() as u64; - trace!( - "Staleness check: my_ts={}, primary_ts={}, diff={}ms, timeout={}ms", - my_metadata.timestamp, - primary_metadata.timestamp, - time_diff_ms, - failover_timeout_ms - ); + trace!( + "Staleness check: my_ts={}, primary_ts={}, diff={}ms, timeout={}ms", + my_metadata.timestamp, + primary_metadata.timestamp, + time_diff_ms, + failover_timeout_ms + ); - if time_diff_ms > failover_timeout_ms { - info!( - "Primary heartbeat stale ({}ms > {}ms), attempting promotion", - time_diff_ms, failover_timeout_ms - ); + if time_diff_ms > failover_timeout_ms { + info!( + "Primary heartbeat stale ({}ms > {}ms), attempting promotion", + time_diff_ms, failover_timeout_ms + ); - return true; - } - } + return true; } + } + } false } } diff --git a/harmony_assets/src/store/local.rs b/harmony_assets/src/store/local.rs index 2d7c00dc..0a6486a4 100644 --- a/harmony_assets/src/store/local.rs +++ b/harmony_assets/src/store/local.rs @@ -139,7 +139,6 @@ impl AssetStore for LocalStore { #[cfg(test)] mod tests { use super::*; - #[test] fn local_store_default_uses_cache_dir() { diff --git a/harmony_cli/src/cli_reporter.rs b/harmony_cli/src/cli_reporter.rs index 1cd0d0cd..8682aa68 100644 --- a/harmony_cli/src/cli_reporter.rs +++ b/harmony_cli/src/cli_reporter.rs @@ -45,17 +45,16 @@ pub fn init() { } => { details.extend(feature_details.clone()); } - HarmonyEvent::HarmonyFinished - if !details.is_empty() => { - println!( - "\n{} All done! Here's a few info for you:", - theme::EMOJI_SUMMARY - ); - for detail in details.iter() { - println!("- {detail}"); - } - println!(); + HarmonyEvent::HarmonyFinished if !details.is_empty() => { + println!( + "\n{} All done! Here's a few info for you:", + theme::EMOJI_SUMMARY + ); + for detail in details.iter() { + println!("- {detail}"); } + println!(); + } _ => {} }; } diff --git a/harmony_composer/src/main.rs b/harmony_composer/src/main.rs index 5af1d294..e2005b8b 100644 --- a/harmony_composer/src/main.rs +++ b/harmony_composer/src/main.rs @@ -309,11 +309,11 @@ async fn compile_cargo(platform: String, harmony_location: String) -> Result { - debug!("{:?}", artifact); - artifacts.push(artifact); - } + .manifest_path => + { + debug!("{:?}", artifact); + artifacts.push(artifact); + } Message::BuildScriptExecuted(_script) => (), Message::BuildFinished(finished) => { debug!("{:?}", finished); diff --git a/harmony_inventory_agent/src/hwinfo.rs b/harmony_inventory_agent/src/hwinfo.rs index fd27956d..3e814cc8 100644 --- a/harmony_inventory_agent/src/hwinfo.rs +++ b/harmony_inventory_agent/src/hwinfo.rs @@ -831,8 +831,8 @@ impl PhysicalHost { Ok("Ramdisk".to_string()) } else { // Try to determine from device path - let subsystem = Self::read_sysfs_string(&device_path.join("device/subsystem")) - .unwrap_or_default(); + let subsystem = + Self::read_sysfs_string(&device_path.join("device/subsystem")).unwrap_or_default(); Ok(subsystem .split('/') .next_back() @@ -857,9 +857,10 @@ impl PhysicalHost { for line in stdout.lines() { if line.contains("SMART overall-health self-assessment") - && let Some(status) = line.split(':').nth(1) { - return Ok(Some(status.trim().to_string())); - } + && let Some(status) = line.split(':').nth(1) + { + return Ok(Some(status.trim().to_string())); + } } Ok(None) diff --git a/harmony_node_readiness/src/main.rs b/harmony_node_readiness/src/main.rs index 6a6e1d4a..c59f3385 100644 --- a/harmony_node_readiness/src/main.rs +++ b/harmony_node_readiness/src/main.rs @@ -263,7 +263,6 @@ async fn main() -> std::io::Result<()> { #[cfg(test)] mod tests { use super::*; - #[test] fn parse_checks_defaults_to_node_ready() { diff --git a/harmony_secret/src/store/zitadel.rs b/harmony_secret/src/store/zitadel.rs index 5c1dad17..c549bb23 100644 --- a/harmony_secret/src/store/zitadel.rs +++ b/harmony_secret/src/store/zitadel.rs @@ -163,10 +163,11 @@ impl ZitadelOidcAuth { pub async fn authenticate(&self) -> Result { if let Ok(session) = load_session() - && !session.is_expired() { - info!("ZITADEL_OIDC: Using cached session"); - return Ok(session); - } + && !session.is_expired() + { + info!("ZITADEL_OIDC: Using cached session"); + return Ok(session); + } info!("ZITADEL_OIDC: Starting device authorization flow"); @@ -191,13 +192,14 @@ impl ZitadelOidcAuth { // (which Zitadel validates against ExternalDomain) while routing // through the local k3d/traefik ingress. if let Ok(url) = reqwest::Url::parse(&self.sso_url) - && let Some(host) = url.host_str() { - let port = url - .port() - .unwrap_or(if url.scheme() == "https" { 443 } else { 80 }); - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port)); - builder = builder.resolve(host, addr); - } + && let Some(host) = url.host_str() + { + let port = url + .port() + .unwrap_or(if url.scheme() == "https" { 443 } else { 80 }); + let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port)); + builder = builder.resolve(host, addr); + } builder .build() @@ -272,34 +274,35 @@ impl ZitadelOidcAuth { .map_err(|e| format!("Failed to read response body: {e}"))?; if status == 400 - && let Ok(error) = serde_json::from_str::(&body) { - match error.error.as_str() { - "authorization_pending" => { - debug!("ZITADEL_OIDC: authorization_pending (attempt {})", attempt); - continue; - } - "slow_down" => { - debug!("ZITADEL_OIDC: slow_down, increasing interval"); - tokio::time::sleep(Duration::from_secs(5)).await; - continue; - } - "expired_token" => { - return Err( - "Device code expired. Please restart authentication.".to_string() - ); - } - "access_denied" => { - return Err("Access denied by user.".to_string()); - } - _ => { - return Err(format!( - "OAuth error: {} - {}", - error.error, - error.error_description.unwrap_or_default() - )); - } + && let Ok(error) = serde_json::from_str::(&body) + { + match error.error.as_str() { + "authorization_pending" => { + debug!("ZITADEL_OIDC: authorization_pending (attempt {})", attempt); + continue; + } + "slow_down" => { + debug!("ZITADEL_OIDC: slow_down, increasing interval"); + tokio::time::sleep(Duration::from_secs(5)).await; + continue; + } + "expired_token" => { + return Err( + "Device code expired. Please restart authentication.".to_string() + ); + } + "access_denied" => { + return Err("Access denied by user.".to_string()); + } + _ => { + return Err(format!( + "OAuth error: {} - {}", + error.error, + error.error_description.unwrap_or_default() + )); } } + } return serde_json::from_str(&body) .map_err(|e| format!("Failed to parse token response: {e}")); diff --git a/harmony_tui/src/lib.rs b/harmony_tui/src/lib.rs index 6dd9c5a8..da00cb96 100644 --- a/harmony_tui/src/lib.rs +++ b/harmony_tui/src/lib.rs @@ -236,16 +236,17 @@ impl HarmonyTUI { async fn handle_event(&mut self, event: &Event) { debug!("Got event {event:?}"); if let Event::Key(key) = event - && key.kind == KeyEventKind::Press { - match key.code { - KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, - KeyCode::PageUp => self.tui_state.transition(TuiWidgetEvent::PrevPageKey), - KeyCode::PageDown => self.tui_state.transition(TuiWidgetEvent::NextPageKey), - KeyCode::Char('G') | KeyCode::End => { - self.tui_state.transition(TuiWidgetEvent::EscapeKey) - } - _ => self.score.handle_event(event).await, + && key.kind == KeyEventKind::Press + { + match key.code { + KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, + KeyCode::PageUp => self.tui_state.transition(TuiWidgetEvent::PrevPageKey), + KeyCode::PageDown => self.tui_state.transition(TuiWidgetEvent::NextPageKey), + KeyCode::Char('G') | KeyCode::End => { + self.tui_state.transition(TuiWidgetEvent::EscapeKey) } + _ => self.score.handle_event(event).await, } + } } } diff --git a/harmony_tui/src/widget/score.rs b/harmony_tui/src/widget/score.rs index c673d5a4..e91f2076 100644 --- a/harmony_tui/src/widget/score.rs +++ b/harmony_tui/src/widget/score.rs @@ -124,16 +124,17 @@ impl ScoreListWidget { pub(crate) async fn handle_event(&mut self, event: &Event) { if let Event::Key(key) = event - && key.kind == KeyEventKind::Press { - match key.code { - KeyCode::Char('j') | KeyCode::Down => self.scroll_down(), - KeyCode::Char('k') | KeyCode::Up => self.scroll_up(), - KeyCode::Enter => self.launch_execution(), - KeyCode::Char('y') => self.confirm(true).await, - KeyCode::Char('n') => self.confirm(false).await, - _ => {} - } + && key.kind == KeyEventKind::Press + { + match key.code { + KeyCode::Char('j') | KeyCode::Down => self.scroll_down(), + KeyCode::Char('k') | KeyCode::Up => self.scroll_up(), + KeyCode::Enter => self.launch_execution(), + KeyCode::Char('y') => self.confirm(true).await, + KeyCode::Char('n') => self.confirm(false).await, + _ => {} } + } } } diff --git a/nats/jwt/src/algorithm.rs b/nats/jwt/src/algorithm.rs index 4991a4a2..5cf7a734 100644 --- a/nats/jwt/src/algorithm.rs +++ b/nats/jwt/src/algorithm.rs @@ -187,10 +187,7 @@ mod tests { }; let token = encode(&claims, &account_kp).unwrap(); - eprintln!( - "TOKEN_PAYLOAD={}", - token.split('.').nth(1).unwrap_or("") - ); + eprintln!("TOKEN_PAYLOAD={}", token.split('.').nth(1).unwrap_or("")); let decoded: UserClaims = decode(&token).unwrap(); assert_eq!(decoded.nats.pub_perm.allow.as_ref().unwrap()[0], "_INBOX.>"); assert_eq!(decoded.nats.sub_perm.allow.as_ref().unwrap()[0], "_INBOX.>"); diff --git a/nats/jwt/src/claims/user.rs b/nats/jwt/src/claims/user.rs index e5a17619..ee92833a 100644 --- a/nats/jwt/src/claims/user.rs +++ b/nats/jwt/src/claims/user.rs @@ -47,8 +47,7 @@ pub struct User { pub generic: GenericFields, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[derive(Default)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct UserPermissionLimits { #[serde(default, skip_serializing_if = "Option::is_none")] pub allow: Option>, @@ -62,7 +61,6 @@ impl UserPermissionLimits { } } - #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ResponsePermission { pub max: i32, diff --git a/opnsense-api/examples/firmware_update.rs b/opnsense-api/examples/firmware_update.rs index de72470f..93b3620d 100644 --- a/opnsense-api/examples/firmware_update.rs +++ b/opnsense-api/examples/firmware_update.rs @@ -121,9 +121,10 @@ async fn main() { status.status_msg.as_deref().unwrap_or("Updates available.") ); if let Some(reboot) = status.status_reboot - && reboot == "1" { - println!(" ⚠ This update requires a reboot."); - } + && reboot == "1" + { + println!(" ⚠ This update requires a reboot."); + } let pkg_count = if let serde_json::Value::Object(ref map) = status.all_packages { map.len() diff --git a/opnsense-api/examples/install_and_wait.rs b/opnsense-api/examples/install_and_wait.rs index 7b4c568c..05a12638 100644 --- a/opnsense-api/examples/install_and_wait.rs +++ b/opnsense-api/examples/install_and_wait.rs @@ -83,10 +83,11 @@ async fn main() { .expect("info API call failed"); if let Some(pkgs) = info["package"].as_array() - && let Some(pkg) = pkgs.iter().find(|p| p["name"].as_str() == Some(&pkg_name)) { - println!( - "Package {} version={} installed={}", - pkg["name"], pkg["version"], pkg["installed"] - ); - } + && let Some(pkg) = pkgs.iter().find(|p| p["name"].as_str() == Some(&pkg_name)) + { + println!( + "Package {} version={} installed={}", + pkg["name"], pkg["version"], pkg["installed"] + ); + } } diff --git a/opnsense-api/tests/e2e_test.rs b/opnsense-api/tests/e2e_test.rs index fc64030b..c0928330 100644 --- a/opnsense-api/tests/e2e_test.rs +++ b/opnsense-api/tests/e2e_test.rs @@ -390,13 +390,14 @@ async fn e2e_haproxy_configure_service_via_config() { if fe["bind"].as_str() == Some("10.255.255.253:19999") { if let Some(be_uuid) = fe["defaultBackend"].as_str() { if let Some(be) = config["haproxy"]["backends"]["backend"].get(be_uuid) - && let Some(srv_csv) = be["linkedServers"].as_str() { - for srv_uuid in srv_csv.split(',').filter(|s: &&str| !s.is_empty()) { - let _ = client - .del_item("haproxy", "settings", "Server", srv_uuid) - .await; - } + && let Some(srv_csv) = be["linkedServers"].as_str() + { + for srv_uuid in srv_csv.split(',').filter(|s: &&str| !s.is_empty()) { + let _ = client + .del_item("haproxy", "settings", "Server", srv_uuid) + .await; } + } let _ = client .del_item("haproxy", "settings", "Backend", be_uuid) .await; diff --git a/opnsense-codegen/src/codegen.rs b/opnsense-codegen/src/codegen.rs index d585c6a7..0d2ce20e 100644 --- a/opnsense-codegen/src/codegen.rs +++ b/opnsense-codegen/src/codegen.rs @@ -1095,9 +1095,10 @@ pub fn write_mod_rs(dir: &std::path::Path) -> std::io::Result<()> { let path = entry.path(); if path.extension().and_then(|e| e.to_str()) == Some("rs") && let Some(stem) = path.file_stem().and_then(|s| s.to_str()) - && stem != "mod" { - modules.push(stem.to_string()); - } + && stem != "mod" + { + modules.push(stem.to_string()); + } } modules.sort(); diff --git a/opnsense-codegen/src/controller_parser.rs b/opnsense-codegen/src/controller_parser.rs index 96961e9b..84a17940 100644 --- a/opnsense-codegen/src/controller_parser.rs +++ b/opnsense-codegen/src/controller_parser.rs @@ -225,9 +225,10 @@ fn extract_body_keys(php: &str) -> std::collections::HashMap { // Fallback: if no matches, try just the first addBase call if keys.is_empty() - && let Some(caps) = re.captures(php) { - keys.insert("default".to_string(), caps[1].to_string()); - } + && let Some(caps) = re.captures(php) + { + keys.insert("default".to_string(), caps[1].to_string()); + } keys } diff --git a/opnsense-codegen/src/lib.rs b/opnsense-codegen/src/lib.rs index b04322cf..c677279b 100644 --- a/opnsense-codegen/src/lib.rs +++ b/opnsense-codegen/src/lib.rs @@ -638,7 +638,6 @@ pub mod generated { #[cfg(test)] mod tests { - use super::generated::example_service::*; use super::ir; diff --git a/opnsense-codegen/src/parser.rs b/opnsense-codegen/src/parser.rs index 699b45ab..7e94c999 100644 --- a/opnsense-codegen/src/parser.rs +++ b/opnsense-codegen/src/parser.rs @@ -82,9 +82,10 @@ fn parse_xml_into_tree(xml_data: &[u8]) -> Result { let text = e.unescape().map_err(|e| ParseError::Xml(e.to_string()))?; if !text.trim().is_empty() && let Some(XmlNode::Element { text: cur_text, .. }) = stack.last_mut() - && cur_text.is_none() { - *cur_text = Some(text.to_string()); - } + && cur_text.is_none() + { + *cur_text = Some(text.to_string()); + } } Event::End(_) => { if let Some(node) = stack.pop() { @@ -357,10 +358,9 @@ fn extract_field_metadata(children: &[XmlNode]) -> FieldMetadata { continue; }; match name.as_str() { - "Required" - if text.as_deref() == Some("Y") => { - meta.required = true; - } + "Required" if text.as_deref() == Some("Y") => { + meta.required = true; + } "Default" => { meta.default = text.clone(); } @@ -370,14 +370,12 @@ fn extract_field_metadata(children: &[XmlNode]) -> FieldMetadata { "MaximumValue" => { meta.max = text.as_ref().and_then(|v| v.parse().ok()); } - "AsList" - if text.as_deref() == Some("Y") => { - meta.as_list = true; - } - "Multiple" - if text.as_deref() == Some("Y") => { - meta.multiple = true; - } + "AsList" if text.as_deref() == Some("Y") => { + meta.as_list = true; + } + "Multiple" if text.as_deref() == Some("Y") => { + meta.multiple = true; + } "Mask" => { meta.mask = text.clone(); } @@ -725,12 +723,13 @@ fn build_field( if variants.is_empty() && let Some(t) = meta.default.clone() - && !t.is_empty() { - variants.push(EnumVariantIR { - rust_name: sanitize_rust_ident(&t.to_pascal_case()), - wire_value: t.clone(), - }); - } + && !t.is_empty() + { + variants.push(EnumVariantIR { + rust_name: sanitize_rust_ident(&t.to_pascal_case()), + wire_value: t.clone(), + }); + } model.enums.push(EnumIR { name: enum_name.clone(), diff --git a/opnsense-config-xml/src/data/haproxy.rs b/opnsense-config-xml/src/data/haproxy.rs index 7fd2928e..718e283b 100644 --- a/opnsense-config-xml/src/data/haproxy.rs +++ b/opnsense-config-xml/src/data/haproxy.rs @@ -83,7 +83,11 @@ pub struct HAProxyId(String); impl Default for HAProxyId { fn default() -> Self { let mut rng = rand::rng(); - Self(format!("{:x}.{:x}", rng.random::(), rng.random::())) + Self(format!( + "{:x}.{:x}", + rng.random::(), + rng.random::() + )) } } -- 2.39.5 From ee95a5d1a3417d38828bc0a07f550011ee588e68 Mon Sep 17 00:00:00 2001 From: Jean-Gabriel Gill-Couture Date: Mon, 11 May 2026 22:43:56 -0400 Subject: [PATCH 2/3] feat: maud + htmx + tailwindcss frontend for fleet operator, initial commit, still much work to do --- fleet/harmony-fleet-operator/Cargo.toml | 14 + fleet/harmony-fleet-operator/README.md | 140 +++++++++ fleet/harmony-fleet-operator/build.rs | 66 ++++ .../src/frontend/assets.rs | 10 + .../src/frontend/layout.rs | 53 ++++ .../src/frontend/mod.rs | 14 + .../src/frontend/server.rs | 174 +++++++++++ .../src/frontend/views/dashboard.rs | 35 +++ .../src/frontend/views/deployments.rs | 50 +++ .../src/frontend/views/devices.rs | 83 +++++ .../src/frontend/views/mod.rs | 3 + fleet/harmony-fleet-operator/src/main.rs | 79 ++++- .../src/service/mock.rs | 221 +++++++++++++ .../harmony-fleet-operator/src/service/mod.rs | 99 ++++++ fleet/harmony-fleet-operator/style/input.css | 4 + .../vendor/htmx-ext-sse.js | 290 ++++++++++++++++++ .../harmony-fleet-operator/vendor/htmx.min.js | 1 + 17 files changed, 1319 insertions(+), 17 deletions(-) create mode 100644 fleet/harmony-fleet-operator/README.md create mode 100644 fleet/harmony-fleet-operator/build.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/assets.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/layout.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/mod.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/server.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/deployments.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/devices.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/mod.rs create mode 100644 fleet/harmony-fleet-operator/src/service/mock.rs create mode 100644 fleet/harmony-fleet-operator/src/service/mod.rs create mode 100644 fleet/harmony-fleet-operator/style/input.css create mode 100644 fleet/harmony-fleet-operator/vendor/htmx-ext-sse.js create mode 100644 fleet/harmony-fleet-operator/vendor/htmx.min.js diff --git a/fleet/harmony-fleet-operator/Cargo.toml b/fleet/harmony-fleet-operator/Cargo.toml index ac8883d3..d4ef4d28 100644 --- a/fleet/harmony-fleet-operator/Cargo.toml +++ b/fleet/harmony-fleet-operator/Cargo.toml @@ -3,6 +3,15 @@ name = "harmony-fleet-operator" version = "0.1.0" edition = "2024" rust-version = "1.85" +build = "build.rs" + +[features] +default = [] +# Server-side dashboard (axum + Maud + HTMX). Tailwind CSS is embedded at +# build time when the standalone `tailwindcss` CLI is on PATH; otherwise +# the bundled CSS is empty and `--css-from ` must be used at runtime +# (the sidecar-watch dev workflow does this). +web-frontend = ["dep:axum", "dep:maud", "dep:tokio-stream"] [dependencies] harmony = { path = "../../harmony", features = ["podman"] } @@ -23,3 +32,8 @@ anyhow.workspace = true clap.workspace = true futures-util = { workspace = true } thiserror.workspace = true +async-trait.workspace = true + +axum = { version = "0.8", optional = true } +maud = { version = "0.27", features = ["axum"], optional = true } +tokio-stream = { version = "0.1", optional = true } diff --git a/fleet/harmony-fleet-operator/README.md b/fleet/harmony-fleet-operator/README.md new file mode 100644 index 00000000..9ddd7005 --- /dev/null +++ b/fleet/harmony-fleet-operator/README.md @@ -0,0 +1,140 @@ +# harmony-fleet-operator + +IoT operator — reconciles `Deployment` CRDs into NATS KV desired-state and +aggregates device/deployment state back into CR status. + +## Web frontend (optional) + +A small **server-side dashboard** is built into the operator behind the +`web-frontend` cargo feature. Stack: `axum` + `maud` (HTML-in-Rust) + vendored +[HTMX](https://htmx.org/) + Tailwind CSS. No WASM, no `cargo-leptos`, no JS +build toolchain — `cargo build --features web-frontend` is the whole build. + +### Why this stack + +Every interaction is an HTTP request that returns an HTML fragment, and HTMX +swaps it into the DOM. There is no client-side state. The presentation layer +is intentionally thin: + +```rust +async fn devices_handler(State(s): State) -> Result { + let devices = s.fleet.list_devices().await?; + Ok(page("Devices", s.live_reload, devices_view::page(&devices))) +} +``` + +Each handler is _extract state → call domain service → render Maud markup_. +All real work — listing devices, blacklisting, etc. — lives in +[`service::FleetService`](src/service/mod.rs), a trait the dashboard, tests, +and a future CLI all share. Presentation never reaches past that trait. + +**Why Maud instead of Leptos?** We don't use Leptos's reactivity (it's pure +SSR + HTMX), so the runtime/macro footprint was dead weight. Maud is a +compile-time HTML macro that produces a `Markup` value — smaller dep tree, +faster compiles, same Rust-flavored ergonomics. + +**Why HTMX + xterm.js for interactivity?** A real terminal needs xterm.js in +the browser regardless; once that JS exists, HTMX (~14 KB) is a rounding +error and lets every other interaction stay declarative in markup +(`hx-post`, `hx-target`, `hx-swap`). + +**Why everything bundled?** The operator already ships as a single +container. Tailwind CSS, HTMX, and the HTMX SSE extension are all embedded +via `include_bytes!` so air-gapped clusters get the dashboard with nothing +extra to mount. The only build-time external is the standalone `tailwindcss` +v4 CLI — missing-CLI degrades gracefully (warning + empty embedded CSS); the +dev workflow uses `--css-from` instead anyway. + +### Running it locally (mock data, no NATS, no kube) + +```sh +# One-time: install the standalone Tailwind v4 CLI (single static binary). +curl -L -o ~/.local/bin/tailwindcss \ + https://github.com/tailwindlabs/tailwindcss/releases/latest/download/tailwindcss-linux-x64 +chmod +x ~/.local/bin/tailwindcss +``` + +Two terminals for the dev loop: + +```sh +# Terminal 1 — Tailwind sidecar, regenerates CSS on every class change. +tailwindcss \ + -i fleet/harmony-fleet-operator/style/input.css \ + -o fleet/harmony-fleet-operator/style/dist/tailwind.css \ + --watch + +# Terminal 2 — the operator, serving the dashboard against fake data and +# reading CSS from Tailwind's output. `--live-reload` reloads the browser +# tab whenever you restart the server. +cargo run -p harmony-fleet-operator --features web-frontend -- serve-web \ + --mock \ + --css-from fleet/harmony-fleet-operator/style/dist/tailwind.css \ + --live-reload +``` + +Open . + +`--mock` uses [`MockFleetService`](src/service/mock.rs), an in-memory +seeded dataset (10 fake devices in mixed states, 4 deployments). You can +click "Blacklist" on a row and the row will swap in place to reflect the +new status — this exercises the same `FleetService` API the real impl +will satisfy. No NATS, no Kubernetes cluster needed. + +#### Iteration cost + +| Change | Reload step | +| --- | --- | +| Tailwind class in a Maud template | edit → save → refresh tab _(Tailwind sidecar already rebuilt CSS; no Rust compile)_ | +| Maud template structure / handler logic | edit → `cargo run` restarts → `--live-reload` auto-refreshes | +| `FleetService` types | edit → `cargo run` restarts → tab auto-refreshes | + +The Rust recompile is the actual floor. Tailwind changes never trigger one. + +### Production builds + +```sh +# Once, before cargo build: produce the embedded CSS. +tailwindcss \ + -i fleet/harmony-fleet-operator/style/input.css \ + -o fleet/harmony-fleet-operator/style/dist/tailwind.css \ + --minify + +cargo build -p harmony-fleet-operator --features web-frontend --release +``` + +The release binary serves the embedded CSS unless you pass `--css-from` at +runtime. (`build.rs` will _also_ run `tailwindcss` if it's on PATH; the +manual step above is just a guarantee that the embedded copy is correct.) + +### Layout + +``` +fleet/harmony-fleet-operator/ +├── src/ +│ ├── service/ ← domain abstraction (FleetService trait + Mock) +│ │ ├── mod.rs ← trait + summary types +│ │ └── mock.rs ← in-memory seeded data +│ └── frontend/ ← presentation layer (cfg web-frontend) +│ ├── server.rs ← axum router + handlers +│ ├── layout.rs ← page shell (Maud) +│ ├── assets.rs ← embedded Tailwind/HTMX bytes +│ └── views/ +│ ├── dashboard.rs +│ ├── devices.rs ← also exposes `row()` for HTMX swaps +│ └── deployments.rs +├── style/ +│ └── input.css ← Tailwind v4 entry point +└── vendor/ + ├── htmx.min.js ← HTMX v2.0.9 + └── htmx-ext-sse.js ← SSE extension (used by future log-tail views) +``` + +### What's deferred + +- **Real `FleetService` impl** (wraps the kube client + NATS KV the + reconcilers already use). `serve-web` without `--mock` currently errors + out. +- **Zitadel SSO + admin-role check.** v1 assumes an oauth2-proxy fronts the + dashboard at the cluster edge. +- **Live log tail** (SSE-based, HTMX `sse-swap`) — the wiring is in place. +- **Interactive shell** (xterm.js + axum WS + portable-pty) — separate design. diff --git a/fleet/harmony-fleet-operator/build.rs b/fleet/harmony-fleet-operator/build.rs new file mode 100644 index 00000000..c004905b --- /dev/null +++ b/fleet/harmony-fleet-operator/build.rs @@ -0,0 +1,66 @@ +//! Best-effort Tailwind CSS build for the `web-frontend` feature. +//! +//! When the standalone `tailwindcss` v4 CLI is on PATH and the +//! `web-frontend` feature is on, this script generates the production +//! CSS bundle into `$OUT_DIR/tailwind.css`. The binary embeds that file +//! via `include_bytes!`. +//! +//! If the CLI is missing or fails we write an *empty* CSS file rather +//! than failing the build — the dev workflow uses +//! `serve-web --css-from ` to read Tailwind output from a sidecar +//! `tailwindcss --watch` process, so the embedded copy is irrelevant +//! there. Production builds should ensure `tailwindcss` is on PATH; the +//! warning below shows up in `cargo build` output when it is not. + +use std::path::PathBuf; +use std::process::Command; + +fn main() { + let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap()); + let output = out_dir.join("tailwind.css"); + + if std::env::var_os("CARGO_FEATURE_WEB_FRONTEND").is_none() { + // Feature off — emit an empty placeholder so the `include_bytes!` + // path in src/frontend/assets.rs still compiles if anything + // references it (it should be cfg-gated, but belt-and-braces). + std::fs::write(&output, b"").unwrap(); + return; + } + + let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); + let input = manifest_dir.join("style/input.css"); + + println!("cargo:rerun-if-changed=style/input.css"); + println!("cargo:rerun-if-changed=src/frontend"); + println!("cargo:rerun-if-changed=src/service"); + + let status = Command::new("tailwindcss") + .arg("--input") + .arg(&input) + .arg("--output") + .arg(&output) + .arg("--minify") + .status(); + + match status { + Ok(s) if s.success() => {} + Ok(s) => { + println!( + "cargo:warning=tailwindcss exited with status {s}; embedded CSS will be empty. \ + Install the v4 standalone CLI \ + (https://github.com/tailwindlabs/tailwindcss/releases) for production builds, \ + or use `serve-web --css-from ` against a `tailwindcss --watch` sidecar in dev." + ); + std::fs::write(&output, b"").unwrap(); + } + Err(e) => { + println!( + "cargo:warning=tailwindcss not invocable ({e}); embedded CSS will be empty. \ + Install the v4 standalone CLI \ + (https://github.com/tailwindlabs/tailwindcss/releases) for production builds, \ + or use `serve-web --css-from ` against a `tailwindcss --watch` sidecar in dev." + ); + std::fs::write(&output, b"").unwrap(); + } + } +} diff --git a/fleet/harmony-fleet-operator/src/frontend/assets.rs b/fleet/harmony-fleet-operator/src/frontend/assets.rs new file mode 100644 index 00000000..627bd85f --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/assets.rs @@ -0,0 +1,10 @@ +//! Static assets embedded in the binary. +//! +//! Tailwind CSS is built by `build.rs` into `$OUT_DIR/tailwind.css` +//! (empty if the CLI was unavailable — dev uses `--css-from` instead). +//! HTMX and its SSE extension are vendored under `vendor/` so the +//! container ships with no external script dependencies. + +pub const TAILWIND_CSS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/tailwind.css")); +pub const HTMX_JS: &[u8] = include_bytes!("../../vendor/htmx.min.js"); +pub const HTMX_SSE_JS: &[u8] = include_bytes!("../../vendor/htmx-ext-sse.js"); diff --git a/fleet/harmony-fleet-operator/src/frontend/layout.rs b/fleet/harmony-fleet-operator/src/frontend/layout.rs new file mode 100644 index 00000000..be075ae7 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/layout.rs @@ -0,0 +1,53 @@ +//! Page shell — ``, ``, top nav, body slot. + +use maud::{DOCTYPE, Markup, PreEscaped, html}; + +pub fn page(title: &str, live_reload: bool, content: Markup) -> Markup { + html! { + (DOCTYPE) + html lang="en" { + head { + meta charset="utf-8"; + meta name="viewport" content="width=device-width, initial-scale=1"; + title { (title) " — Harmony Fleet" } + link rel="stylesheet" href="/static/tailwind.css"; + script src="/static/htmx.min.js" defer {} + script src="/static/htmx-ext-sse.js" defer {} + @if live_reload { + script { (PreEscaped(LIVE_RELOAD_JS)) } + } + } + body class="min-h-screen bg-slate-950 text-slate-100" hx-ext="sse" { + header class="border-b border-slate-800 px-6 py-4 flex items-baseline gap-6" { + h1 class="text-xl font-semibold" { "Harmony Fleet Operator" } + nav class="flex gap-4 text-sm text-slate-400" { + a href="/" class="hover:text-slate-100" { "Dashboard" } + a href="/devices" class="hover:text-slate-100" { "Devices" } + a href="/deployments" class="hover:text-slate-100" { "Deployments" } + } + @if live_reload { + span class="ml-auto text-xs text-amber-400" { "dev · live reload" } + } + } + main class="p-6 space-y-8" { (content) } + } + } + } +} + +/// Tiny inline script: reconnects an EventSource to `/__dev/reload`; +/// when the server comes back up after a restart, reload the page. +const LIVE_RELOAD_JS: &str = r#" +(function(){ + let connected = false; + function connect() { + const src = new EventSource("/__dev/reload"); + src.onopen = () => { + if (connected) location.reload(); + connected = true; + }; + src.onerror = () => { src.close(); setTimeout(connect, 500); }; + } + connect(); +})(); +"#; diff --git a/fleet/harmony-fleet-operator/src/frontend/mod.rs b/fleet/harmony-fleet-operator/src/frontend/mod.rs new file mode 100644 index 00000000..c14d8059 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/mod.rs @@ -0,0 +1,14 @@ +//! Web dashboard for the fleet operator. +//! +//! Pure server-side: axum routes + Maud templates + vendored HTMX + +//! Tailwind CSS. No WASM, no JS frameworks, single binary. +//! +//! The presentation layer is intentionally thin — every handler +//! resolves to a [`service::FleetService`](crate::service::FleetService) +//! call followed by a Maud render. The same service trait will back the +//! future CLI. + +pub mod assets; +pub mod layout; +pub mod server; +pub mod views; diff --git a/fleet/harmony-fleet-operator/src/frontend/server.rs b/fleet/harmony-fleet-operator/src/frontend/server.rs new file mode 100644 index 00000000..588404d3 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/server.rs @@ -0,0 +1,174 @@ +use std::convert::Infallible; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use axum::Router; +use axum::body::Body; +use axum::extract::{Path, State}; +use axum::http::{StatusCode, header}; +use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use maud::Markup; +use tokio_stream::StreamExt; + +use super::assets::{HTMX_JS, HTMX_SSE_JS, TAILWIND_CSS}; +use super::layout::page; +use super::views::{dashboard, deployments as deployments_view, devices as devices_view}; +use crate::service::FleetService; + +/// Default high port — keeps clear of NATS (4222), k8s API (6443), +/// and common metrics/webhook ports (8080/9090/9443). +pub const DEFAULT_PORT: u16 = 18080; + +#[derive(Clone)] +pub struct AppState { + pub fleet: Arc, + /// Read Tailwind CSS from this path on every request when set. + /// Lets a sidecar `tailwindcss --watch` drive iteration without + /// recompiling the binary. + pub css_override: Option, + /// When true, inject the live-reload script into pages and expose + /// `/__dev/reload`. + pub live_reload: bool, +} + +pub struct Config { + pub addr: SocketAddr, + pub state: AppState, +} + +impl Config { + pub fn new(state: AppState) -> Self { + Self { + addr: SocketAddr::from(([0, 0, 0, 0], DEFAULT_PORT)), + state, + } + } + + pub fn with_addr(mut self, addr: SocketAddr) -> Self { + self.addr = addr; + self + } +} + +pub fn router(state: AppState) -> Router { + let mut r = Router::new() + .route("/", get(dashboard_handler)) + .route("/devices", get(devices_handler)) + .route("/devices/{id}/blacklist", post(blacklist_handler)) + .route("/deployments", get(deployments_handler)) + .route("/static/tailwind.css", get(tailwind_css)) + .route("/static/htmx.min.js", get(htmx_js)) + .route("/static/htmx-ext-sse.js", get(htmx_sse_js)); + + if state.live_reload { + r = r.route("/__dev/reload", get(dev_reload_sse)); + } + + r.with_state(state) +} + +pub async fn run(cfg: Config) -> Result<()> { + let addr = cfg.addr; + let listener = tokio::net::TcpListener::bind(addr).await?; + tracing::info!(%addr, "fleet operator web frontend listening"); + axum::serve(listener, router(cfg.state)).await?; + Ok(()) +} + +// ---- handlers: each is a 3-liner: extract state, call service, render. ---- + +async fn dashboard_handler(State(s): State) -> Result { + let summary = s.fleet.dashboard_summary().await?; + Ok(page("Dashboard", s.live_reload, dashboard::page(&summary))) +} + +async fn devices_handler(State(s): State) -> Result { + let devices = s.fleet.list_devices().await?; + Ok(page("Devices", s.live_reload, devices_view::page(&devices))) +} + +async fn deployments_handler(State(s): State) -> Result { + let deployments = s.fleet.list_deployments().await?; + Ok(page( + "Deployments", + s.live_reload, + deployments_view::page(&deployments), + )) +} + +async fn blacklist_handler( + State(s): State, + Path(id): Path, +) -> Result { + let updated = s.fleet.blacklist_device(&id).await?; + Ok(devices_view::row(&updated)) +} + +// ---- static assets ---- + +async fn tailwind_css(State(s): State) -> Response { + let css: Vec = match &s.css_override { + Some(path) => match tokio::fs::read(path).await { + Ok(bytes) => bytes, + Err(e) => { + tracing::warn!(?path, error = %e, "css_override read failed; serving empty CSS"); + Vec::new() + } + }, + None => TAILWIND_CSS.to_vec(), + }; + static_response(css, "text/css; charset=utf-8") +} + +async fn htmx_js() -> Response { + static_response(HTMX_JS.to_vec(), "application/javascript; charset=utf-8") +} + +async fn htmx_sse_js() -> Response { + static_response( + HTMX_SSE_JS.to_vec(), + "application/javascript; charset=utf-8", + ) +} + +fn static_response(bytes: Vec, content_type: &'static str) -> Response { + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type) + .body(Body::from(bytes)) + .expect("well-formed static response") +} + +// ---- dev live-reload SSE ---- + +async fn dev_reload_sse() -> Sse>> { + // We never send actual reload events from here. The browser-side + // pattern is simpler: on EventSource reconnect after the server + // came back up, reload the page. So all we do is hold the + // connection open with keep-alive pings. + let stream = tokio_stream::iter([Ok::<_, Infallible>(Event::default().data("ready"))]) + .chain(tokio_stream::pending()); + Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))) +} + +// ---- error type ---- + +pub struct AppError(anyhow::Error); + +impl> From for AppError { + fn from(e: E) -> Self { + Self(e.into()) + } +} + +impl IntoResponse for AppError { + fn into_response(self) -> Response { + tracing::error!(error = %self.0, "request failed"); + (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", self.0)).into_response() + } +} diff --git a/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs b/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs new file mode 100644 index 00000000..1e2a0170 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs @@ -0,0 +1,35 @@ +use maud::{Markup, html}; + +use crate::service::DashboardSummary; + +pub fn page(summary: &DashboardSummary) -> Markup { + html! { + section { + h2 class="text-lg font-medium mb-4 text-slate-300" { "Devices" } + div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4" { + (card("Total", &summary.devices_total.to_string(), "text-slate-50")) + (card("Healthy", &summary.devices_healthy.to_string(), "text-emerald-400")) + (card("Pending", &summary.devices_pending.to_string(), "text-amber-400")) + (card("Stale", &summary.devices_stale.to_string(), "text-rose-400")) + (card("Blacklisted", &summary.devices_blacklisted.to_string(), "text-slate-500")) + } + } + section { + h2 class="text-lg font-medium mb-4 text-slate-300" { "Deployments" } + div class="grid grid-cols-2 sm:grid-cols-3 gap-4" { + (card("Total", &summary.deployments_total.to_string(), "text-slate-50")) + (card("Active / Rolling", &summary.deployments_active.to_string(), "text-emerald-400")) + (card("Failing", &summary.deployments_failing.to_string(), "text-rose-400")) + } + } + } +} + +fn card(title: &str, value: &str, value_class: &str) -> Markup { + html! { + div class="rounded-lg border border-slate-800 bg-slate-900 p-4" { + div class="text-xs uppercase tracking-wide text-slate-400" { (title) } + div class={"mt-2 text-3xl font-semibold " (value_class)} { (value) } + } + } +} diff --git a/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs b/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs new file mode 100644 index 00000000..cd13d4cb --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs @@ -0,0 +1,50 @@ +use maud::{Markup, html}; + +use crate::service::{DeploymentStatus, DeploymentSummary}; + +pub fn page(deployments: &[DeploymentSummary]) -> Markup { + html! { + section { + div class="flex items-baseline gap-3 mb-4" { + h2 class="text-lg font-medium text-slate-300" { "Deployments" } + span class="text-xs text-slate-500" { (deployments.len()) " total" } + } + div class="overflow-x-auto rounded-lg border border-slate-800" { + table class="min-w-full divide-y divide-slate-800 text-sm" { + thead class="bg-slate-900 text-xs uppercase tracking-wide text-slate-400" { + tr { + th class="px-3 py-2 text-left font-medium" { "Name" } + th class="px-3 py-2 text-left font-medium" { "Status" } + th class="px-3 py-2 text-left font-medium" { "Health" } + } + } + tbody class="divide-y divide-slate-800 bg-slate-950" { + @for d in deployments { + tr { + td class="px-3 py-2 font-mono text-slate-200" { (d.name) } + td class="px-3 py-2" { (status_badge(d.status)) } + td class="px-3 py-2 text-slate-300" { + (d.healthy_devices) " / " (d.target_devices) " healthy" + } + } + } + } + } + } + } + } +} + +fn status_badge(s: DeploymentStatus) -> Markup { + let (label, classes) = match s { + DeploymentStatus::Active => ("active", "bg-emerald-900 text-emerald-300"), + DeploymentStatus::Rolling => ("rolling", "bg-sky-900 text-sky-300"), + DeploymentStatus::Failing => ("failing", "bg-rose-900 text-rose-300"), + DeploymentStatus::Paused => ("paused", "bg-slate-800 text-slate-400"), + }; + html! { + span class={"inline-block rounded px-2 py-0.5 text-xs font-medium " (classes)} { + (label) + } + } +} diff --git a/fleet/harmony-fleet-operator/src/frontend/views/devices.rs b/fleet/harmony-fleet-operator/src/frontend/views/devices.rs new file mode 100644 index 00000000..6d9c6c99 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/devices.rs @@ -0,0 +1,83 @@ +use maud::{Markup, html}; + +use crate::service::{DeviceStatus, DeviceSummary}; + +pub fn page(devices: &[DeviceSummary]) -> Markup { + html! { + section { + div class="flex items-baseline gap-3 mb-4" { + h2 class="text-lg font-medium text-slate-300" { "Devices" } + span class="text-xs text-slate-500" { (devices.len()) " total" } + } + div class="overflow-x-auto rounded-lg border border-slate-800" { + table class="min-w-full divide-y divide-slate-800 text-sm" { + thead class="bg-slate-900 text-xs uppercase tracking-wide text-slate-400" { + tr { + th class="px-3 py-2 text-left font-medium" { "ID" } + th class="px-3 py-2 text-left font-medium" { "Status" } + th class="px-3 py-2 text-left font-medium" { "Deployment" } + th class="px-3 py-2 text-left font-medium" { "IP" } + th class="px-3 py-2 text-left font-medium" { "Last seen" } + th class="px-3 py-2 text-right font-medium" { "Actions" } + } + } + tbody id="device-rows" class="divide-y divide-slate-800 bg-slate-950" { + @for device in devices { + (row(device)) + } + } + } + } + } + } +} + +/// Single row — also the response shape for `POST /devices/:id/blacklist`, +/// so HTMX can swap a row in place after a mutation. +pub fn row(d: &DeviceSummary) -> Markup { + html! { + tr id={"device-" (d.id)} { + td class="px-3 py-2 font-mono text-slate-200" { (d.id) } + td class="px-3 py-2" { (status_badge(d.status)) } + td class="px-3 py-2 text-slate-300" { + @if let Some(deployment) = &d.deployment { (deployment) } + @else { span class="text-slate-600" { "—" } } + } + td class="px-3 py-2 font-mono text-slate-400" { + @if let Some(ip) = &d.ip { (ip) } + @else { span class="text-slate-600" { "—" } } + } + td class="px-3 py-2 text-slate-400" { + (d.last_seen.format("%Y-%m-%d %H:%M:%S").to_string()) " UTC" + } + td class="px-3 py-2 text-right" { + @if d.status != DeviceStatus::Blacklisted { + button + class="rounded bg-rose-700 hover:bg-rose-600 px-2 py-1 text-xs font-medium" + hx-post={"/devices/" (d.id) "/blacklist"} + hx-target={"#device-" (d.id)} + hx-swap="outerHTML" + hx-confirm={"Blacklist " (d.id) "?"} + { "Blacklist" } + } @else { + span class="text-xs text-slate-500" { "blacklisted" } + } + } + } + } +} + +fn status_badge(s: DeviceStatus) -> Markup { + let (label, classes) = match s { + DeviceStatus::Healthy => ("healthy", "bg-emerald-900 text-emerald-300"), + DeviceStatus::Pending => ("pending", "bg-amber-900 text-amber-300"), + DeviceStatus::Stale => ("stale", "bg-rose-900 text-rose-300"), + DeviceStatus::Blacklisted => ("blacklisted", "bg-slate-800 text-slate-400"), + DeviceStatus::Unknown => ("unknown", "bg-slate-800 text-slate-500"), + }; + html! { + span class={"inline-block rounded px-2 py-0.5 text-xs font-medium " (classes)} { + (label) + } + } +} diff --git a/fleet/harmony-fleet-operator/src/frontend/views/mod.rs b/fleet/harmony-fleet-operator/src/frontend/views/mod.rs new file mode 100644 index 00000000..ec2901b5 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/mod.rs @@ -0,0 +1,3 @@ +pub mod dashboard; +pub mod deployments; +pub mod devices; diff --git a/fleet/harmony-fleet-operator/src/main.rs b/fleet/harmony-fleet-operator/src/main.rs index c54b88fa..46300ee9 100644 --- a/fleet/harmony-fleet-operator/src/main.rs +++ b/fleet/harmony-fleet-operator/src/main.rs @@ -1,5 +1,8 @@ mod controller; +#[cfg(feature = "web-frontend")] +mod frontend; mod install; +mod service; use harmony_fleet_operator::{device_reconciler, fleet_aggregator}; @@ -78,6 +81,27 @@ enum Command { #[arg(long, default_value = "info,kube_runtime=warn")] log_level: String, }, + /// Run the web dashboard only. Useful for frontend iteration — + /// pair with `--mock` to bypass NATS and Kubernetes entirely. Pair + /// with `--css-from` against a `tailwindcss --watch` sidecar for + /// instant CSS updates without recompiling. + #[cfg(feature = "web-frontend")] + ServeWeb { + /// Use seeded fake data instead of connecting to NATS/kube. + #[arg(long)] + mock: bool, + /// Bind address (defaults to 0.0.0.0:18080). + #[arg(long, default_value = "0.0.0.0:18080")] + addr: std::net::SocketAddr, + /// Override the embedded Tailwind CSS by reading this file on + /// every request. Intended for dev: point at the output of + /// `tailwindcss --watch`. + #[arg(long)] + css_from: Option, + /// Inject the live-reload script and expose /__dev/reload. + #[arg(long)] + live_reload: bool, + }, } #[tokio::main] @@ -115,25 +139,46 @@ async fn main() -> Result<()> { println!("{}", written.display()); Ok(()) } + #[cfg(feature = "web-frontend")] + Command::ServeWeb { + mock, + addr, + css_from, + live_reload, + } => serve_web(mock, addr, css_from, live_reload).await, } +} - // TODO - // Launch a web server with frontend and possibly API. This frontend logs in using zitadel SSO - // then based on the user's credentials (check if fleet admin role), allow the user to view nats - // and k8s states. - // - // First page to develop it a dashboard with aggregated numbers for devices in each state - // (pending, healthy, stale (when no neetwork connection in over x minutes?), etc and aggregated deployment - // information (number of deployments, number in each state, etc). - // - // This frontend should be written in a separate crate but be initialized here (if possible? - // maybe cirtular dependency problem, in which case just write it in a subfolder of the opeartor - // itself). - // - // This frontend should leverage our existing data structures for the operator. - // - // I am open to using almost any rust web framework, my own default is leptos - // do this in app.rs, I want to cleanup main.rs as much as possible +#[cfg(feature = "web-frontend")] +async fn serve_web( + mock: bool, + addr: std::net::SocketAddr, + css_from: Option, + live_reload: bool, +) -> Result<()> { + use std::sync::Arc; + + use frontend::server::{AppState, Config}; + use service::{FleetService, mock::MockFleetService}; + + let fleet: Arc = if mock { + Arc::new(MockFleetService::default()) + } else { + anyhow::bail!( + "serve-web without --mock is not implemented yet (real FleetService impl pending). \ + Pass --mock for the dev workflow." + ); + }; + + frontend::server::run( + Config::new(AppState { + fleet, + css_override: css_from, + live_reload, + }) + .with_addr(addr), + ) + .await } async fn run(nats_url: &str, bucket: &str, credentials_toml: &str) -> Result<()> { diff --git a/fleet/harmony-fleet-operator/src/service/mock.rs b/fleet/harmony-fleet-operator/src/service/mock.rs new file mode 100644 index 00000000..27da4675 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/service/mock.rs @@ -0,0 +1,221 @@ +//! In-memory `FleetService` with seeded fake data. +//! +//! Used by `serve-web --mock` for local development without a NATS +//! server or a Kubernetes cluster, and by tests that exercise the +//! presentation layer. + +use std::collections::HashMap; +use std::sync::Mutex; + +use async_trait::async_trait; +use chrono::{Duration, Utc}; + +use super::{ + DashboardSummary, DeploymentStatus, DeploymentSummary, DeviceStatus, DeviceSummary, + FleetService, +}; + +pub struct MockFleetService { + devices: Mutex>, + deployments: Mutex>, +} + +impl Default for MockFleetService { + fn default() -> Self { + Self::with_seeded_data() + } +} + +impl MockFleetService { + pub fn with_seeded_data() -> Self { + let now = Utc::now(); + let devices = [ + ( + "pi-001", + DeviceStatus::Healthy, + 30, + Some("kiosk-v3"), + Some("10.0.1.21"), + ), + ( + "pi-002", + DeviceStatus::Healthy, + 45, + Some("kiosk-v3"), + Some("10.0.1.22"), + ), + ( + "pi-003", + DeviceStatus::Healthy, + 12, + Some("kiosk-v3"), + Some("10.0.1.23"), + ), + ( + "pi-004", + DeviceStatus::Pending, + 5, + Some("kiosk-v3"), + Some("10.0.1.24"), + ), + ( + "pi-005", + DeviceStatus::Stale, + 1820, + Some("kiosk-v2"), + Some("10.0.1.25"), + ), + ("pi-006", DeviceStatus::Stale, 2400, Some("kiosk-v2"), None), + ( + "pi-007", + DeviceStatus::Blacklisted, + 600, + None, + Some("10.0.1.27"), + ), + ("pi-008", DeviceStatus::Unknown, 9999, None, None), + ( + "pi-009", + DeviceStatus::Healthy, + 88, + Some("sensor-edge"), + Some("10.0.2.10"), + ), + ( + "pi-010", + DeviceStatus::Pending, + 3, + Some("sensor-edge"), + Some("10.0.2.11"), + ), + ]; + let devices: HashMap = devices + .into_iter() + .map(|(id, status, seconds_ago, deployment, ip)| { + ( + id.to_string(), + DeviceSummary { + id: id.to_string(), + status, + last_seen: now - Duration::seconds(seconds_ago), + deployment: deployment.map(str::to_string), + ip: ip.map(str::to_string), + }, + ) + }) + .collect(); + + let deployments = vec![ + DeploymentSummary { + name: "kiosk-v3".into(), + status: DeploymentStatus::Rolling, + target_devices: 4, + healthy_devices: 3, + }, + DeploymentSummary { + name: "kiosk-v2".into(), + status: DeploymentStatus::Paused, + target_devices: 2, + healthy_devices: 0, + }, + DeploymentSummary { + name: "sensor-edge".into(), + status: DeploymentStatus::Active, + target_devices: 2, + healthy_devices: 1, + }, + DeploymentSummary { + name: "ota-canary".into(), + status: DeploymentStatus::Failing, + target_devices: 1, + healthy_devices: 0, + }, + ]; + + Self { + devices: Mutex::new(devices), + deployments: Mutex::new(deployments), + } + } +} + +#[async_trait] +impl FleetService for MockFleetService { + async fn dashboard_summary(&self) -> anyhow::Result { + let devices = self.devices.lock().unwrap(); + let deployments = self.deployments.lock().unwrap(); + let mut s = DashboardSummary { + devices_total: devices.len() as u32, + deployments_total: deployments.len() as u32, + ..Default::default() + }; + for d in devices.values() { + match d.status { + DeviceStatus::Healthy => s.devices_healthy += 1, + DeviceStatus::Pending => s.devices_pending += 1, + DeviceStatus::Stale => s.devices_stale += 1, + DeviceStatus::Blacklisted => s.devices_blacklisted += 1, + DeviceStatus::Unknown => {} + } + } + for d in deployments.iter() { + match d.status { + DeploymentStatus::Active | DeploymentStatus::Rolling => s.deployments_active += 1, + DeploymentStatus::Failing => s.deployments_failing += 1, + DeploymentStatus::Paused => {} + } + } + Ok(s) + } + + async fn list_devices(&self) -> anyhow::Result> { + let mut out: Vec<_> = self.devices.lock().unwrap().values().cloned().collect(); + out.sort_by(|a, b| a.id.cmp(&b.id)); + Ok(out) + } + + async fn get_device(&self, id: &str) -> anyhow::Result> { + Ok(self.devices.lock().unwrap().get(id).cloned()) + } + + async fn list_deployments(&self) -> anyhow::Result> { + Ok(self.deployments.lock().unwrap().clone()) + } + + async fn blacklist_device(&self, id: &str) -> anyhow::Result { + let mut devices = self.devices.lock().unwrap(); + let dev = devices + .get_mut(id) + .ok_or_else(|| anyhow::anyhow!("device {id} not found"))?; + dev.status = DeviceStatus::Blacklisted; + dev.deployment = None; + Ok(dev.clone()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn dashboard_summary_counts_by_status() { + let svc = MockFleetService::default(); + let s = svc.dashboard_summary().await.unwrap(); + assert_eq!(s.devices_total, 10); + assert_eq!(s.devices_healthy, 4); + assert_eq!(s.devices_pending, 2); + assert_eq!(s.devices_stale, 2); + assert_eq!(s.devices_blacklisted, 1); + } + + #[tokio::test] + async fn blacklist_flips_status() { + let svc = MockFleetService::default(); + let before = svc.get_device("pi-001").await.unwrap().unwrap(); + assert_eq!(before.status, DeviceStatus::Healthy); + svc.blacklist_device("pi-001").await.unwrap(); + let after = svc.get_device("pi-001").await.unwrap().unwrap(); + assert_eq!(after.status, DeviceStatus::Blacklisted); + assert!(after.deployment.is_none()); + } +} diff --git a/fleet/harmony-fleet-operator/src/service/mod.rs b/fleet/harmony-fleet-operator/src/service/mod.rs new file mode 100644 index 00000000..50ebf351 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/service/mod.rs @@ -0,0 +1,99 @@ +//! Domain-level fleet query/command surface. +//! +//! Presentation (the `frontend` module) and any future CLI both call +//! into this trait. Implementations: +//! +//! - [`mock::MockFleetService`] — in-memory fake data, for `serve-web --mock` +//! and tests. Reachable without NATS or a Kubernetes cluster. +//! - `real::KubeNatsFleetService` (TODO) — wraps the operator's real +//! data sources (kube client + NATS JetStream KV). + +// The whole module is dead code when neither the web frontend nor any +// future CLI is compiled in — it's intentionally a library surface. +#![allow(dead_code)] + +pub mod mock; + +use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use serde::Serialize; + +#[async_trait] +pub trait FleetService: Send + Sync + 'static { + async fn dashboard_summary(&self) -> anyhow::Result; + async fn list_devices(&self) -> anyhow::Result>; + async fn get_device(&self, id: &str) -> anyhow::Result>; + async fn list_deployments(&self) -> anyhow::Result>; + async fn blacklist_device(&self, id: &str) -> anyhow::Result; +} + +#[derive(Debug, Clone, Serialize)] +pub struct DeviceSummary { + pub id: String, + pub status: DeviceStatus, + pub last_seen: DateTime, + pub deployment: Option, + pub ip: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum DeviceStatus { + Healthy, + Pending, + Stale, + Blacklisted, + Unknown, +} + +impl DeviceStatus { + pub fn label(self) -> &'static str { + match self { + DeviceStatus::Healthy => "healthy", + DeviceStatus::Pending => "pending", + DeviceStatus::Stale => "stale", + DeviceStatus::Blacklisted => "blacklisted", + DeviceStatus::Unknown => "unknown", + } + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct DeploymentSummary { + pub name: String, + pub status: DeploymentStatus, + pub target_devices: u32, + pub healthy_devices: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum DeploymentStatus { + Active, + Rolling, + Failing, + Paused, +} + +impl DeploymentStatus { + pub fn label(self) -> &'static str { + match self { + DeploymentStatus::Active => "active", + DeploymentStatus::Rolling => "rolling", + DeploymentStatus::Failing => "failing", + DeploymentStatus::Paused => "paused", + } + } +} + +#[derive(Debug, Clone, Default, Serialize)] +pub struct DashboardSummary { + pub devices_total: u32, + pub devices_healthy: u32, + pub devices_pending: u32, + pub devices_stale: u32, + pub devices_blacklisted: u32, + pub deployments_total: u32, + pub deployments_active: u32, + pub deployments_failing: u32, +} diff --git a/fleet/harmony-fleet-operator/style/input.css b/fleet/harmony-fleet-operator/style/input.css new file mode 100644 index 00000000..41db48a4 --- /dev/null +++ b/fleet/harmony-fleet-operator/style/input.css @@ -0,0 +1,4 @@ +@import "tailwindcss"; + +@source "../src"; +@source "../style"; diff --git a/fleet/harmony-fleet-operator/vendor/htmx-ext-sse.js b/fleet/harmony-fleet-operator/vendor/htmx-ext-sse.js new file mode 100644 index 00000000..9f5af5c5 --- /dev/null +++ b/fleet/harmony-fleet-operator/vendor/htmx-ext-sse.js @@ -0,0 +1,290 @@ +/* +Server Sent Events Extension +============================ +This extension adds support for Server Sent Events to htmx. See /www/extensions/sse.md for usage instructions. + +*/ + +(function() { + /** @type {import("../htmx").HtmxInternalApi} */ + var api + + htmx.defineExtension('sse', { + + /** + * Init saves the provided reference to the internal HTMX API. + * + * @param {import("../htmx").HtmxInternalApi} api + * @returns void + */ + init: function(apiRef) { + // store a reference to the internal API. + api = apiRef + + // set a function in the public API for creating new EventSource objects + if (htmx.createEventSource == undefined) { + htmx.createEventSource = createEventSource + } + }, + + getSelectors: function() { + return ['[sse-connect]', '[data-sse-connect]', '[sse-swap]', '[data-sse-swap]'] + }, + + /** + * onEvent handles all events passed to this extension. + * + * @param {string} name + * @param {Event} evt + * @returns void + */ + onEvent: function(name, evt) { + var parent = evt.target || evt.detail.elt + switch (name) { + case 'htmx:beforeCleanupElement': + var internalData = api.getInternalData(parent) + // Try to remove remove an EventSource when elements are removed + var source = internalData.sseEventSource + if (source) { + api.triggerEvent(parent, 'htmx:sseClose', { + source, + type: 'nodeReplaced', + }) + internalData.sseEventSource.close() + } + + return + + // Try to create EventSources when elements are processed + case 'htmx:afterProcessNode': + ensureEventSourceOnElement(parent) + } + } + }) + + /// //////////////////////////////////////////// + // HELPER FUNCTIONS + /// //////////////////////////////////////////// + + /** + * createEventSource is the default method for creating new EventSource objects. + * it is hoisted into htmx.config.createEventSource to be overridden by the user, if needed. + * + * @param {string} url + * @returns EventSource + */ + function createEventSource(url) { + return new EventSource(url, { withCredentials: true }) + } + + /** + * registerSSE looks for attributes that can contain sse events, right + * now hx-trigger and sse-swap and adds listeners based on these attributes too + * the closest event source + * + * @param {HTMLElement} elt + */ + function registerSSE(elt) { + // Add message handlers for every `sse-swap` attribute + if (api.getAttributeValue(elt, 'sse-swap')) { + // Find closest existing event source + var sourceElement = api.getClosestMatch(elt, hasEventSource) + if (sourceElement == null) { + // api.triggerErrorEvent(elt, "htmx:noSSESourceError") + return null // no eventsource in parentage, orphaned element + } + + // Set internalData and source + var internalData = api.getInternalData(sourceElement) + var source = internalData.sseEventSource + + var sseSwapAttr = api.getAttributeValue(elt, 'sse-swap') + var sseEventNames = sseSwapAttr.split(',') + + for (var i = 0; i < sseEventNames.length; i++) { + const sseEventName = sseEventNames[i].trim() + const listener = function(event) { + // If the source is missing then close SSE + if (maybeCloseSSESource(sourceElement)) { + return + } + + // If the body no longer contains the element, remove the listener + if (!api.bodyContains(elt)) { + source.removeEventListener(sseEventName, listener) + return + } + + // swap the response into the DOM and trigger a notification + if (!api.triggerEvent(elt, 'htmx:sseBeforeMessage', event)) { + return + } + swap(elt, event.data) + api.triggerEvent(elt, 'htmx:sseMessage', event) + } + + // Register the new listener + api.getInternalData(elt).sseEventListener = listener + source.addEventListener(sseEventName, listener) + } + } + + // Add message handlers for every `hx-trigger="sse:*"` attribute + if (api.getAttributeValue(elt, 'hx-trigger')) { + // Find closest existing event source + var sourceElement = api.getClosestMatch(elt, hasEventSource) + if (sourceElement == null) { + // api.triggerErrorEvent(elt, "htmx:noSSESourceError") + return null // no eventsource in parentage, orphaned element + } + + // Set internalData and source + var internalData = api.getInternalData(sourceElement) + var source = internalData.sseEventSource + + var triggerSpecs = api.getTriggerSpecs(elt) + triggerSpecs.forEach(function(ts) { + if (ts.trigger.slice(0, 4) !== 'sse:') { + return + } + + var listener = function (event) { + if (maybeCloseSSESource(sourceElement)) { + return + } + if (!api.bodyContains(elt)) { + source.removeEventListener(ts.trigger.slice(4), listener) + } + // Trigger events to be handled by the rest of htmx + htmx.trigger(elt, ts.trigger, event) + htmx.trigger(elt, 'htmx:sseMessage', event) + } + + // Register the new listener + api.getInternalData(elt).sseEventListener = listener + source.addEventListener(ts.trigger.slice(4), listener) + }) + } + } + + /** + * ensureEventSourceOnElement creates a new EventSource connection on the provided element. + * If a usable EventSource already exists, then it is returned. If not, then a new EventSource + * is created and stored in the element's internalData. + * @param {HTMLElement} elt + * @param {number} retryCount + * @returns {EventSource | null} + */ + function ensureEventSourceOnElement(elt, retryCount) { + if (elt == null) { + return null + } + + // handle extension source creation attribute + if (api.getAttributeValue(elt, 'sse-connect')) { + var sseURL = api.getAttributeValue(elt, 'sse-connect') + if (sseURL == null) { + return + } + + ensureEventSource(elt, sseURL, retryCount) + } + + registerSSE(elt) + } + + function ensureEventSource(elt, url, retryCount) { + var source = htmx.createEventSource(url) + + source.onerror = function(err) { + // Log an error event + api.triggerErrorEvent(elt, 'htmx:sseError', { error: err, source }) + + // If parent no longer exists in the document, then clean up this EventSource + if (maybeCloseSSESource(elt)) { + return + } + + // Otherwise, try to reconnect the EventSource + if (source.readyState === EventSource.CLOSED) { + retryCount = retryCount || 0 + retryCount = Math.max(Math.min(retryCount * 2, 128), 1) + var timeout = retryCount * 500 + window.setTimeout(function() { + ensureEventSourceOnElement(elt, retryCount) + }, timeout) + } + } + + source.onopen = function(evt) { + api.triggerEvent(elt, 'htmx:sseOpen', { source }) + + if (retryCount && retryCount > 0) { + const childrenToFix = elt.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]") + for (let i = 0; i < childrenToFix.length; i++) { + registerSSE(childrenToFix[i]) + } + // We want to increase the reconnection delay for consecutive failed attempts only + retryCount = 0 + } + } + + api.getInternalData(elt).sseEventSource = source + + + var closeAttribute = api.getAttributeValue(elt, "sse-close"); + if (closeAttribute) { + // close eventsource when this message is received + source.addEventListener(closeAttribute, function() { + api.triggerEvent(elt, 'htmx:sseClose', { + source, + type: 'message', + }) + source.close() + }); + } + } + + /** + * maybeCloseSSESource confirms that the parent element still exists. + * If not, then any associated SSE source is closed and the function returns true. + * + * @param {HTMLElement} elt + * @returns boolean + */ + function maybeCloseSSESource(elt) { + if (!api.bodyContains(elt)) { + var source = api.getInternalData(elt).sseEventSource + if (source != undefined) { + api.triggerEvent(elt, 'htmx:sseClose', { + source, + type: 'nodeMissing', + }) + source.close() + // source = null + return true + } + } + return false + } + + + /** + * @param {HTMLElement} elt + * @param {string} content + */ + function swap(elt, content) { + api.withExtensions(elt, function(extension) { + content = extension.transformResponse(content, null, elt) + }) + + var swapSpec = api.getSwapSpecification(elt) + var target = api.getTarget(elt) + api.swap(target, content, swapSpec) + } + + + function hasEventSource(node) { + return api.getInternalData(node).sseEventSource != null + } +})() diff --git a/fleet/harmony-fleet-operator/vendor/htmx.min.js b/fleet/harmony-fleet-operator/vendor/htmx.min.js new file mode 100644 index 00000000..37cd83ca --- /dev/null +++ b/fleet/harmony-fleet-operator/vendor/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.9"};Q.onLoad=j;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Nn;Q.find=f;Q.findAll=y;Q.closest=g;Q.remove=z;Q.addClass=G;Q.removeClass=b;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=$;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:U,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:A,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function q(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function A(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;A(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function N(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function I(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function D(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=N(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);I(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);I(r,i.body);r.title=i.title}else{const i=L('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){D(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function M(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function F(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function X(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function U(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function V(e){try{const t=new URL(e,window.location.href);e=t.pathname+t.search}catch(e){}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function $(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function y(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return y(te(),e)}}function x(){return window}function z(e,t){e=w(e);if(t){x().setTimeout(function(){z(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function J(e){return e instanceof HTMLElement?e:null}function K(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function G(e,t,n){e=ce(w(e));if(!e){return}if(n){x().setTimeout(function(){G(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function b(e,t,n){let r=ce(w(e));if(!r){return}if(n){x().setTimeout(function(){b(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){b(e,t)});G(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=q(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(q(t,!!n));i.push(...F(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(q(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(k(t)){return{target:te().body,event:K(e),listener:t,options:n}}else{return{target:w(e),event:K(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(A(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(A(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);$e(s,e,e,t,i);Re()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o,target:n})}return e}function Re(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(y(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ne(e){return function(){b(e,Q.config.addedClass);Ft(ce(e));Le(p(e));ae(e,"htmx:load")}}function Le(e){const t="[autofocus]";const n=J(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;G(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ne(o))}}}function Ie(e,t){let n=0;while(n0}function ze(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?q(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=P(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){x().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){x().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(M(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=x().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=x().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=x().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&B(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){x().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Nt(e){return e.form||g(e,"form")}function Lt(e){const t=At(e.target);if(!t){return}const n=Nt(t);if(!n){return}return oe(n)}function It(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){Pe(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!U()){return null}t=V(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);ze(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){ze(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;if(!e.hasAttribute("disabled")){e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")}});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){b(e,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0&&e.hasAttribute("data-disabled-by-htmx")){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return F(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return F(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Nt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=X(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){x().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Nn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function Ln(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const N=ee(f,"formmethod");if(N!=null){if(de.includes(N.toLowerCase())){t=N}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const L=d.split(":");const I=L[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(L[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Ln(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;let l=t.etc.push||ne(e,"hx-push-url");let c=t.etc.replace||ne(e,"hx-replace-url");if(l==="false")l=null;if(c==="false")c=null;const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};x().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file -- 2.39.5 From 96e7d43b2fb19b4f63cb90407d417d08537b28ef Mon Sep 17 00:00:00 2001 From: Reda Tarzalt Date: Tue, 19 May 2026 20:37:08 +0000 Subject: [PATCH 3/3] add auth to frontend through lib (#284) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds OIDC login support to the harmony-fleet-operator web dashboard using Zitadel SSO. pkce was the recommended option for this since we don't need to hold on to any secret. We compute a value on server before sending the data to Zitadel who validates authenticity by recomputing the hash and comparing the two values. pkce Auth flow 1. User visits a protected dashboard route, like /devices. 2. If no valid harmony_fleet_session cookie exists, the app redirects to /login. 3. /login creates: - random state - random pkce_code_verifier - derived code_challenge = base64url(sha256(pkce_code_verifier)) 4. The app stores state and pkce_code_verifier in a temporary HTTP-only login-attempt cookie. 5. The browser is redirected to Zitadel’s authorize endpoint with: - client_id - redirect_uri - scope - state - code_challenge - code_challenge_method=S256 6. After SSO login, Zitadel redirects back to /auth/callback?code=...&state=.... 7. The callback handler: - parses the raw query into a strict success/failure enum - reads the temporary login-attempt cookie - validates returned state - exchanges code + pkce_code_verifier for tokens - validates the returned ID token using OIDC discovery/JWKS - creates a local harmony_fleet_session cookie - redirects to / 8. Protected routes validate the local dashboard session cookie on each request. 9. /logout clears the dashboard session cookie and redirects to /login. --- Auth middleware responses depending on request type: - normal browser request: redirect to /login - SSE request: 401 authentication required - HTMX request: 401 with HX-Redirect: /login (HTMX redirect is more idiomatic than through Axum for this) Reviewed-on: https://git.nationtech.io/NationTech/harmony/pulls/284 Reviewed-by: johnride Co-authored-by: Reda Tarzalt Co-committed-by: Reda Tarzalt --- .cargo/config.toml | 3 + .env.example | 7 + .gitignore | 1 + Cargo.lock | 238 +++++- Cargo.toml | 1 + docs/SUMMARY.md | 1 + docs/guides/web-auth-security.md | 217 +++++ .../tests/security_model.rs | 3 + fleet/harmony-fleet-operator/Cargo.toml | 8 +- .../src/frontend/assets.rs | 1 + .../src/frontend/auth.rs | 6 + .../src/frontend/layout.rs | 199 ++++- .../src/frontend/mod.rs | 1 + .../src/frontend/server.rs | 619 +++++++++++++- .../src/frontend/views/alerts.rs | 125 +++ .../src/frontend/views/badges.rs | 91 ++ .../src/frontend/views/dashboard.rs | 376 ++++++++- .../src/frontend/views/deployments.rs | 603 +++++++++++++- .../src/frontend/views/devices.rs | 692 ++++++++++++++-- .../src/frontend/views/mod.rs | 3 + .../src/frontend/views/settings.rs | 70 ++ fleet/harmony-fleet-operator/src/main.rs | 16 + .../src/service/mock.rs | 777 ++++++++++++++---- .../harmony-fleet-operator/src/service/mod.rs | 174 +++- fleet/harmony-fleet-operator/style/input.css | 102 +++ fleet/harmony-fleet-operator/vendor/app.js | 3 + harmony_assets/src/store/local.rs | 1 + harmony_zitadel_auth/Cargo.toml | 30 + harmony_zitadel_auth/src/axum_login_flow.rs | 164 ++++ harmony_zitadel_auth/src/config.rs | 75 ++ harmony_zitadel_auth/src/jwks.rs | 210 +++++ harmony_zitadel_auth/src/lib.rs | 23 + harmony_zitadel_auth/src/login.rs | 228 +++++ harmony_zitadel_auth/src/session.rs | 21 + 34 files changed, 4740 insertions(+), 349 deletions(-) create mode 100644 .env.example create mode 100644 docs/guides/web-auth-security.md create mode 100644 fleet/harmony-fleet-operator/src/frontend/auth.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/alerts.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/badges.rs create mode 100644 fleet/harmony-fleet-operator/src/frontend/views/settings.rs create mode 100644 fleet/harmony-fleet-operator/vendor/app.js create mode 100644 harmony_zitadel_auth/Cargo.toml create mode 100644 harmony_zitadel_auth/src/axum_login_flow.rs create mode 100644 harmony_zitadel_auth/src/config.rs create mode 100644 harmony_zitadel_auth/src/jwks.rs create mode 100644 harmony_zitadel_auth/src/lib.rs create mode 100644 harmony_zitadel_auth/src/login.rs create mode 100644 harmony_zitadel_auth/src/session.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index a0b2a08a..d8baa144 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -6,3 +6,6 @@ rustflags = ["-C", "link-arg=-Wl,--stack,8000000"] [target.aarch64-unknown-linux-gnu] linker = "aarch64-linux-gnu-gcc" + +[profile.test] +debug = 0 diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..2f4ae554 --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +FLEET_AUTH_ISSUER_URL= +FLEET_AUTH_AUTHORIZE_URL= +FLEET_AUTH_TOKEN_URL= +FLEET_AUTH_CLIENT_ID= +FLEET_AUTH_REDIRECT_URI= +FLEET_AUTH_SCOPE= +FLEET_AUTH_TRUSTED_AUDIENCES= diff --git a/.gitignore b/.gitignore index 76ea8ec2..cce78a00 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ ### General ### private_repos/ +.env ### Harmony ### harmony.log diff --git a/Cargo.lock b/Cargo.lock index b627afeb..5344ac04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1010,6 +1010,81 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes 1.11.1", + "form_urlencoded", + "futures-util", + "http 1.4.0", + "http-body 1.0.1", + "http-body-util", + "hyper 1.8.1", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper 1.0.2", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes 1.11.1", + "futures-core", + "http 1.4.0", + "http-body 1.0.1", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper 1.0.2", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-extra" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9963ff19f40c6102c76756ef0a46004c0d58957d87259fc9208ff8441c12ab96" +dependencies = [ + "axum", + "axum-core", + "bytes 1.11.1", + "cookie 0.18.1", + "futures-util", + "http 1.4.0", + "http-body 1.0.1", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "serde_core", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "backon" version = "1.6.0" @@ -1739,6 +1814,21 @@ dependencies = [ "version_check", ] +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "aes-gcm", + "base64 0.22.1", + "percent-encoding", + "rand 0.8.5", + "subtle", + "time", + "version_check", +] + [[package]] name = "cookie_store" version = "0.20.0" @@ -3992,22 +4082,32 @@ version = "0.1.0" dependencies = [ "anyhow", "async-nats", + "async-trait", + "axum", + "axum-extra", + "base64 0.22.1", "chrono", "clap", + "dotenvy", "futures-util", "harmony", "harmony-fleet-auth", "harmony-reconciler-contracts", + "harmony_zitadel_auth", "k8s-openapi", "kube", + "maud", + "reqwest 0.12.28", "schemars 0.8.22", "serde", "serde_json", "thiserror 2.0.18", "tokio", + "tokio-stream", "toml", "tracing", "tracing-subscriber", + "url", ] [[package]] @@ -4352,6 +4452,29 @@ dependencies = [ "url", ] +[[package]] +name = "harmony_zitadel_auth" +version = "0.1.0" +dependencies = [ + "anyhow", + "arc-swap", + "axum", + "axum-extra", + "base64 0.22.1", + "chrono", + "jsonwebtoken", + "openidconnect", + "rand 0.9.2", + "reqwest 0.12.28", + "serde", + "serde_json", + "sha2", + "time", + "tokio", + "tracing", + "url", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -5111,6 +5234,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.13.0" @@ -5582,6 +5714,36 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "maud" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e" +dependencies = [ + "axum-core", + "http 1.4.0", + "itoa", + "maud_macros", +] + +[[package]] +name = "maud_macros" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.117", +] + [[package]] name = "md-5" version = "0.10.6" @@ -5870,6 +6032,26 @@ dependencies = [ "libc", ] +[[package]] +name = "oauth2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" +dependencies = [ + "base64 0.22.1", + "chrono", + "getrandom 0.2.17", + "http 1.4.0", + "rand 0.8.5", + "reqwest 0.12.28", + "serde", + "serde_json", + "serde_path_to_error", + "sha2", + "thiserror 1.0.69", + "url", +] + [[package]] name = "objc2" version = "0.6.4" @@ -5962,6 +6144,37 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openidconnect" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c6709ba2ea764bbed26bce1adf3c10517113ddea6f2d4196e4851757ef2b2" +dependencies = [ + "base64 0.21.7", + "chrono", + "dyn-clone", + "ed25519-dalek", + "hmac", + "http 1.4.0", + "itertools 0.10.5", + "log", + "oauth2", + "p256 0.13.2", + "p384", + "rand 0.8.5", + "rsa", + "serde", + "serde-value", + "serde_json", + "serde_path_to_error", + "serde_plain", + "serde_with", + "sha2", + "subtle", + "thiserror 1.0.69", + "url", +] + [[package]] name = "openssl-probe" version = "0.1.6" @@ -6615,6 +6828,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "version_check", +] + [[package]] name = "psl-types" version = "2.0.11" @@ -6817,7 +7042,7 @@ dependencies = [ "crossterm 0.28.1", "indoc", "instability", - "itertools", + "itertools 0.13.0", "lru", "paste", "strum 0.26.3", @@ -7718,6 +7943,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_plain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50" +dependencies = [ + "serde", +] + [[package]] name = "serde_repr" version = "0.1.20" @@ -9070,7 +9304,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" dependencies = [ - "itertools", + "itertools 0.13.0", "unicode-segmentation", "unicode-width 0.1.14", ] diff --git a/Cargo.toml b/Cargo.toml index 1cf47d01..9c382a89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "examples/*", "private_repos/*", "harmony", + "harmony_zitadel_auth", "harmony_types", "harmony_macros", "harmony_tui", diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index a61fbf68..10ae47c4 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -23,6 +23,7 @@ - [Writing a Score](./guides/writing-a-score.md) - [Writing a Topology](./guides/writing-a-topology.md) - [Adding Capabilities](./guides/adding-capabilities.md) +- [Web Authentication and CSRF Security](./guides/web-auth-security.md) ## Configuration diff --git a/docs/guides/web-auth-security.md b/docs/guides/web-auth-security.md new file mode 100644 index 00000000..8c52a52e --- /dev/null +++ b/docs/guides/web-auth-security.md @@ -0,0 +1,217 @@ +# Web Authentication and CSRF Security Guidelines + +These guidelines define the baseline for Harmony web frontends and future operator dashboards that use browser-based authentication, cookie sessions, Axum, HTMX, or OIDC providers such as Zitadel. + +## Goals + +- Prevent unauthenticated access. +- Prevent authenticated users from performing actions they are not authorized to perform. +- Prevent CSRF on state-changing endpoints. +- Reduce XSS impact with CSP and safe rendering practices. +- Keep authentication code understandable and reusable across projects. + +## Required Baseline + +Every browser-facing authenticated application must implement the following controls before production use: + +1. **OIDC Authorization Code + PKCE** for login. +2. **OIDC nonce validation** on login callback. +3. **Explicit authorization checks** using roles, groups, claims, or permissions. +4. **CSRF protection** on all mutating routes. +5. **Secure cookie settings**: `HttpOnly`, `Secure` in production, constrained `SameSite`, and appropriate path/domain scoping. +6. **Strict security headers**, especially Content Security Policy. +7. **No permissive credentialed CORS** for operator dashboards. +8. **Generic client-facing errors** with detailed errors logged server-side only. + +## OIDC Login Requirements + +Use Authorization Code flow with PKCE. On login start, generate and persist a short-lived login attempt containing: + +- `state` +- `pkce_code_verifier` +- `nonce` +- creation timestamp or cookie expiration + +Send `state`, PKCE challenge, and `nonce` to the authorization endpoint. + +On callback: + +1. Require a valid login-attempt cookie. +2. Validate returned `state` against the stored state. +3. Exchange the authorization code using the stored PKCE verifier. +4. Validate the returned ID token as an OIDC ID token, including: + - signature + - issuer + - audience/client ID + - expiration/not-before + - nonce + - authorized party (`azp`) when applicable +5. Create the application session only after all checks pass. +6. Delete the login-attempt cookie. + +`state` and `nonce` are not interchangeable: + +- `state` binds the callback redirect to the browser login attempt. +- `nonce` binds the returned ID token to the browser login attempt. +- PKCE binds the code exchange to the client that started the flow. + +## Session Requirements + +For small internal dashboards, a verified short-lived ID token in an `HttpOnly` cookie may be acceptable. For higher-risk systems, prefer server-side sessions: + +- Store a random session ID in the browser cookie. +- Store tokens and session metadata server-side. +- Support revocation, rotation, idle timeout, and absolute timeout. + +Session cookies must use: + +- `HttpOnly` +- `Secure` outside local development +- `SameSite=Lax` or `SameSite=Strict` +- `Path=/` unless a narrower path is possible +- No broad `Domain` attribute unless explicitly required + +Production services should fail closed if HTTPS/secure-cookie configuration is inconsistent. + +## Authorization Requirements + +Authentication is not authorization. A valid identity provider token only proves who the user is. + +Every protected application must define required permissions for each state-changing or sensitive route. Examples: + +- `fleet:viewer` for read-only dashboard access +- `fleet:operator` for alert acknowledgement and operational actions +- `fleet:admin` for settings, user management, or destructive actions + +Authorization must be enforced server-side. UI hiding is not sufficient. + +## CSRF Protection Standard + +For Axum + HTMX dashboards, the recommended baseline is: + +1. Require a custom header on all mutating requests. +2. Validate `Origin` or `Referer` against the configured application origin. +3. Keep cookies `SameSite=Lax` or stricter. +4. Do not enable permissive credentialed CORS. + +Mutating methods are: + +- `POST` +- `PUT` +- `PATCH` +- `DELETE` + +Recommended behavior: + +- Reject mutating requests without `x-csrf-token`. +- Reject mutating requests whose `Origin` is present and does not match the configured base URL origin. +- If `Origin` is absent, require `Referer` to match the configured base URL origin. +- Reject when neither `Origin` nor `Referer` is available, unless the route is explicitly exempted and documented. + +The CSRF header value may be static for HTMX dashboards, for example `x-csrf-token: 1`. The protection comes from the fact that cross-origin HTML forms cannot set custom headers, and cross-origin JavaScript cannot send custom headers with credentials unless CORS allows it. + +Do not rely on header presence alone if adding Origin/Referer validation is practical. + +## HTMX Integration + +Add the CSRF header globally from a static JavaScript file: + +```js +document.body.addEventListener('htmx:configRequest', (event) => { + event.detail.headers['x-csrf-token'] = '1'; +}); +``` + +Serve this as a static asset, for example `/static/app.js`. Avoid inline scripts so that the application can use a strict CSP without `unsafe-inline`. + +## Content Security Policy + +Every browser-facing dashboard should set a restrictive CSP. A good starting point is: + +```http +Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none' +``` + +Meaning: + +- Only load scripts, styles, and API/SSE/HTMX connections from the same origin. +- Prevent clickjacking with `frame-ancestors 'none'`. +- Prevent plugin/object execution with `object-src 'none'`. +- Prevent injected `` tags from rewriting relative URLs. +- Prevent forms from submitting to external origins. + +If inline scripts or styles are unavoidable, prefer per-response nonces over `unsafe-inline`. + +## Other Security Headers + +Set these headers on all HTML responses, or globally when safe: + +```http +X-Content-Type-Options: nosniff +Referrer-Policy: same-origin +Permissions-Policy: geolocation=(), microphone=(), camera=() +``` + +When the service is HTTPS-only, also set HSTS: + +```http +Strict-Transport-Security: max-age=31536000; includeSubDomains +``` + +Only enable HSTS when the domain and subdomains are intended to be HTTPS-only. + +## CORS Policy + +Operator dashboards should normally not enable CORS. + +Never combine all of the following unless there is a reviewed, explicit integration need: + +- credentialed requests +- arbitrary or reflected origins +- custom request headers such as `x-csrf-token` + +A permissive credentialed CORS policy can bypass custom-header CSRF protection. + +## Error Handling + +Client-facing auth errors should be generic, for example: + +```text +Authentication failed. Please start login again. +``` + +Detailed causes, provider responses, token validation failures, and stack traces should be logged server-side only. + +Avoid returning raw OIDC provider error bodies or JWT validation details to the browser. + +## Implementation Checklist + +Before shipping a Harmony web frontend: + +- [ ] Login uses Authorization Code + PKCE. +- [ ] Login attempt stores `state`, PKCE verifier, `nonce`, and expires quickly. +- [ ] Callback validates `state`. +- [ ] Callback validates ID token nonce. +- [ ] JWT validation checks issuer and exact intended audience/client. +- [ ] Authorization roles/permissions are enforced server-side. +- [ ] Mutating routes are protected by CSRF middleware. +- [ ] CSRF middleware requires custom header and same-origin `Origin`/`Referer`. +- [ ] Session cookies are `HttpOnly`, `Secure` in production, and `SameSite=Lax` or stricter. +- [ ] No permissive credentialed CORS is enabled. +- [ ] CSP is configured without `unsafe-inline` where practical. +- [ ] Security headers are configured. +- [ ] Auth errors shown to users are generic. +- [ ] Detailed auth failures are logged server-side. + +## Recommended Default for Harmony Dashboards + +For current and future Axum + HTMX dashboards, use this default design: + +- Zitadel/OIDC Authorization Code + PKCE + nonce. +- Short-lived encrypted login-attempt cookie. +- Server-side authorization middleware based on roles/claims. +- `HttpOnly`, `Secure`, `SameSite=Lax` or `Strict` session cookie. +- CSRF middleware requiring `x-csrf-token` and same-origin `Origin`/`Referer`. +- Static `/static/app.js` that adds the HTMX CSRF header. +- Strict CSP that allows scripts only from `self`. +- No CORS unless explicitly reviewed. diff --git a/examples/fleet_auth_callout/tests/security_model.rs b/examples/fleet_auth_callout/tests/security_model.rs index 9b1d05c8..80a54730 100644 --- a/examples/fleet_auth_callout/tests/security_model.rs +++ b/examples/fleet_auth_callout/tests/security_model.rs @@ -59,6 +59,7 @@ async fn connect_with_role(stack: &StackHandles, key_json: &str) -> Result Result<()> { let _ = tracing_subscriber::fmt().with_env_filter("info").try_init(); let stack = shared_stack().await?; @@ -84,6 +85,7 @@ async fn admin_can_read_any_device_subject() -> Result<()> { } #[tokio::test] +#[ignore = "requires k3d + docker environment"] async fn device_can_only_access_own_subjects() -> Result<()> { let _ = tracing_subscriber::fmt().with_env_filter("info").try_init(); let stack = shared_stack().await?; @@ -114,6 +116,7 @@ async fn device_can_only_access_own_subjects() -> Result<()> { } #[tokio::test] +#[ignore = "requires k3d + docker environment"] async fn unknown_role_is_rejected() -> Result<()> { let _ = tracing_subscriber::fmt().with_env_filter("info").try_init(); let stack = shared_stack().await?; diff --git a/fleet/harmony-fleet-operator/Cargo.toml b/fleet/harmony-fleet-operator/Cargo.toml index d4ef4d28..f272a067 100644 --- a/fleet/harmony-fleet-operator/Cargo.toml +++ b/fleet/harmony-fleet-operator/Cargo.toml @@ -11,12 +11,13 @@ default = [] # build time when the standalone `tailwindcss` CLI is on PATH; otherwise # the bundled CSS is empty and `--css-from ` must be used at runtime # (the sidecar-watch dev workflow does this). -web-frontend = ["dep:axum", "dep:maud", "dep:tokio-stream"] +web-frontend = ["dep:axum", "dep:axum-extra", "dep:maud", "dep:tokio-stream", "harmony_zitadel_auth/axum"] [dependencies] harmony = { path = "../../harmony", features = ["podman"] } harmony-fleet-auth = { path = "../harmony-fleet-auth" } harmony-reconciler-contracts = { path = "../../harmony-reconciler-contracts" } +harmony_zitadel_auth = { path = "../../harmony_zitadel_auth" } toml = { workspace = true } chrono = { workspace = true, features = ["serde"] } kube = { workspace = true, features = ["runtime", "derive"] } @@ -33,7 +34,12 @@ clap.workspace = true futures-util = { workspace = true } thiserror.workspace = true async-trait.workspace = true +url.workspace = true +base64.workspace = true +reqwest.workspace = true axum = { version = "0.8", optional = true } +axum-extra = { version = "0.10", features = ["cookie", "cookie-private"], optional = true } maud = { version = "0.27", features = ["axum"], optional = true } tokio-stream = { version = "0.1", optional = true } +dotenvy = "0.15" diff --git a/fleet/harmony-fleet-operator/src/frontend/assets.rs b/fleet/harmony-fleet-operator/src/frontend/assets.rs index 627bd85f..1b0be691 100644 --- a/fleet/harmony-fleet-operator/src/frontend/assets.rs +++ b/fleet/harmony-fleet-operator/src/frontend/assets.rs @@ -8,3 +8,4 @@ pub const TAILWIND_CSS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/tailwind.css")); pub const HTMX_JS: &[u8] = include_bytes!("../../vendor/htmx.min.js"); pub const HTMX_SSE_JS: &[u8] = include_bytes!("../../vendor/htmx-ext-sse.js"); +pub const APP_JS: &[u8] = include_bytes!("../../vendor/app.js"); diff --git a/fleet/harmony-fleet-operator/src/frontend/auth.rs b/fleet/harmony-fleet-operator/src/frontend/auth.rs new file mode 100644 index 00000000..e3d62567 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/auth.rs @@ -0,0 +1,6 @@ +pub use harmony_zitadel_auth::{JwksCache, VerifiedSession as DashboardSession}; + +pub use harmony_zitadel_auth::axum_login_flow::{ + HARMONY_SESSION_COOKIE as DASHBOARD_SESSION_COOKIE, callback_handler, login_handler, + logout_handler, +}; diff --git a/fleet/harmony-fleet-operator/src/frontend/layout.rs b/fleet/harmony-fleet-operator/src/frontend/layout.rs index be075ae7..7e039d58 100644 --- a/fleet/harmony-fleet-operator/src/frontend/layout.rs +++ b/fleet/harmony-fleet-operator/src/frontend/layout.rs @@ -1,8 +1,26 @@ -//! Page shell — ``, ``, top nav, body slot. - use maud::{DOCTYPE, Markup, PreEscaped, html}; -pub fn page(title: &str, live_reload: bool, content: Markup) -> Markup { +use crate::frontend::auth::DashboardSession; + +// ── Inline SVG icons ──────────────────────────────────────────────────── + +const ICON_DASHBOARD: &str = r#""#; +const ICON_DEVICES: &str = r#""#; +const ICON_DEPLOY: &str = r#""#; +const ICON_BELL: &str = r#""#; +const ICON_COG: &str = r#""#; +const ICON_LOGOUT: &str = r#""#; +const ICON_BRAND: &str = r#""#; + +/// Render a full page with sidebar + topbar layout. +pub fn page( + title: &str, + live_reload: bool, + current_path: &str, + session: Option<&DashboardSession>, + unacked_alerts: usize, + content: Markup, +) -> Markup { html! { (DOCTYPE) html lang="en" { @@ -13,30 +31,179 @@ pub fn page(title: &str, live_reload: bool, content: Markup) -> Markup { link rel="stylesheet" href="/static/tailwind.css"; script src="/static/htmx.min.js" defer {} script src="/static/htmx-ext-sse.js" defer {} + script src="/static/app.js" defer {} @if live_reload { script { (PreEscaped(LIVE_RELOAD_JS)) } } } - body class="min-h-screen bg-slate-950 text-slate-100" hx-ext="sse" { - header class="border-b border-slate-800 px-6 py-4 flex items-baseline gap-6" { - h1 class="text-xl font-semibold" { "Harmony Fleet Operator" } - nav class="flex gap-4 text-sm text-slate-400" { - a href="/" class="hover:text-slate-100" { "Dashboard" } - a href="/devices" class="hover:text-slate-100" { "Devices" } - a href="/deployments" class="hover:text-slate-100" { "Deployments" } - } - @if live_reload { - span class="ml-auto text-xs text-amber-400" { "dev · live reload" } + body class="min-h-screen" hx-ext="sse" style="background:var(--bg); color:#e2e8f0; font-family:'Inter',sans-serif" { + div class="flex h-screen overflow-hidden" style="background:var(--bg)" { + (sidebar(current_path, session, unacked_alerts)) + main class="flex-1 min-w-0 flex flex-col overflow-hidden" { + (topbar(title, unacked_alerts)) + div class="flex-1 overflow-y-auto grid-bg" { (content) } } } - main class="p-6 space-y-8" { (content) } + div id="modal-root" {} } } } } -/// Tiny inline script: reconnects an EventSource to `/__dev/reload`; -/// when the server comes back up after a restart, reload the page. +fn sidebar( + current_path: &str, + session: Option<&DashboardSession>, + unacked_alerts: usize, +) -> Markup { + let nav_items: [(&str, &str, &str, usize); 5] = [ + ("/", ICON_DASHBOARD, "Dashboard", 0), + ("/devices", ICON_DEVICES, "Devices", 0), + ("/deployments", ICON_DEPLOY, "Deployments", 0), + ("/alerts", ICON_BELL, "Alerts", unacked_alerts), + ("/settings", ICON_COG, "Settings", 0), + ]; + + html! { + aside class="shrink-0 flex flex-col border-r w-[224px]" style="border-color:var(--border); background:var(--bg)" { + div class="flex items-center justify-between px-4 py-4 border-b" style="border-color:var(--border)" { + div class="flex items-center gap-2" { + div class="relative w-6 h-6 rounded-md flex items-center justify-center" style="background:var(--accent); color:#0c0c0c" { + (PreEscaped(ICON_BRAND)) + } + span class="text-sm font-semibold tracking-tight text-slate-100" { "Harmony Fleet" } + } + } + + nav class="flex-1 px-2 py-3 space-y-0.5" { + @for (href, icon, label, badge) in &nav_items { + @let active = is_active(current_path, href); + a + href=(*href) + class={"group w-full flex items-center gap-2.5 px-2.5 h-9 rounded-md text-[13px] transition-colors duration-150 relative " + (if active { "text-slate-100 font-medium" } else { "text-slate-400 hover:text-slate-100" })} + style={(if active { "background:rgba(148,163,184,0.06)" } else { "background:transparent" })} + { + @if active { + span class="absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-r" style="background:var(--accent)" {} + } + span class={(if active { "text-slate-100" } else { "text-slate-500 group-hover:text-slate-300" })} { + (PreEscaped(icon)) + } + span class="flex-1 text-left" { (label) } + @if *badge > 0 { + span class="inline-flex items-center justify-center min-w-[18px] h-[18px] rounded-full text-[10px] font-semibold px-1" style="background:var(--bad); color:#0c0c0c" { + (badge) + } + } + } + } + } + + @if let Some(s) = session { + div class="border-t p-3" style="border-color:var(--border)" { + (user_footer(s)) + } + } + } + } +} + +fn user_footer(session: &DashboardSession) -> Markup { + let initials = session + .name + .as_deref() + .and_then(|name| { + let s: String = name + .split_whitespace() + .filter_map(|w| w.chars().next()) + .collect::() + .to_uppercase(); + if s.is_empty() { None } else { Some(s) } + }) + .unwrap_or_else(|| { + session + .subject + .chars() + .take(2) + .collect::() + .to_uppercase() + }); + + let display = session + .name + .as_deref() + .or(session.email.as_deref()) + .unwrap_or(&session.subject); + + html! { + div class="flex items-center gap-3" { + div class="flex items-center justify-center w-8 h-8 rounded-full text-[11px] font-medium text-slate-300 shrink-0" style="background:rgba(148,163,184,0.1)" { + (initials) + } + div class="min-w-0" { + p class="text-[13px] text-slate-200 truncate leading-tight" { (display) } + @if let Some(email) = session.email.as_deref() { + p class="text-[11px] text-slate-500 truncate leading-tight" { (email) } + } + } + } + a + href="/logout" + class="mt-2 flex items-center gap-1.5 text-[11px] text-slate-500 hover:text-rose-400 transition-colors" + { + (PreEscaped(ICON_LOGOUT)) + span { "Log out" } + } + } +} + +fn topbar(title: &str, unacked_alerts: usize) -> Markup { + html! { + div class="flex items-center justify-between px-6 h-14 border-b shrink-0" style="border-color:var(--border); background:var(--bg)" { + div class="flex items-center gap-3 min-w-0" { + div class="min-w-0" { + h1 class="text-[15px] font-semibold text-slate-100 flex items-center gap-2 truncate" { + (title) + } + } + } + div class="flex items-center gap-2" { + div class="relative" { + input + class="input w-64" + type="text" + name="search" + placeholder="Search devices, deployments\u{2026}" + hx-get="/devices/search" + hx-trigger="keyup changed delay:300ms" + hx-target="#device-table-wrapper" + hx-swap="innerHTML"; + } + a href="/alerts" class="relative btn btn-ghost py-1.5" { + (PreEscaped(ICON_BELL)) + span { "Alerts" } + @if unacked_alerts > 0 { + span class="ml-1 inline-flex items-center justify-center min-w-[18px] h-[18px] rounded-full text-[10px] font-semibold px-1" style="background:var(--bad); color:#0c0c0c" { + (unacked_alerts) + } + } + } + a href="/settings" class="btn btn-ghost py-1.5" title="Settings" { + (PreEscaped(ICON_COG)) + } + } + } + } +} + +fn is_active(current: &str, href: &str) -> bool { + if href == "/" { + current == "/" + } else { + current.starts_with(href) + } +} + const LIVE_RELOAD_JS: &str = r#" (function(){ let connected = false; diff --git a/fleet/harmony-fleet-operator/src/frontend/mod.rs b/fleet/harmony-fleet-operator/src/frontend/mod.rs index c14d8059..3735b677 100644 --- a/fleet/harmony-fleet-operator/src/frontend/mod.rs +++ b/fleet/harmony-fleet-operator/src/frontend/mod.rs @@ -9,6 +9,7 @@ //! future CLI. pub mod assets; +pub mod auth; pub mod layout; pub mod server; pub mod views; diff --git a/fleet/harmony-fleet-operator/src/frontend/server.rs b/fleet/harmony-fleet-operator/src/frontend/server.rs index 588404d3..035362b2 100644 --- a/fleet/harmony-fleet-operator/src/frontend/server.rs +++ b/fleet/harmony-fleet-operator/src/frontend/server.rs @@ -7,33 +7,64 @@ use std::time::Duration; use anyhow::Result; use axum::Router; use axum::body::Body; -use axum::extract::{Path, State}; -use axum::http::{StatusCode, header}; +use axum::extract::{Extension, FromRef, Path, Query, State}; +use axum::http::Request; +use axum::http::{HeaderValue, Method, StatusCode, header}; +use axum::middleware::{self, Next}; use axum::response::sse::{Event, KeepAlive, Sse}; -use axum::response::{IntoResponse, Response}; +use axum::response::{IntoResponse, Redirect, Response}; use axum::routing::{get, post}; +use axum_extra::extract::cookie::{Cookie, Key, PrivateCookieJar}; use maud::Markup; +use serde::Deserialize; use tokio_stream::StreamExt; +use tokio_stream::wrappers::IntervalStream; -use super::assets::{HTMX_JS, HTMX_SSE_JS, TAILWIND_CSS}; +use super::assets::{APP_JS, HTMX_JS, HTMX_SSE_JS, TAILWIND_CSS}; use super::layout::page; -use super::views::{dashboard, deployments as deployments_view, devices as devices_view}; +use super::views::{ + alerts as alerts_view, dashboard as dashboard_view, deployments as deployments_view, + devices as devices_view, settings as settings_view, +}; +use crate::frontend::auth::{self, DASHBOARD_SESSION_COOKIE, DashboardSession, JwksCache}; use crate::service::FleetService; +use harmony_zitadel_auth::ZitadelAuthConfig; -/// Default high port — keeps clear of NATS (4222), k8s API (6443), -/// and common metrics/webhook ports (8080/9090/9443). pub const DEFAULT_PORT: u16 = 18080; #[derive(Clone)] pub struct AppState { pub fleet: Arc, - /// Read Tailwind CSS from this path on every request when set. - /// Lets a sidecar `tailwindcss --watch` drive iteration without - /// recompiling the binary. + pub cookie_key: Key, pub css_override: Option, - /// When true, inject the live-reload script into pages and expose - /// `/__dev/reload`. pub live_reload: bool, + pub config: ZitadelAuthConfig, + pub http_client: reqwest::Client, + pub jwks: JwksCache, +} + +impl FromRef for Key { + fn from_ref(state: &AppState) -> Self { + state.cookie_key.clone() + } +} + +impl FromRef for ZitadelAuthConfig { + fn from_ref(state: &AppState) -> Self { + state.config.clone() + } +} + +impl FromRef for reqwest::Client { + fn from_ref(state: &AppState) -> Self { + state.http_client.clone() + } +} + +impl FromRef for JwksCache { + fn from_ref(state: &AppState) -> Self { + state.jwks.clone() + } } pub struct Config { @@ -56,20 +87,197 @@ impl Config { } pub fn router(state: AppState) -> Router { - let mut r = Router::new() - .route("/", get(dashboard_handler)) - .route("/devices", get(devices_handler)) - .route("/devices/{id}/blacklist", post(blacklist_handler)) - .route("/deployments", get(deployments_handler)) + let public_routes = Router::new() + .route("/login", get(auth::login_handler)) + .route("/auth/callback", get(auth::callback_handler)) .route("/static/tailwind.css", get(tailwind_css)) .route("/static/htmx.min.js", get(htmx_js)) - .route("/static/htmx-ext-sse.js", get(htmx_sse_js)); + .route("/static/htmx-ext-sse.js", get(htmx_sse_js)) + .route("/static/app.js", get(app_js)); + + let private_routes = Router::new() + // Dashboard + .route("/", get(dashboard_handler)) + // Devices + .route("/devices", get(devices_handler)) + .route("/devices/search", get(devices_search_handler)) + .route("/devices/{id}/blacklist", post(blacklist_handler)) + .route("/devices/{id}/logs", get(device_logs_handler)) + .route("/devices/{id}/logs/stream", get(device_logs_stream_handler)) + // Device detail + .route("/device/{id}", get(device_detail_handler)) + // Deployments + .route("/deployments", get(deployments_handler)) + .route("/deployment/{id}", get(deployment_handler)) + // Alerts + .route("/alerts", get(alerts_handler)) + .route("/alerts/{id}/ack", post(ack_alert_handler)) + // Settings + .route("/settings", get(settings_handler)) + .route("/settings/toggle/{key}", post(settings_toggle_handler)) + // Logout + .route("/logout", get(auth::logout_handler)) + .route_layer(middleware::from_fn_with_state(state.clone(), csrf_protect)) + .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)); + + let mut r = public_routes.merge(private_routes); if state.live_reload { r = r.route("/__dev/reload", get(dev_reload_sse)); } - r.with_state(state) + r.layer(middleware::from_fn_with_state( + state.clone(), + security_headers, + )) + .with_state(state) +} + +async fn require_auth( + State(state): State, + jar: PrivateCookieJar, + mut req: Request, + next: Next, +) -> Response { + let Some(cookie) = jar.get(DASHBOARD_SESSION_COOKIE) else { + return unauthenticated_response(&req); + }; + + match state.jwks.verify(cookie.value(), &state.config).await { + Ok(session) => { + req.extensions_mut().insert(session); + next.run(req).await + } + Err(e) => { + tracing::warn!(%e, "invalid session cookie"); + let jar = jar.remove(Cookie::from(DASHBOARD_SESSION_COOKIE)); + (jar, unauthenticated_response(&req)).into_response() + } + } +} + +async fn csrf_protect(State(state): State, req: Request, next: Next) -> Response { + if !is_mutating_method(req.method()) { + return next.run(req).await; + } + + if req.headers().get("x-csrf-token").is_none() { + return (StatusCode::FORBIDDEN, "CSRF check failed").into_response(); + } + + if !is_same_origin_request(&req, &state.config.base_url) { + return (StatusCode::FORBIDDEN, "CSRF origin check failed").into_response(); + } + + next.run(req).await +} + +fn is_mutating_method(method: &Method) -> bool { + matches!( + *method, + Method::POST | Method::PUT | Method::PATCH | Method::DELETE + ) +} + +fn is_same_origin_request(req: &Request, base_url: &str) -> bool { + let Ok(expected) = url::Url::parse(base_url) else { + tracing::error!(%base_url, "invalid BASE_URL; rejecting mutating request"); + return false; + }; + + if let Some(origin) = req + .headers() + .get(header::ORIGIN) + .and_then(|v| v.to_str().ok()) + { + return origin_matches(origin, &expected); + } + + req.headers() + .get(header::REFERER) + .and_then(|v| v.to_str().ok()) + .is_some_and(|referer| origin_matches(referer, &expected)) +} + +fn origin_matches(candidate: &str, expected: &url::Url) -> bool { + let Ok(candidate) = url::Url::parse(candidate) else { + return false; + }; + + candidate.scheme() == expected.scheme() + && candidate.host_str() == expected.host_str() + && candidate.port_or_known_default() == expected.port_or_known_default() +} + +async fn security_headers( + State(state): State, + req: Request, + next: Next, +) -> Response { + let mut response = next.run(req).await; + let headers = response.headers_mut(); + + let csp = if state.live_reload { + "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'" + } else { + "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'" + }; + + headers.insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static(csp), + ); + headers.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + headers.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("same-origin"), + ); + headers.insert( + "Permissions-Policy", + HeaderValue::from_static("geolocation=(), microphone=(), camera=()"), + ); + + if state.config.use_secure_cookies() { + headers.insert( + header::STRICT_TRANSPORT_SECURITY, + HeaderValue::from_static("max-age=31536000; includeSubDomains"), + ); + } + + response +} + +fn unauthenticated_response(req: &Request) -> Response { + if is_sse_request(req) { + return (StatusCode::UNAUTHORIZED, "authentication required").into_response(); + } + + if is_htmx_request(req) { + return Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header("HX-Redirect", "/login") + .body(Body::empty()) + .expect("well-formed HTMX auth response"); + } + + Redirect::to("/login").into_response() +} + +fn is_htmx_request(req: &Request) -> bool { + req.headers() + .get("HX-Request") + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value == "true") +} + +fn is_sse_request(req: &Request) -> bool { + req.headers() + .get(header::ACCEPT) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.contains("text/event-stream")) } pub async fn run(cfg: Config) -> Result<()> { @@ -80,27 +288,356 @@ pub async fn run(cfg: Config) -> Result<()> { Ok(()) } -// ---- handlers: each is a 3-liner: extract state, call service, render. ---- +// ── Dashboard ────────────────────────────────────────────────────────── -async fn dashboard_handler(State(s): State) -> Result { - let summary = s.fleet.dashboard_summary().await?; - Ok(page("Dashboard", s.live_reload, dashboard::page(&summary))) +async fn dashboard_handler( + State(s): State, + session: Option>, +) -> Result { + let detail = s.fleet.dashboard_detail().await?; + let unacked = detail.active_alerts.iter().filter(|a| !a.acked).count(); + Ok(page( + "Dashboard", + s.live_reload, + "/", + session.as_ref().map(|e| &e.0), + unacked, + dashboard_view::page(&detail), + )) } -async fn devices_handler(State(s): State) -> Result { - let devices = s.fleet.list_devices().await?; - Ok(page("Devices", s.live_reload, devices_view::page(&devices))) +// ── Devices ──────────────────────────────────────────────────────────── + +#[derive(Deserialize, Default)] +struct DevicesQuery { + status: Option, + deployment: Option, + region: Option, + search: Option, } -async fn deployments_handler(State(s): State) -> Result { +async fn devices_handler( + State(s): State, + Query(q): Query, + session: Option>, +) -> Result { + let status = q.status.as_deref().and_then(|s| parse_device_status(s)); + + let devices = s + .fleet + .filtered_devices( + status, + q.deployment.clone(), + q.region.clone(), + q.search.clone(), + ) + .await?; + + let all_devices = s.fleet.list_devices().await?; + let all_regions: Vec = { + let mut r: Vec = all_devices.iter().map(|d| d.region.clone()).collect(); + r.sort(); + r.dedup(); + r + }; + let all_deployments: Vec = { + let deps = s.fleet.list_deployments().await?; + deps.into_iter().map(|d| d.name).collect() + }; + + let unacked = s + .fleet + .list_alerts() + .await? + .iter() + .filter(|a| !a.acked) + .count(); + + Ok(page( + "Devices", + s.live_reload, + "/devices", + session.as_ref().map(|e| &e.0), + unacked, + devices_view::page( + &devices, + &all_regions, + &all_deployments, + status, + q.deployment.as_deref(), + q.region.as_deref(), + q.search.as_deref(), + ), + )) +} + +async fn devices_search_handler( + State(s): State, + Query(q): Query, +) -> Result { + let status = q.status.as_deref().and_then(|s| parse_device_status(s)); + + let devices = s + .fleet + .filtered_devices( + status, + q.deployment.clone(), + q.region.clone(), + q.search.clone(), + ) + .await?; + + Ok(devices_view::page( + &devices, + &[], + &[], + status, + q.deployment.as_deref(), + q.region.as_deref(), + q.search.as_deref(), + )) +} + +// ── Device detail ────────────────────────────────────────────────────── + +#[derive(Deserialize, Default)] +struct DeviceDetailQuery { + tab: Option, +} + +async fn device_detail_handler( + State(s): State, + Path(id): Path, + Query(q): Query, + session: Option>, +) -> Result { + let device = s + .fleet + .get_device(&id) + .await? + .ok_or_else(|| anyhow::anyhow!("device not found: {id}"))?; + + let deployment_version = if let Some(ref dep_name) = device.deployment { + s.fleet.get_deployment(dep_name).await?.map(|d| d.version) + } else { + None + }; + + let tab = q.tab.as_deref().unwrap_or("overview"); + + // If a specific tab is requested via query param, return tab content only (for HTMX) + if q.tab.is_some() { + return Ok(devices_view::tab_content( + &device, + tab, + deployment_version.as_deref(), + )); + } + + let unacked = s + .fleet + .list_alerts() + .await? + .iter() + .filter(|a| !a.acked) + .count(); + + Ok(page( + &device.id, + s.live_reload, + "/devices", + session.as_ref().map(|e| &e.0), + unacked, + devices_view::detail(&device, deployment_version.as_deref()), + )) +} + +// ── Deployments ──────────────────────────────────────────────────────── + +async fn deployments_handler( + State(s): State, + session: Option>, +) -> Result { let deployments = s.fleet.list_deployments().await?; + let unacked = s + .fleet + .list_alerts() + .await? + .iter() + .filter(|a| !a.acked) + .count(); + Ok(page( "Deployments", s.live_reload, + "/deployments", + session.as_ref().map(|e| &e.0), + unacked, deployments_view::page(&deployments), )) } +// ── Deployment detail ────────────────────────────────────────────────── + +#[derive(Deserialize, Default)] +struct DeploymentQuery { + tab: Option, + task_view: Option, +} + +async fn deployment_handler( + State(s): State, + Path(id): Path, + Query(q): Query, + session: Option>, +) -> Result { + let deployment = s + .fleet + .get_deployment(&id) + .await? + .ok_or_else(|| anyhow::anyhow!("deployment not found: {id}"))?; + + let devices = s.fleet.get_deployment_devices(&id).await?; + let task_graph = s.fleet.get_task_graph(&id).await?; + let task_view = q.task_view.as_deref().unwrap_or("linear"); + let tab = q.tab.as_deref().unwrap_or("overview"); + let unacked = s + .fleet + .list_alerts() + .await? + .iter() + .filter(|a| !a.acked) + .count(); + + if q.tab.is_some() && q.tab.as_deref() != Some("overview") { + // HTMX tab content only + Ok(deployments_view::tab_content( + &deployment, + &devices, + &task_graph, + task_view, + tab, + )) + } else { + Ok(page( + &deployment.name, + s.live_reload, + "/deployments", + session.as_ref().map(|e| &e.0), + unacked, + deployments_view::detail(&deployment, &devices, &task_graph, task_view), + )) + } +} + +// ── Alerts ───────────────────────────────────────────────────────────── + +async fn alerts_handler( + State(s): State, + session: Option>, +) -> Result { + let alerts = s.fleet.list_alerts().await?; + let unacked = alerts.iter().filter(|a| !a.acked).count(); + + Ok(page( + "Alerts", + s.live_reload, + "/alerts", + session.as_ref().map(|e| &e.0), + unacked, + alerts_view::page(&alerts), + )) +} + +async fn ack_alert_handler( + State(s): State, + Path(id): Path, +) -> Result { + s.fleet.ack_alert(&id).await?; + let alerts = s.fleet.list_alerts().await?; + let alert = alerts + .iter() + .find(|a| a.id == id) + .ok_or_else(|| anyhow::anyhow!("alert not found: {id}"))?; + + // Return just the row (for HTMX swap) + Ok(alerts_view::alert_row(alert)) +} + +// ── Settings ─────────────────────────────────────────────────────────── + +async fn settings_handler( + State(s): State, + session: Option>, +) -> Result { + let unacked = s + .fleet + .list_alerts() + .await? + .iter() + .filter(|a| !a.acked) + .count(); + + Ok(page( + "Settings", + s.live_reload, + "/settings", + session.as_ref().map(|e| &e.0), + unacked, + settings_view::page(), + )) +} + +async fn settings_toggle_handler(Path(_key): Path) -> Result { + // In a real app this would toggle a notification channel. + // For the mock, we return the same static content. + Ok(settings_view::page()) +} + +// ── Device logs ──────────────────────────────────────────────────────── + +async fn device_logs_handler(Path(id): Path) -> Result { + Ok(devices_view::logs_modal(&id)) +} + +async fn device_logs_stream_handler( + Path(id): Path, +) -> Sse>> { + let mut line_no = 0usize; + let stream = IntervalStream::new(tokio::time::interval(Duration::from_secs(1))).map( + move |_| { + line_no += 1; + let now = chrono::Utc::now().format("%H:%M:%S"); + let sevs = ["debug", "info", "info", "info", "info", "warn", "error"]; + let _sev = sevs[line_no % sevs.len()]; + let msgs = [ + "agent heartbeat ok (latency 12ms)", + "mqtt connection established to broker.harmony.local", + "reporting metrics batch (48 samples)", + "config reload requested by control-plane", + "task t4 (install deps) progress 73%", + "unexpected schema version v3, falling back", + "sensord pid=2841 started", + "gpu temp 54\u{b0}C \u{2014} within range", + "apt-get: package libsensor-7 not found", + "flushed 19 pending events to ingest", + "network jitter 84ms \u{2014} degrading to backup link", + "gc cycle complete in 47ms", + ]; + let msg = msgs[line_no % msgs.len()]; + let html = format!( + r#"
{now}{id} {msg}
"#, + ); + + Ok::<_, Infallible>(Event::default().event("log").data(html)) + }, + ); + + Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))) +} + +// ── Blacklist ────────────────────────────────────────────────────────── + async fn blacklist_handler( State(s): State, Path(id): Path, @@ -109,7 +646,21 @@ async fn blacklist_handler( Ok(devices_view::row(&updated)) } -// ---- static assets ---- +// ── Helpers ──────────────────────────────────────────────────────────── + +fn parse_device_status(s: &str) -> Option { + match s { + "healthy" => Some(crate::service::DeviceStatus::Healthy), + "pending" => Some(crate::service::DeviceStatus::Pending), + "failing" => Some(crate::service::DeviceStatus::Failing), + "stale" => Some(crate::service::DeviceStatus::Stale), + "blacklisted" => Some(crate::service::DeviceStatus::Blacklisted), + "unknown" => Some(crate::service::DeviceStatus::Unknown), + _ => None, + } +} + +// ── Static assets ────────────────────────────────────────────────────── async fn tailwind_css(State(s): State) -> Response { let css: Vec = match &s.css_override { @@ -136,6 +687,10 @@ async fn htmx_sse_js() -> Response { ) } +async fn app_js() -> Response { + static_response(APP_JS.to_vec(), "application/javascript; charset=utf-8") +} + fn static_response(bytes: Vec, content_type: &'static str) -> Response { Response::builder() .status(StatusCode::OK) @@ -144,19 +699,15 @@ fn static_response(bytes: Vec, content_type: &'static str) -> Response { .expect("well-formed static response") } -// ---- dev live-reload SSE ---- +// ── Dev live-reload SSE ──────────────────────────────────────────────── async fn dev_reload_sse() -> Sse>> { - // We never send actual reload events from here. The browser-side - // pattern is simpler: on EventSource reconnect after the server - // came back up, reload the page. So all we do is hold the - // connection open with keep-alive pings. let stream = tokio_stream::iter([Ok::<_, Infallible>(Event::default().data("ready"))]) .chain(tokio_stream::pending()); Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))) } -// ---- error type ---- +// ── Error type ───────────────────────────────────────────────────────── pub struct AppError(anyhow::Error); diff --git a/fleet/harmony-fleet-operator/src/frontend/views/alerts.rs b/fleet/harmony-fleet-operator/src/frontend/views/alerts.rs new file mode 100644 index 00000000..d3db66be --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/alerts.rs @@ -0,0 +1,125 @@ +use maud::{Markup, html}; + +use crate::frontend::views::badges; +use crate::service::Alert; + +pub fn page(alerts: &[Alert]) -> Markup { + let unacked = alerts.iter().filter(|a| !a.acked).count(); + html! { + div class="p-6 space-y-4" { + div class="flex items-center gap-2" { + h2 class="text-[15px] font-semibold text-slate-200" { "Alerts" } + span class="text-[11px] text-slate-500" { "\u{b7} " (unacked) " unacked" } + div class="flex-1" {} + button class="btn btn-ghost" { "Ack all" } + } + div class="card card-flush" { + table class="tbl" { + thead { + tr { + th style="width:32px" {} + th { "Severity" } + th { "Alert" } + th { "Source" } + th { "Time" } + th class="text-right" { "Action" } + } + } + tbody { + @for a in alerts { + tr class={(if a.acked { "opacity-50" } else { "" })} { + td { + @if !a.acked { + span class="w-1.5 h-1.5 rounded-full block" + style={"background:" (severity_color(a.severity))} {} + } + } + td { (badges::severity_pill(a.severity)) } + td class="text-slate-200" { (&a.title) } + td class="font-mono text-[12px] text-slate-400 whitespace-nowrap" { + @if let Some(dep) = &a.deployment { (dep) } + @else if let Some(dev) = &a.device { (dev) } + @else { "system" } + } + td class="text-[12px] text-slate-500 tabular-nums" { (&a.at) } + td class="text-right" { + div class="inline-flex items-center gap-1" { + @if a.deployment.is_some() { + a href={"/deployment/" (a.deployment.as_deref().unwrap())} class="btn btn-ghost py-1" { + "Open" + } + } @else if a.device.is_some() && a.deployment.is_none() { + a href={"/device/" (a.device.as_deref().unwrap())} class="btn btn-ghost py-1" { + "Open" + } + } + @if !a.acked { + button + class="btn btn-ghost py-1" + hx-post={"/alerts/" (a.id) "/ack"} + hx-target="closest tr" + hx-swap="outerHTML" { + "Ack" + } + } + } + } + } + } + } + } + } + } + } +} + +pub fn alert_row(a: &Alert) -> Markup { + html! { + tr class={(if a.acked { "opacity-50" } else { "" })} { + td { + @if !a.acked { + span class="w-1.5 h-1.5 rounded-full block" + style={"background:" (severity_color(a.severity))} {} + } + } + td { (badges::severity_pill(a.severity)) } + td class="text-slate-200" { (&a.title) } + td class="font-mono text-[12px] text-slate-400 whitespace-nowrap" { + @if let Some(dep) = &a.deployment { (dep) } + @else if let Some(dev) = &a.device { (dev) } + @else { "system" } + } + td class="text-[12px] text-slate-500 tabular-nums" { (&a.at) } + td class="text-right" { + div class="inline-flex items-center gap-1" { + @if a.deployment.is_some() { + a href={"/deployment/" (a.deployment.as_deref().unwrap())} class="btn btn-ghost py-1" { + "Open" + } + } @else if a.device.is_some() && a.deployment.is_none() { + a href={"/device/" (a.device.as_deref().unwrap())} class="btn btn-ghost py-1" { + "Open" + } + } + @if !a.acked { + button + class="btn btn-ghost py-1" + hx-post={"/alerts/" (a.id) "/ack"} + hx-target="closest tr" + hx-swap="outerHTML" { + "Ack" + } + } + } + } + } + } +} + +fn severity_color(s: crate::service::AlertSeverity) -> &'static str { + match s { + crate::service::AlertSeverity::Critical => "var(--bad)", + crate::service::AlertSeverity::Warning => "var(--warn)", + crate::service::AlertSeverity::Info => "var(--info)", + } +} diff --git a/fleet/harmony-fleet-operator/src/frontend/views/badges.rs b/fleet/harmony-fleet-operator/src/frontend/views/badges.rs new file mode 100644 index 00000000..e2b1f991 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/badges.rs @@ -0,0 +1,91 @@ +use maud::{Markup, html}; + +use crate::service::{AlertSeverity, DeploymentStatus, DeviceStatus}; + +pub fn device_status(s: DeviceStatus) -> Markup { + let (color, bg, border, label) = match s { + DeviceStatus::Healthy => ("var(--ok)", "var(--ok-soft)", "rgba(52,211,153,0.25)", "healthy"), + DeviceStatus::Pending => ( + "var(--warn)", + "var(--warn-soft)", + "rgba(251,191,36,0.25)", + "pending", + ), + DeviceStatus::Stale => ( + "var(--bad)", + "var(--bad-soft)", + "rgba(251,113,133,0.25)", + "stale", + ), + DeviceStatus::Failing => ( + "var(--bad)", + "var(--bad-soft)", + "rgba(251,113,133,0.25)", + "failing", + ), + DeviceStatus::Blacklisted => ( + "#94a3b8", + "rgba(148,163,184,0.10)", + "rgba(148,163,184,0.25)", + "blacklisted", + ), + DeviceStatus::Unknown => ( + "#64748b", + "rgba(100,116,139,0.10)", + "rgba(100,116,139,0.25)", + "unknown", + ), + }; + status_badge(label, color, bg, border) +} + +pub fn deployment_status(s: DeploymentStatus) -> Markup { + let (color, bg, border, label) = match s { + DeploymentStatus::Active => ("var(--ok)", "var(--ok-soft)", "#none", "active"), + DeploymentStatus::Rolling => ("var(--info)", "var(--info-soft)", "#none", "rolling"), + DeploymentStatus::Failing => ("var(--bad)", "var(--bad-soft)", "#none", "failing"), + DeploymentStatus::Paused => ("#94a3b8", "rgba(148,163,184,0.10)", "#none", "paused"), + }; + + let border_style = if border == "#none" { + "transparent" + } else { + border + }; + + status_badge(label, color, bg, border_style) +} + +pub fn severity_pill(s: AlertSeverity) -> Markup { + let (color, bg, icon, label) = match s { + AlertSeverity::Critical => ("var(--bad)", "var(--bad-soft)", ICON_ERROR, "critical"), + AlertSeverity::Warning => ("var(--warn)", "var(--warn-soft)", ICON_WARNING, "warning"), + AlertSeverity::Info => ("var(--info)", "var(--info-soft)", ICON_INFO, "info"), + }; + + html! { + span class="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[11px] font-medium" + style={"background:" (bg) "; color:" (color)} { + (PreEscaped(icon)) + (label) + } + } +} + +fn status_badge(label: &str, color: &str, bg: &str, border: &str) -> Markup { + html! { + span class="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[11px] font-medium id-mono" + style={"background:" (bg) "; color:" (color) "; border:1px solid " (border)} { + span class="inline-block rounded-full" style={"width:5px; height:5px; background:" (color)} {} + (label) + } + } +} + +// ── Tiny inline SVGs for severity icons ──────────────────────────────── + +const ICON_ERROR: &str = r#""#; +const ICON_WARNING: &str = r#""#; +const ICON_INFO: &str = r#""#; + +use maud::PreEscaped; diff --git a/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs b/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs index 1e2a0170..1bae27bf 100644 --- a/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs +++ b/fleet/harmony-fleet-operator/src/frontend/views/dashboard.rs @@ -1,35 +1,369 @@ -use maud::{Markup, html}; +use maud::{Markup, PreEscaped, html}; -use crate::service::DashboardSummary; +use crate::frontend::views::badges; +use crate::service::DashboardDetail; -pub fn page(summary: &DashboardSummary) -> Markup { +// ── Inline icons ──────────────────────────────────────────────────────── +const ICON_PLUS: &str = r#""#; +const ICON_CHEVRON: &str = r#""#; +const ICON_LIST: &str = r#""#; +const ICON_ERROR: &str = r#""#; +const ICON_WARNING: &str = r#""#; + +pub fn page(d: &DashboardDetail) -> Markup { html! { - section { - h2 class="text-lg font-medium mb-4 text-slate-300" { "Devices" } - div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4" { - (card("Total", &summary.devices_total.to_string(), "text-slate-50")) - (card("Healthy", &summary.devices_healthy.to_string(), "text-emerald-400")) - (card("Pending", &summary.devices_pending.to_string(), "text-amber-400")) - (card("Stale", &summary.devices_stale.to_string(), "text-rose-400")) - (card("Blacklisted", &summary.devices_blacklisted.to_string(), "text-slate-500")) + div class="p-6 space-y-5" { + // Alert strip (if there are unacked alerts) + @if !d.active_alerts.is_empty() { + @let top = &d.active_alerts[0]; + @let more = d.active_alerts.len().saturating_sub(1); + (alert_strip(top, more)) } + + (health_row(d)) + (lower_row(d)) } - section { - h2 class="text-lg font-medium mb-4 text-slate-300" { "Deployments" } - div class="grid grid-cols-2 sm:grid-cols-3 gap-4" { - (card("Total", &summary.deployments_total.to_string(), "text-slate-50")) - (card("Active / Rolling", &summary.deployments_active.to_string(), "text-emerald-400")) - (card("Failing", &summary.deployments_failing.to_string(), "text-rose-400")) + } +} + +fn alert_strip(alert: &crate::service::Alert, more: usize) -> Markup { + let is_crit = matches!(alert.severity, crate::service::AlertSeverity::Critical); + let border = if is_crit { "rgba(244,63,94,0.3)" } else { "rgba(251,191,36,0.3)" }; + let bg = if is_crit { "rgba(244,63,94,0.06)" } else { "rgba(251,191,36,0.06)" }; + let icon_bg = if is_crit { "var(--bad-soft)" } else { "var(--warn-soft)" }; + let icon_color = if is_crit { "var(--bad)" } else { "var(--warn)" }; + + html! { + div class="card flex items-center gap-3 px-4 py-3" style={"border-color:" (border) "; background:" (bg)} { + span class="inline-flex items-center justify-center w-7 h-7 rounded-md" style={"background:" (icon_bg) "; color:" (icon_color)} { + @if is_crit { (PreEscaped(ICON_ERROR)) } @else { (PreEscaped(ICON_WARNING)) } + } + div class="min-w-0 flex-1" { + div class="text-[13px] text-slate-100 leading-snug truncate" { (&alert.title) } + div class="text-[11px] text-slate-500 mt-0.5" { + (&alert.at) + @if more > 0 { + span class="ml-2" { "\u{b7} " (more) " more alert" @if more > 1 { "s" } } + } + } + } + @if alert.deployment.is_some() { + a href={"/deployment/" (alert.deployment.as_deref().unwrap())} class="btn btn-ghost" { "Open deployment" } + } @else if alert.device.is_some() { + a href={"/device/" (alert.device.as_deref().unwrap())} class="btn btn-ghost" { "Open device" } + } + button + class="btn btn-ghost" + hx-post={"/alerts/" (alert.id) "/ack"} + hx-swap="none" + { "Ack" } + } + } +} + +fn health_row(d: &DashboardDetail) -> Markup { + let health_trend_svg = sparkline_svg(&d.health_trend, "var(--ok)", 180.0, 36.0, "ok"); + let ingest_trend_svg = sparkline_svg_u32(&d.ingest_trend, "var(--accent)", 240.0, 56.0, "ac"); + + html! { + div class="grid grid-cols-12 gap-4" { + // Big health card + div class="col-span-12 lg:col-span-5 card p-5 relative overflow-hidden" { + div class="flex items-start justify-between" { + div { + div class="section-title" { "Fleet Health" } + div class="mt-2 flex items-baseline gap-3" { + span class="text-[44px] font-semibold tracking-tight tabular-nums leading-none text-slate-50" { + (d.health_pct) "%" + } + span class="text-sm text-slate-400" { + "healthy across " (d.devices_total) " devices" + } + } + div class="mt-1.5 flex items-center gap-1.5 text-[11px] text-slate-500" { + span class="text-emerald-400" { "\u{25b2} 1.2%" } + span { "vs. 24h ago" } + } + } + div class="flex items-center gap-1.5 text-[11px] text-slate-400" { + span class="relative inline-flex w-1.5 h-1.5" { + span class="absolute inline-flex h-full w-full animate-ping rounded-full opacity-60" style="background:var(--ok)" {} + span class="relative inline-flex w-1.5 h-1.5 rounded-full" style="background:var(--ok)" {} + } + span { "live" } + } + } + + div class="mt-4" { + (segmented_progress( + &[ + (0u32, d.devices_healthy, "var(--ok)", "healthy"), + (0u32, d.devices_pending, "var(--warn)", "pending"), + (0u32, d.devices_failing, "var(--bad)", "failing"), + (0u32, d.devices_stale, "rgba(251,113,133,0.6)", "stale"), + (0u32, d.devices_blacklisted, "#475569", "blacklisted"), + (0u32, d.devices_unknown, "#334155", "unknown"), + ], + d.devices_total, + 6, + )) + } + + div class="mt-4 grid grid-cols-3 gap-x-6 gap-y-2 text-[12px]" { + (stat("Healthy", d.devices_healthy, "var(--ok)")) + (stat("Pending", d.devices_pending, "var(--warn)")) + (stat("Failing", d.devices_failing, "var(--bad)")) + (stat("Stale", d.devices_stale, "rgba(251,113,133,0.7)")) + (stat("Blacklisted", d.devices_blacklisted, "#94a3b8")) + (stat("Unknown", d.devices_unknown, "#64748b")) + } + + div class="absolute right-5 bottom-3 opacity-90 pointer-events-none" { + (PreEscaped(health_trend_svg)) + div class="text-[10px] text-slate-600 font-mono text-right mt-0.5" { "24h health" } + } + } + + // Deployment summary + div class="col-span-12 lg:col-span-4 card p-5" { + div class="flex items-center justify-between" { + div { + div class="section-title" { "Deployments" } + div class="mt-2 text-[28px] font-semibold text-slate-50 tabular-nums leading-none" { + (d.deployments_total) + } + div class="text-[12px] text-slate-500 mt-1" { + (d.rolling_count) " rolling out \u{b7} " (d.failing_count) " failing" + } + } + a href="/deployments" class="btn btn-ghost" { + (PreEscaped(ICON_PLUS)) " New deployment" + } + } + + div class="mt-5 space-y-1" { + @for dep in &d.top_deployments { + a href={"/deployment/" (dep.name)} class="w-full text-left flex items-center gap-3 py-1.5 px-1 rounded hover:bg-white/2.5" { + div class="flex-1 min-w-0" { + div class="flex items-center gap-2" { + span class="font-mono text-[12px] text-slate-200 truncate whitespace-nowrap" { (&dep.name) } + span class="font-mono text-[10px] text-slate-500 whitespace-nowrap shrink-0" { (&dep.version) } + } + div class="mt-1 flex items-center gap-2" { + div class="flex-1 max-w-[140px]" { + (segmented_progress( + &[ + (0u32, dep.healthy, "var(--ok)", "healthy"), + (0u32, dep.pending, "var(--warn)", "pending"), + (0u32, dep.failing, "var(--bad)", "failing"), + ], + dep.target, + 3, + )) + } + span class="text-[10px] text-slate-500 tabular-nums" { (dep.healthy) "/" (dep.target) } + } + } + (badges::deployment_status(dep.status)) + } + } + } + } + + // Ingest rate + div class="col-span-12 lg:col-span-3 card p-5" { + div class="section-title" { "Ingest rate" } + div class="mt-2 flex items-baseline gap-2" { + span class="text-[28px] font-semibold text-slate-50 tabular-nums leading-none" { (d.ingest_rate) } + span class="text-[12px] text-slate-500" { "k events/min" } + } + div class="mt-3" { + (PreEscaped(ingest_trend_svg)) + } + div class="flex justify-between text-[10px] text-slate-600 font-mono mt-1" { + span { "\u{2212}24h" } + span { "now" } + } } } } } -fn card(title: &str, value: &str, value_class: &str) -> Markup { +fn lower_row(d: &DashboardDetail) -> Markup { html! { - div class="rounded-lg border border-slate-800 bg-slate-900 p-4" { - div class="text-xs uppercase tracking-wide text-slate-400" { (title) } - div class={"mt-2 text-3xl font-semibold " (value_class)} { (value) } + div class="grid grid-cols-12 gap-4" { + // Needs attention + div class="col-span-12 lg:col-span-7 card" { + div class="flex items-center justify-between px-4 py-3 border-b" style="border-color:var(--border)" { + div class="flex items-center gap-2" { + span class="section-title" { "Needs attention" } + span class="text-[10px] text-slate-600 font-mono" { + (d.attention_devices.len()) " devices" + } + } + a href="/devices?status=failing" class="text-[11px] text-slate-400 hover:text-slate-100 flex items-center gap-1" { + "View all " (PreEscaped(ICON_CHEVRON)) + } + } + table class="tbl" { + thead { + tr { + th { "Device" } + th { "Status" } + th { "Deployment" } + th { "Last seen" } + th class="text-right" { "Action" } + } + } + tbody { + @for dev in &d.attention_devices { + tr class="cursor-pointer" + hx-get={"/device/" (dev.id)} + hx-target="closest main" + hx-push-url="true" { + td { + span class="font-mono text-slate-100 whitespace-nowrap" { (&dev.id) } + } + td { (badges::device_status(dev.status)) } + td class="text-slate-300 font-mono text-[12px] whitespace-nowrap" { + @if let Some(dep) = &dev.deployment { (dep) } + @else { "\u{2014}" } + } + td class="text-slate-500 text-[12px] tabular-nums" { + (time_ago(dev.minutes_ago)) + } + td class="text-right" { + button + class="btn btn-ghost py-1" + hx-get={"/devices/" (dev.id) "/logs"} + hx-target="#modal-root" + hx-swap="innerHTML" + onclick="event.stopPropagation();" { + (PreEscaped(ICON_LIST)) " Logs" + } + } + } + } + } + } + } + + // Activity feed + div class="col-span-12 lg:col-span-5 card" { + div class="flex items-center justify-between px-4 py-3 border-b" style="border-color:var(--border)" { + span class="section-title" { "Activity" } + span class="text-[10px] text-slate-600 font-mono" { "live" } + } + ul class="px-4 py-1 space-y-0" { + @for (i, a) in d.activity_feed.iter().enumerate() { + @let border = if i < d.activity_feed.len() - 1 { "border-b" } else { "" }; + li class={"flex items-start gap-3 py-2.5 text-[13px] " (border)} style="border-color:var(--border)" { + span class="font-mono text-[10px] text-slate-600 mt-1 w-10 shrink-0 tabular-nums" { (&a.at) } + span class="text-slate-400 leading-snug" { + span class={(if a.who == "system" { "text-slate-500" } else { "text-slate-200" })} { (&a.who) } + span { " " (a.verb) " " } + @if !a.target.is_empty() { + span class="font-mono text-slate-300 whitespace-nowrap" { (&a.target) } + } + } + } + } + } + } } } } + +fn stat(label: &str, value: u32, color: &str) -> Markup { + html! { + div class="flex items-center gap-1.5" { + span class="w-1.5 h-1.5 rounded-full" style={"background:" (color)} {} + span class="text-slate-500" { (label) } + span class="ml-auto font-mono text-slate-200 tabular-nums" { (value) } + } + } +} + +fn time_ago(minutes: i64) -> String { + if minutes < 1 { + "just now".into() + } else if minutes < 60 { + format!("{}m ago", minutes) + } else if minutes < 60 * 24 { + format!("{}h ago", minutes / 60) + } else { + format!("{}d ago", minutes / (60 * 24)) + } +} + +// ── Segmented progress bar ───────────────────────────────────────────── + +fn segmented_progress(segments: &[(u32, u32, &str, &str)], total: u32, height: u32) -> Markup { + html! { + div class="w-full rounded-full overflow-hidden progress-bg flex" style={"height:" (height) "px"} { + @for (_cum, val, color, _label) in segments { + @let width = if total > 0 { + (*val as f64 / total as f64) * 100.0 + } else { 0.0 }; + div class="h-full" style={"width:" (width) "%; background:" (color)} {} + } + } + } +} + +// ── Sparkline SVG generators ─────────────────────────────────────────── + +pub fn sparkline_svg(values: &[f64], color: &str, w: f64, h: f64, prefix: &str) -> String { + let max = values.iter().cloned().fold(0.0f64, f64::max).max(1.0); + let min = values.iter().cloned().fold(f64::MAX, f64::min).min(0.0); + let range = (max - min).max(1.0); + let step = w / (values.len().max(2) - 1) as f64; + let pts: Vec<(f64, f64)> = values + .iter() + .enumerate() + .map(|(i, &v)| (i as f64 * step, h - ((v - min) / range) * (h - 4.0) - 2.0)) + .collect(); + + let path = pts + .iter() + .enumerate() + .map(|(i, (x, y))| { + if i == 0 { + format!("M {:.1} {:.1}", x, y) + } else { + format!("L {:.1} {:.1}", x, y) + } + }) + .collect::>() + .join(" "); + + let area = format!("{} L {:.0} {:.0} L {:.0} {:.0} Z", path, w, h, 0.0, h); + let (lx, ly) = pts.last().copied().unwrap_or((0.0, 0.0)); + let gradient_id = format!("spark-{prefix}"); + + format!( + r#" + + + + + + + + +"#, + w = w, + h = h, + gid = gradient_id, + color = color, + area = area, + path = path, + lx = lx, + ly = ly, + ) +} + +fn sparkline_svg_u32(values: &[u32], color: &str, w: f64, h: f64, prefix: &str) -> String { + let floats: Vec = values.iter().map(|&v| v as f64).collect(); + sparkline_svg(&floats, color, w, h, prefix) +} diff --git a/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs b/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs index cd13d4cb..7e687d9d 100644 --- a/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs +++ b/fleet/harmony-fleet-operator/src/frontend/views/deployments.rs @@ -1,31 +1,285 @@ -use maud::{Markup, html}; +use maud::{Markup, PreEscaped, html}; -use crate::service::{DeploymentStatus, DeploymentSummary}; +use crate::frontend::views::badges; +use crate::service::{DeploymentDetail, DeviceDetail, TaskGraph, TaskNode, TaskStatus}; -pub fn page(deployments: &[DeploymentSummary]) -> Markup { +// ── Inline icons ──────────────────────────────────────────────────────── +const ICON_PLUS: &str = r#""#; +const ICON_EXTERNAL: &str = r#""#; +const ICON_REFRESH: &str = r#""#; +const ICON_PLAY: &str = r#""#; +const ICON_PAUSE: &str = r#""#; +const ICON_ROLLBACK: &str = r#""#; +const ICON_DEPLOY: &str = r#""#; +const ICON_LIST: &str = r#""#; +const ICON_GRAPH: &str = r#""#; +const ICON_DRAG: &str = r#""#; +const ICON_MORE: &str = r#""#; +const ICON_CHECK: &str = r#""#; +const ICON_CLOSE: &str = r#""#; + +// ── Deployments list page ────────────────────────────────────────────── + +pub fn page(deployments: &[DeploymentDetail]) -> Markup { html! { - section { - div class="flex items-baseline gap-3 mb-4" { - h2 class="text-lg font-medium text-slate-300" { "Deployments" } - span class="text-xs text-slate-500" { (deployments.len()) " total" } + div class="p-6 space-y-4" { + div class="flex items-center gap-2" { + h2 class="text-[15px] font-semibold text-slate-200" { "All deployments" } + span class="text-[11px] text-slate-500" { "\u{b7} " (deployments.len()) } + div class="flex-1" {} + button class="btn btn-primary" { (PreEscaped(ICON_PLUS)) " New deployment" } } - div class="overflow-x-auto rounded-lg border border-slate-800" { - table class="min-w-full divide-y divide-slate-800 text-sm" { - thead class="bg-slate-900 text-xs uppercase tracking-wide text-slate-400" { - tr { - th class="px-3 py-2 text-left font-medium" { "Name" } - th class="px-3 py-2 text-left font-medium" { "Status" } - th class="px-3 py-2 text-left font-medium" { "Health" } + div class="grid grid-cols-1 lg:grid-cols-2 gap-4" { + @for d in deployments { + (deployment_card(d)) + } + } + style { (PreEscaped(r#"@keyframes roll-marquee { 0% { transform: translateX(-100%); } 100% { transform: translateX(400%); } }"#)) } + } + } +} + +fn deployment_card(d: &DeploymentDetail) -> Markup { + html! { + a href={"/deployment/" (d.name)} class="card text-left p-5 hover:border-slate-700 transition-colors relative overflow-hidden group block" { + div class="flex items-start justify-between gap-4" { + div class="min-w-0" { + div class="flex items-center gap-2" { + h3 class="font-mono text-[15px] text-slate-100 truncate" { (&d.name) } + span class="font-mono text-[11px] text-slate-500 whitespace-nowrap shrink-0" { (&d.version) } + } + div class="text-[11px] text-slate-500 mt-1" { + "Last updated " (d.updated_at) " \u{b7} by " + span class="text-slate-400" { (&d.author) } + } + } + (badges::deployment_status(d.status)) + } + + div class="mt-4 flex items-end justify-between gap-6" { + div class="flex-1 min-w-0" { + div class="flex items-baseline gap-2" { + span class="text-[26px] font-semibold text-slate-100 tabular-nums leading-none" { (d.healthy) } + span class="text-[12px] text-slate-500" { "/ " (d.target) " healthy" } + } + div class="mt-2" { + (segmented_progress(d, 5)) + } + div class="mt-2 flex gap-4 text-[11px] text-slate-500 font-mono" { + span { span style="color:var(--ok)" { "\u{25cf}" } " " (d.healthy) " healthy" } + @if d.pending > 0 { + span { span style="color:var(--warn)" { "\u{25cf}" } " " (d.pending) " pending" } + } + @if d.failing > 0 { + span { span style="color:var(--bad)" { "\u{25cf}" } " " (d.failing) " failing" } } } - tbody class="divide-y divide-slate-800 bg-slate-950" { - @for d in deployments { - tr { - td class="px-3 py-2 font-mono text-slate-200" { (d.name) } - td class="px-3 py-2" { (status_badge(d.status)) } - td class="px-3 py-2 text-slate-300" { - (d.healthy_devices) " / " (d.target_devices) " healthy" + } + div class="text-right shrink-0" { + div class="text-[10px] text-slate-600 font-mono uppercase tracking-wider" { "Tasks" } + div class="font-mono text-[12px] text-slate-300 mt-1" { "8 steps \u{b7} DAG" } + div class="mt-2 text-(--accent-fg) text-[11px] flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity" { + "Open " (PreEscaped(ICON_EXTERNAL)) + } + } + } + + @if d.status == crate::service::DeploymentStatus::Rolling { + span class="absolute top-0 left-0 right-0 h-0.5 overflow-hidden" { + span class="block h-full w-1/3" style="background:var(--info); animation:roll-marquee 2.4s linear infinite" {} + } + } + } + } +} + +// ── Deployment detail page ───────────────────────────────────────────── + +pub fn detail( + deployment: &DeploymentDetail, + devices: &[DeviceDetail], + task_graph: &TaskGraph, + task_view: &str, +) -> Markup { + let pct = if deployment.target > 0 { + ((deployment.healthy as f64 / deployment.target as f64) * 100.0).round() as u32 + } else { + 0 + }; + + html! { + div class="p-6 space-y-4" { + // Header + div class="card p-5" { + div class="flex items-start justify-between gap-6" { + div class="min-w-0" { + div class="flex items-center gap-3 flex-wrap" { + h1 class="text-[22px] font-semibold font-mono text-slate-50 truncate whitespace-nowrap" { + (&deployment.name) + } + (badges::deployment_status(deployment.status)) + span class="font-mono text-[11px] text-slate-500 whitespace-nowrap shrink-0" { + (&deployment.version) + } + } + div class="mt-2 flex items-center gap-x-5 gap-y-1 text-[12px] text-slate-500" { + span { span class="text-slate-600" { "Targets" } " " span class="text-slate-300 font-mono" { (deployment.target) " devices" } } + span { span class="text-slate-600" { "Updated" } " " span class="text-slate-300 tabular-nums" { (&deployment.updated_at) } } + span { span class="text-slate-600" { "By" } " " span class="text-slate-300" { (&deployment.author) } } + } + } + div class="flex items-center gap-2 shrink-0" { + button class="btn btn-ghost" { (PreEscaped(ICON_REFRESH)) " Reconcile" } + @if deployment.status == crate::service::DeploymentStatus::Paused { + button class="btn btn-ghost" { (PreEscaped(ICON_PLAY)) " Resume" } + } @else { + button class="btn btn-ghost" { (PreEscaped(ICON_PAUSE)) " Pause" } + } + button class="btn btn-ghost" { (PreEscaped(ICON_ROLLBACK)) " Rollback" } + button class="btn btn-primary" { (PreEscaped(ICON_DEPLOY)) " Roll out" } + } + } + + // Rollout progress + div class="mt-5 grid grid-cols-12 gap-5" { + div class="col-span-12 md:col-span-8" { + div class="flex items-baseline justify-between gap-3 mb-2" { + span class="text-[11px] text-slate-500 uppercase tracking-wider whitespace-nowrap" { + "Rollout progress" + } + span class="text-[12px] text-slate-300 font-mono tabular-nums whitespace-nowrap" { + (pct) "% complete" + } + } + (segmented_progress(deployment, 10)) + div class="mt-3 flex gap-6 text-[12px] text-slate-400" { + span class="flex items-center gap-1.5" { + span class="w-2 h-2 rounded-full" style="background:var(--ok)" {} + span class="font-mono tabular-nums" { (deployment.healthy) } + " healthy" + } + span class="flex items-center gap-1.5" { + span class="w-2 h-2 rounded-full" style="background:var(--warn)" {} + span class="font-mono tabular-nums" { (deployment.pending) } + " pending" + } + span class="flex items-center gap-1.5" { + span class="w-2 h-2 rounded-full" style="background:var(--bad)" {} + span class="font-mono tabular-nums" { (deployment.failing) } + " failing" + } + span class="flex items-center gap-1.5 text-slate-600" { + span class="w-2 h-2 rounded-full" style="background:#475569" {} + span class="font-mono tabular-nums" { + (deployment.target.saturating_sub(deployment.healthy + deployment.pending + deployment.failing)) } + " idle" + } + } + } + div class="col-span-12 md:col-span-4" { + (PreEscaped(sparkline_svg(deployment))) + div class="text-[10px] text-slate-600 font-mono mt-1 text-right" { "Healthy devices \u{b7} 24h" } + } + } + } + + // Tabs + div class="flex items-center gap-1 border-b" style="border-color:var(--border)" { + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-100" + hx-get={"/deployment/" (deployment.name) "?tab=overview"} + hx-target="#dep-tab-content" + hx-swap="innerHTML" { + "Overview" + span class="absolute left-0 right-0 -bottom-px h-0.5" style="background:var(--accent)" {} + } + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-500 hover:text-slate-300" + hx-get={"/deployment/" (deployment.name) "?tab=devices"} + hx-target="#dep-tab-content" + hx-swap="innerHTML" { + "Devices (" (devices.len()) ")" + } + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-500 hover:text-slate-300" + hx-get={"/deployment/" (deployment.name) "?tab=tasks"} + hx-target="#dep-tab-content" + hx-swap="innerHTML" { + "Task graph" + } + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-500 hover:text-slate-300" + hx-get={"/deployment/" (deployment.name) "?tab=config"} + hx-target="#dep-tab-content" + hx-swap="innerHTML" { + "Config" + } + } + + div id="dep-tab-content" { + (overview_tab(task_graph, task_view, devices)) + } + } + } +} + +pub fn tab_content( + deployment: &DeploymentDetail, + devices: &[DeviceDetail], + task_graph: &TaskGraph, + task_view: &str, + tab: &str, +) -> Markup { + match tab { + "devices" => devices_tab(devices), + "tasks" => task_graph_view(task_graph, task_view), + "config" => config_tab(deployment), + _ => overview_tab(task_graph, task_view, devices), + } +} + +fn overview_tab(task_graph: &TaskGraph, task_view: &str, devices: &[DeviceDetail]) -> Markup { + html! { + div class="grid grid-cols-12 gap-4" { + div class="col-span-12 lg:col-span-7" { + (task_graph_view(task_graph, task_view)) + } + div class="col-span-12 lg:col-span-5" { + (per_device_grid(devices)) + } + } + } +} + +fn devices_tab(devices: &[DeviceDetail]) -> Markup { + html! { + div class="card card-flush mt-4" { + table class="tbl" { + thead { + tr { + th { "Device" } + th { "Status" } + th { "Region" } + th { "IP" } + th { "Firmware" } + th { "Last seen" } + th class="text-right" { "Action" } + } + } + tbody { + @for d in devices { + tr { + td { + a href={"/device/" (d.id)} class="font-mono text-slate-100 hover:text-(--accent-fg) whitespace-nowrap" { (&d.id) } + } + td { (badges::device_status(d.status)) } + td { span class="text-[12px] text-slate-400 font-mono whitespace-nowrap" { (&d.region) } } + td { span class="font-mono text-[12px] text-slate-500 whitespace-nowrap" { @if let Some(ip) = &d.ip { (ip) } @else { "\u{2014}" } } } + td { span class="font-mono text-[11px] text-slate-500 whitespace-nowrap" { (&d.fw) } } + td { span class="text-[12px] text-slate-500 tabular-nums" { (time_ago(d.minutes_ago)) } } + td class="text-right" { + button class="text-slate-400 hover:text-slate-100 px-1.5 py-1" { (PreEscaped(ICON_MORE)) } } } } @@ -35,16 +289,305 @@ pub fn page(deployments: &[DeploymentSummary]) -> Markup { } } -fn status_badge(s: DeploymentStatus) -> Markup { - let (label, classes) = match s { - DeploymentStatus::Active => ("active", "bg-emerald-900 text-emerald-300"), - DeploymentStatus::Rolling => ("rolling", "bg-sky-900 text-sky-300"), - DeploymentStatus::Failing => ("failing", "bg-rose-900 text-rose-300"), - DeploymentStatus::Paused => ("paused", "bg-slate-800 text-slate-400"), - }; +fn config_tab(deployment: &DeploymentDetail) -> Markup { html! { - span class={"inline-block rounded px-2 py-0.5 text-xs font-medium " (classes)} { - (label) + div class="card p-5 mt-4" { + div class="section-title mb-2" { "Deployment manifest" } + pre class="font-mono text-[12px] text-slate-300 leading-6 p-4 rounded" style="background:#050608; border:1px solid var(--border)" { + "apiVersion: harmony/v1\n" + "kind: Deployment\n" + "metadata:\n" + " name: " (deployment.name) "\n" + " version: " (deployment.version) "\n" + "spec:\n" + " target:\n" + " selector: tags has \"prod\"\n" + " count: " (deployment.target) "\n" + " strategy:\n" + " type: rolling\n" + " maxUnavailable: 10%\n" + " tasks:\n" + " - id: fetch_artifact\n" + " run: hf-agent pull oci://registry/" (deployment.name) ":" (deployment.version) "\n" + " - id: verify_signature\n" + " run: cosign verify --key /etc/harmony/pub.key\n" + " after: [fetch_artifact]\n" + " - id: install_deps\n" + " run: hf-agent apt install -y libsensor3 libcrypto3\n" + " after: [verify_signature]\n" + " - id: launch_services\n" + " run: systemctl restart sensord relayd\n" + " after: [install_deps]\n" + " - id: health_probe\n" + " run: hf-agent probe --timeout 30s\n" + " after: [launch_services]\n" + } } } } + +fn per_device_grid(devices: &[DeviceDetail]) -> Markup { + html! { + div class="card" { + div class="flex items-center justify-between px-4 py-3 border-b" style="border-color:var(--border)" { + span class="section-title" { "Per-device rollout" } + span class="text-[10px] text-slate-600 font-mono" { (devices.len()) " devices" } + } + div class="p-4 grid grid-cols-10 gap-1.5" { + @for d in devices { + @let c = device_status_color(d.status); + a + href={"/device/" (&d.id)} + title={(&d.id) " \u{b7} " (d.status.label())} + class="aspect-square rounded-[3px] hover:ring-2 transition-all" + style={"background:" (c) "; opacity:" (if d.status == crate::service::DeviceStatus::Pending { "0.5" } else { "1" }) "; box-shadow:inset 0 0 0 1px rgba(0,0,0,0.2)"} { + } + } + } + div class="border-t px-4 py-2.5 flex items-center gap-3 text-[10px] text-slate-500 font-mono" style="border-color:var(--border)" { + span class="flex items-center gap-1" { span class="w-2 h-2 rounded-sm" style="background:var(--ok)" {} " healthy" } + span class="flex items-center gap-1" { span class="w-2 h-2 rounded-sm" style="background:var(--warn)" {} " pending" } + span class="flex items-center gap-1" { span class="w-2 h-2 rounded-sm" style="background:var(--bad)" {} " failing" } + span class="flex items-center gap-1" { span class="w-2 h-2 rounded-sm" style="background:rgba(251,113,133,0.6)" {} " stale" } + } + } + } +} + +fn device_status_color(status: crate::service::DeviceStatus) -> &'static str { + match status { + crate::service::DeviceStatus::Healthy => "var(--ok)", + crate::service::DeviceStatus::Pending => "var(--warn)", + crate::service::DeviceStatus::Failing => "var(--bad)", + crate::service::DeviceStatus::Stale => "rgba(251,113,133,0.6)", + crate::service::DeviceStatus::Blacklisted => "#475569", + crate::service::DeviceStatus::Unknown => "#475569", + } +} + +// ── Task graph view ──────────────────────────────────────────────────── + +fn task_graph_view(task_graph: &TaskGraph, view: &str) -> Markup { + let done_count = task_graph.nodes.iter().filter(|n| n.status == TaskStatus::Done).count(); + html! { + div class="card overflow-hidden" { + div class="flex items-center justify-between px-4 py-3 border-b" style="border-color:var(--border)" { + div class="flex items-center gap-2" { + span class="section-title" { "Task execution" } + span class="text-[10px] text-slate-600 font-mono" { + (done_count) " / " (task_graph.nodes.len()) " complete" + } + } + div class="flex items-center gap-1 p-0.5 rounded-md" style="background:rgba(148,163,184,0.06)" { + a + href={"?task_view=linear"} + class={"px-2 py-1 rounded text-[11px] flex items-center gap-1.5 " + (if view == "linear" { "text-slate-100" } else { "text-slate-500 hover:text-slate-300" })} + style={(if view == "linear" { "background:rgba(148,163,184,0.08)" } else { "background:transparent" })} { + (PreEscaped(ICON_LIST)) " Linear" + } + a + href={"?task_view=dag"} + class={"px-2 py-1 rounded text-[11px] flex items-center gap-1.5 " + (if view == "dag" { "text-slate-100" } else { "text-slate-500 hover:text-slate-300" })} + style={(if view == "dag" { "background:rgba(148,163,184,0.08)" } else { "background:transparent" })} { + (PreEscaped(ICON_GRAPH)) " DAG" + } + } + } + + @if view == "linear" { + ul class="p-3 space-y-1" { + @for (i, n) in task_graph.nodes.iter().enumerate() { + (task_row(n, i)) + } + } + } @else { + (dag_view(task_graph)) + } + } + } +} + +fn task_row(node: &TaskNode, index: usize) -> Markup { + let status = node.status; + let c = match status { + TaskStatus::Done => "var(--ok)", + TaskStatus::Running => "var(--accent)", + TaskStatus::Failed => "var(--bad)", + TaskStatus::Pending => "#475569", + }; + + html! { + li class="flex items-center gap-3 px-2 py-2 rounded hover:bg-white/2 group" { + button class="text-slate-700 hover:text-slate-400 cursor-grab" title="Drag to reorder" { + (PreEscaped(ICON_DRAG)) + } + span class="font-mono text-[10px] text-slate-600 w-5 tabular-nums" { + (format!("{:02}", index + 1)) + } + span class="relative inline-flex w-6 h-6 items-center justify-center rounded-full" + style={"background:" (c) "22; border:1px solid " (c) "55"} { + @if status == TaskStatus::Done { + span style={"color:" (c)} { (PreEscaped(ICON_CHECK)) } + } @else if status == TaskStatus::Running { + span class="absolute inset-0 rounded-full animate-ping opacity-50" style={"background:" (c)} {} + span class="relative w-2 h-2 rounded-full" style={"background:" (c)} {} + } @else if status == TaskStatus::Failed { + span style={"color:" (c)} { (PreEscaped(ICON_CLOSE)) } + } @else { + span class="w-1.5 h-1.5 rounded-full" style={"background:" (c)} {} + } + } + div class="flex-1 min-w-0" { + div class="text-[13px] text-slate-100" { (&node.label) } + div class="text-[10px] text-slate-600 font-mono" { (&node.id) } + } + span class="text-[11px] font-mono text-slate-500 tabular-nums" { (&node.duration) } + span class="text-[10px] uppercase tracking-wider font-medium tabular-nums" style={"color:" (c)} { + (status_label(status)) + } + } + } +} + +fn dag_view(task_graph: &TaskGraph) -> Markup { + let col_w = 132; + let row_h = 92; + let pad = 24; + let cols = task_graph.positions.values().map(|p| p.0).max().unwrap_or(0) + 1; + let rows = task_graph.positions.values().map(|p| p.1).max().unwrap_or(0) + 1; + let total_w = cols * col_w + pad * 2; + let total_h = rows * row_h + pad * 2; + + let pos = |id: &str| -> (usize, usize) { + if let Some(&(c, r)) = task_graph.positions.get(id) { + (pad + c * col_w + col_w / 2 - 50, pad + r * row_h) + } else { + (pad, pad) + } + }; + + let edges_svg: String = task_graph + .edges + .iter() + .map(|(from, to)| { + let (fx, fy) = pos(from); + let (tx, ty) = pos(to); + let x1 = fx + 100; + let y1 = fy + 28; + let x2 = tx; + let y2 = ty + 28; + let cx = (x1 + x2) / 2; + let node = task_graph.nodes.iter().find(|n| &n.id == to); + let stroke = match node.map(|n| n.status) { + Some(TaskStatus::Done) => "rgba(52,211,153,0.45)", + Some(TaskStatus::Running) => "rgba(249,115,22,0.55)", + _ => "rgba(148,163,184,0.25)", + }; + format!( + r#""# + ) + }) + .collect::>() + .join("\n"); + + html! { + div class="p-3 overflow-auto" style="min-height:300px" { + style { (PreEscaped(r#"@keyframes draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }"#)) } + div class="relative" style={"width:" (total_w) "px; height:" (total_h) "px"} { + svg class="absolute inset-0" width=(total_w) height=(total_h) style="pointer-events:none" { + defs { + marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse" { + path d="M 0 0 L 10 5 L 0 10 z" fill="rgba(148,163,184,0.45)" {} + } + } + (PreEscaped(&edges_svg)) + } + @for n in &task_graph.nodes { + @let (x, y) = pos(&n.id); + @let c = match n.status { + TaskStatus::Done => "var(--ok)", + TaskStatus::Running => "var(--accent)", + TaskStatus::Failed => "var(--bad)", + TaskStatus::Pending => "#475569", + }; + div class="absolute rounded-md px-2.5 py-2 select-none" + style={"left:" (x) "px; top:" (y) "px; width:100px; height:56px; background:var(--bg-elev-2); border:1px solid " (c) "55; box-shadow:0 0 0 1px rgba(255,255,255,0.02) inset"} { + div class="flex items-center gap-1.5" { + span class="relative inline-flex w-2 h-2 items-center justify-center" { + @if n.status == TaskStatus::Running { + span class="absolute inset-0 rounded-full animate-ping" style={"background:" (c) "; opacity:0.5"} {} + } + span class="w-2 h-2 rounded-full" style={"background:" (c)} {} + } + span class="text-[10px] font-mono uppercase tracking-wider" style={"color:" (c)} { + (status_label(n.status)) + } + } + div class="text-[11px] text-slate-100 leading-tight mt-1 line-clamp-2" { (&n.label) } + div class="absolute right-2 bottom-1 text-[9px] font-mono text-slate-600 tabular-nums" { + (&n.duration) + } + } + } + } + } + } +} + +// ── Helpers ──────────────────────────────────────────────────────────── + +fn segmented_progress(d: &DeploymentDetail, height: u32) -> Markup { + html! { + div class="w-full rounded-full overflow-hidden progress-bg flex" style={"height:" (height) "px"} { + @if d.healthy > 0 { + div class="h-full" style={"width:" ((d.healthy as f64 / d.target as f64) * 100.0) "%; background:var(--ok)"} {} + } + @if d.pending > 0 { + div class="h-full" style={"width:" ((d.pending as f64 / d.target as f64) * 100.0) "%; background:var(--warn)"} {} + } + @if d.failing > 0 { + div class="h-full" style={"width:" ((d.failing as f64 / d.target as f64) * 100.0) "%; background:var(--bad)"} {} + } + } + } +} + +fn sparkline_svg(deployment: &DeploymentDetail) -> String { + let w = 300.0; + let h = 48.0; + let end = deployment.healthy as f64; + let range = deployment.target as f64 * 0.4; + let values: Vec = (0..24) + .map(|i| { + end - range / 2.0 + + (i as f64 / 3.0).sin() * range / 3.0 + + ((i as f64 * 7.3).sin() * 2.0) + }) + .collect(); + super::dashboard::sparkline_svg(&values, "var(--accent)", w, h, "dep") +} + +fn time_ago(minutes: i64) -> String { + if minutes < 1 { + "just now".into() + } else if minutes < 60 { + format!("{}m ago", minutes) + } else if minutes < 60 * 24 { + format!("{}h ago", minutes / 60) + } else { + format!("{}d ago", minutes / (60 * 24)) + } +} + +fn status_label(s: TaskStatus) -> &'static str { + match s { + TaskStatus::Done => "done", + TaskStatus::Running => "running", + TaskStatus::Pending => "pending", + TaskStatus::Failed => "failed", + } +} + + diff --git a/fleet/harmony-fleet-operator/src/frontend/views/devices.rs b/fleet/harmony-fleet-operator/src/frontend/views/devices.rs index 6d9c6c99..3116c110 100644 --- a/fleet/harmony-fleet-operator/src/frontend/views/devices.rs +++ b/fleet/harmony-fleet-operator/src/frontend/views/devices.rs @@ -1,29 +1,381 @@ -use maud::{Markup, html}; +use maud::{Markup, PreEscaped, html}; -use crate::service::{DeviceStatus, DeviceSummary}; +use crate::frontend::views::badges; +use crate::service::{DeviceDetail, DeviceStatus}; + +// ── Inline icons ──────────────────────────────────────────────────────── +const ICON_SEARCH: &str = r#""#; +const ICON_CHEVRON_DOWN: &str = r#""#; +const ICON_LIST: &str = r#""#; +const ICON_MORE: &str = r#""#; +const ICON_POWER: &str = r#""#; +const ICON_PAUSE: &str = r#""#; +const ICON_BAN: &str = r#""#; +const ICON_EXPAND: &str = r#""#; +const ICON_EXTERNAL: &str = r#""#; +const ICON_REFRESH: &str = r#""#; +const ICON_COPY: &str = r#""#; + +// ── Devices list page ────────────────────────────────────────────────── + +pub fn page(devices: &[DeviceDetail], regions: &[String], deployments: &[String], status_filter: Option, deployment_filter: Option<&str>, region_filter: Option<&str>, search: Option<&str>) -> Markup { + let total = devices.len(); + let all_regions: Vec<&str> = regions.iter().map(|s| s.as_str()).collect(); -pub fn page(devices: &[DeviceSummary]) -> Markup { html! { - section { - div class="flex items-baseline gap-3 mb-4" { - h2 class="text-lg font-medium text-slate-300" { "Devices" } - span class="text-xs text-slate-500" { (devices.len()) " total" } - } - div class="overflow-x-auto rounded-lg border border-slate-800" { - table class="min-w-full divide-y divide-slate-800 text-sm" { - thead class="bg-slate-900 text-xs uppercase tracking-wide text-slate-400" { - tr { - th class="px-3 py-2 text-left font-medium" { "ID" } - th class="px-3 py-2 text-left font-medium" { "Status" } - th class="px-3 py-2 text-left font-medium" { "Deployment" } - th class="px-3 py-2 text-left font-medium" { "IP" } - th class="px-3 py-2 text-left font-medium" { "Last seen" } - th class="px-3 py-2 text-right font-medium" { "Actions" } + div class="p-6 space-y-4" { + div class="flex items-center gap-2 flex-wrap" { + @for (k, label) in [("all", "All"), ("healthy", "Healthy"), ("pending", "Pending"), ("failing", "Failing"), ("stale", "Stale"), ("blacklisted", "Blacklisted")].iter() { + @let active = match &status_filter { + None => *k == "all", + Some(s) => k == &s.label(), + }; + a href={"/devices?status=" (k)} class={(if active { "chip active" } else { "chip" })} { + span { (label) } + } + } + div class="w-px h-5 mx-1" style="background:var(--border-strong)" {} + form class="relative" hx-get="/devices" hx-target="body" hx-push-url="true" { + @if let Some(s) = status_filter { + input type="hidden" name="status" value=(s.label()); + } + select + name="deployment" + class="input pl-3 pr-8 appearance-none font-mono text-[12px]" + style="padding-left:10px" + onchange="this.form.requestSubmit()" { + option value="" selected[deployment_filter.is_none()] { "All deployments" } + @for dep in deployments { + option value=(dep.as_str()) selected[deployment_filter == Some(dep.as_str())] { (dep) } } } - tbody id="device-rows" class="divide-y divide-slate-800 bg-slate-950" { - @for device in devices { - (row(device)) + span class="absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500" { + (PreEscaped(ICON_CHEVRON_DOWN)) + } + } + form class="relative" hx-get="/devices" hx-target="body" hx-push-url="true" { + @if let Some(s) = status_filter { + input type="hidden" name="status" value=(s.label()); + } + @if let Some(d) = deployment_filter { + input type="hidden" name="deployment" value=(d); + } + select + name="region" + class="input pl-3 pr-8 appearance-none font-mono text-[12px]" + style="padding-left:10px" + onchange="this.form.requestSubmit()" { + option value="" selected[region_filter.is_none()] { "All regions" } + @for r in &all_regions { + option value=(r) selected[region_filter == Some(r)] { (r) } + } + } + span class="absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500" { + (PreEscaped(ICON_CHEVRON_DOWN)) + } + } + form class="relative flex-1 max-w-[280px] ml-auto" hx-get="/devices" hx-target="body" hx-push-url="true" { + @if let Some(s) = status_filter { + input type="hidden" name="status" value=(s.label()); + } + span class="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-500" { + (PreEscaped(ICON_SEARCH)) + } + @let search_val = search.unwrap_or(""); + input + class="input w-full" + type="text" + name="search" + placeholder="Filter by id, ip, tag\u{2026}" + value=(search_val) + hx-get="/devices" + hx-trigger="keyup changed delay:300ms" + hx-target="body" + hx-push-url="true" + hx-include="closest form"; + } + } + + div class="card card-flush overflow-hidden" id="device-table-wrapper" { + div class="overflow-x-auto" style="max-height:calc(100vh - 240px)" { + table class="tbl" { + thead class="sticky top-0 z-10" { + tr { + th style="width:36px" {} + th { "Device ID" } + th { "Status" } + th { "Deployment" } + th { "Region" } + th { "IP" } + th { "Firmware" } + th { "Last seen" } + th class="text-right" { "Action" } + } + } + tbody { + @for d in devices { + tr hx-get={"/device/" (d.id)} hx-target="body" hx-push-url="true" class="cursor-pointer" { + td { + input + type="checkbox" + class="accent-(--accent) w-3.5 h-3.5 rounded" + onclick="event.stopPropagation()"; + } + td { + span class="font-mono text-slate-100 hover:text-(--accent-fg) hover:underline underline-offset-2 whitespace-nowrap" { + (&d.id) + } + } + td { (badges::device_status(d.status)) } + td { + @if let Some(dep) = &d.deployment { + span class="font-mono text-[12px] text-slate-300 whitespace-nowrap" { (dep) } + } @else { + span class="text-slate-700" { "\u{2014}" } + } + } + td { + span class="text-[12px] text-slate-400 font-mono whitespace-nowrap" { (&d.region) } + } + td { + span class="font-mono text-[12px] text-slate-500 whitespace-nowrap" { + @if let Some(ip) = &d.ip { (ip) } @else { "\u{2014}" } + } + } + td { + span class="font-mono text-[11px] text-slate-500 whitespace-nowrap" { (&d.fw) } + } + td { + span class="text-[12px] text-slate-500 tabular-nums" { (time_ago(d.minutes_ago)) } + } + td class="text-right" { + div class="inline-flex items-center gap-1" { + button + class="text-slate-400 hover:text-slate-100 px-1.5 py-1 rounded hover:bg-white/4" + title="Quick logs" + hx-get={"/devices/" (d.id) "/logs"} + hx-target="#modal-root" + hx-swap="innerHTML" + onclick="event.stopPropagation()" { + (PreEscaped(ICON_LIST)) + } + button + class="text-slate-400 hover:text-slate-100 px-1.5 py-1 rounded hover:bg-white/4" + title="More" + onclick="event.stopPropagation()" { + (PreEscaped(ICON_MORE)) + } + } + } + } + } + @if devices.is_empty() { + tr { + td colspan="9" class="text-center py-12 text-slate-500 text-[13px]" { + "No devices match these filters" + } + } + } + } + } + } + div class="flex items-center justify-between px-4 py-2.5 border-t text-[12px] text-slate-500" style="border-color:var(--border)" { + span { + "Showing " span class="text-slate-300 tabular-nums" { (devices.len()) } + " of " span class="text-slate-300 tabular-nums" { (total) } " devices" + } + } + } + } + } +} + +// ── Device detail page ───────────────────────────────────────────────── + +pub fn detail(device: &DeviceDetail, deployment_version: Option<&str>) -> Markup { + html! { + div class="p-6 space-y-4" { + // Header + div class="card p-5" { + div class="flex items-start justify-between gap-6" { + div class="min-w-0" { + div class="flex items-center gap-3 flex-wrap" { + h1 class="text-[22px] font-semibold font-mono text-slate-50 truncate whitespace-nowrap" { (&device.id) } + (badges::device_status(device.status)) + @for t in &device.tags { + span class="text-[10px] font-mono text-slate-400 px-1.5 py-0.5 rounded" style="background:rgba(148,163,184,0.06); border:1px solid var(--border)" { + "#" (t) + } + } + } + div class="mt-2 flex flex-wrap items-center gap-x-5 gap-y-1 text-[12px] text-slate-500" { + span { span class="text-slate-600" { "Model" } " " span class="text-slate-300 font-mono" { (&device.model) } } + span { span class="text-slate-600" { "Region" } " " span class="text-slate-300 font-mono" { (&device.region) } } + span { + span class="text-slate-600" { "IP" } " " + span class="text-slate-300 font-mono" { @if let Some(ip) = &device.ip { (ip) } @else { "\u{2014}" } } + } + span { span class="text-slate-600" { "Firmware" } " " span class="text-slate-300 font-mono" { (&device.fw) } } + span { span class="text-slate-600" { "Last seen" } " " span class="text-slate-300 tabular-nums" { (time_ago(device.minutes_ago)) } } + } + } + div class="flex items-center gap-2 shrink-0" { + button class="btn btn-ghost" { (PreEscaped(ICON_REFRESH)) " Reconcile" } + button class="btn btn-ghost" { (PreEscaped(ICON_POWER)) " Restart" } + button class="btn btn-ghost" { (PreEscaped(ICON_PAUSE)) " Suspend" } + @if device.status != DeviceStatus::Blacklisted { + button + class="btn btn-danger" + hx-post={"/devices/" (device.id) "/blacklist"} + hx-confirm={"Blacklist " (device.id) "?"} + hx-target="body" { + (PreEscaped(ICON_BAN)) " Blacklist" + } + } + } + } + } + + // Tab bar + div class="flex items-center gap-1 border-b" style="border-color:var(--border)" { + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-100" + hx-get={"/device/" (device.id) "?tab=overview"} + hx-target="#device-tab-content" + hx-swap="innerHTML" { + "Overview" + span class="absolute left-0 right-0 -bottom-px h-0.5" style="background:var(--accent)" {} + } + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-500 hover:text-slate-300" + hx-get={"/device/" (device.id) "?tab=logs"} + hx-target="#device-tab-content" + hx-swap="innerHTML" { + "Logs" + } + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-500 hover:text-slate-300" + hx-get={"/device/" (device.id) "?tab=history"} + hx-target="#device-tab-content" + hx-swap="innerHTML" { + "Deployment history" + } + button + class="px-3 py-2 text-[13px] font-medium relative text-slate-500 hover:text-slate-300" + hx-get={"/device/" (device.id) "?tab=config"} + hx-target="#device-tab-content" + hx-swap="innerHTML" { + "Config" + } + div class="flex-1" {} + button + class="btn btn-ghost mb-1" + hx-get={"/devices/" (device.id) "/logs"} + hx-target="#modal-root" + hx-swap="innerHTML" { + (PreEscaped(ICON_EXPAND)) " Pop-out logs" + } + } + + div id="device-tab-content" { + (overview_tab(device, deployment_version)) + } + } + } +} + +pub fn tab_content(device: &DeviceDetail, tab: &str, deployment_version: Option<&str>) -> Markup { + match tab { + "logs" => logs_tab(device), + "history" => history_tab(device, deployment_version), + "config" => config_tab(device, deployment_version), + _ => overview_tab(device, deployment_version), + } +} + +fn overview_tab(device: &DeviceDetail, deployment_version: Option<&str>) -> Markup { + html! { + div class="grid grid-cols-12 gap-4" { + div class="col-span-12 lg:col-span-8 space-y-4" { + // Metrics + div class="card p-5" { + div class="section-title mb-3" { "Metrics (last hour)" } + div class="grid grid-cols-3 gap-5" { + (metric_card("CPU", &format!("{}%", device.cpu), "var(--accent)", device.cpu)) + (metric_card("Memory", &format!("{}%", device.mem), "var(--info)", device.mem)) + (metric_card("Uptime", &format!("{}d {}h", device.uptime_h / 24, device.uptime_h % 24), "var(--ok)", 78)) + } + } + + // Recent logs preview + div class="card" { + div class="flex items-center justify-between px-4 py-3 border-b" style="border-color:var(--border)" { + span class="section-title" { "Recent logs" } + button + class="text-[11px] text-slate-400 hover:text-slate-100 flex items-center gap-1" + hx-get={"/devices/" (device.id) "/logs"} + hx-target="#modal-root" + hx-swap="innerHTML" { + "Open full " (PreEscaped(ICON_EXTERNAL)) + } + } + div class="font-mono text-[11.5px] leading-6 px-4 py-2 max-h-[200px] overflow-auto" style="background:#050608" { + @for i in 0..7 { + (log_line("info", &format!("07:{}:0{}", 28 + i, (i * 3) % 10), &device.id, &format!("mock log entry #{}", i + 1))) + } + } + } + } + + // Sidebar + div class="col-span-12 lg:col-span-4 space-y-4" { + // Current deployment + div class="card p-5" { + div class="section-title mb-3" { "Current deployment" } + @if let Some(dep_name) = &device.deployment { + a href={"/deployment/" (dep_name)} class="w-full text-left block" { + div class="font-mono text-slate-100 text-[14px] whitespace-nowrap" { (dep_name) } + div class="text-[11px] text-slate-500 mt-0.5" { + @if let Some(v) = deployment_version { (v) } + } + div class="mt-3 text-[11px] text-(--accent-fg) flex items-center gap-1" { + "Open deployment " (PreEscaped(ICON_EXTERNAL)) + } + } + } @else { + div class="text-[12px] text-slate-500" { "No deployment assigned" } + } + } + + // Identity + div class="card p-5" { + div class="section-title mb-3" { "Identity" } + (definition("Device ID", &device.id, true, true)) + (definition("MAC", "b8:27:eb:42:0a:1f", true, false)) + (definition("Agent", &format!("harmony-agent {}", device.fw), true, false)) + (definition("Enrolled", "2025-11-14 09:22 UTC", false, false)) + (definition("Region", &device.region, true, false)) + } + + // Activity + div class="card p-5" { + div class="section-title mb-3" { "Activity" } + ul class="space-y-2.5 text-[12px]" { + li class="flex gap-3" { + span class="font-mono text-slate-600 tabular-nums shrink-0" { "07:24" } + span class="text-slate-400" { span class="text-slate-200" { "r.tarzalt" } " triggered reconcile" } + } + li class="flex gap-3" { + span class="font-mono text-slate-600 tabular-nums shrink-0" { "06:51" } + span class="text-slate-400" { + "deployment " + span class="font-mono text-slate-300" { @if let Some(dep) = &device.deployment { (dep) } @else { "edge-gateway" } } + " applied" + } + } + li class="flex gap-3" { + span class="font-mono text-slate-600 tabular-nums shrink-0" { "04:12" } + span class="text-slate-400" { "agent restarted (reason: signal=15)" } } } } @@ -32,52 +384,284 @@ pub fn page(devices: &[DeviceSummary]) -> Markup { } } -/// Single row — also the response shape for `POST /devices/:id/blacklist`, -/// so HTMX can swap a row in place after a mutation. -pub fn row(d: &DeviceSummary) -> Markup { +fn logs_tab(device: &DeviceDetail) -> Markup { html! { - tr id={"device-" (d.id)} { - td class="px-3 py-2 font-mono text-slate-200" { (d.id) } - td class="px-3 py-2" { (status_badge(d.status)) } - td class="px-3 py-2 text-slate-300" { - @if let Some(deployment) = &d.deployment { (deployment) } - @else { span class="text-slate-600" { "—" } } + div class="card overflow-hidden mt-4" { + div class="flex items-center gap-2 px-4 py-2.5 border-b" style="border-color:var(--border)" { + span class="relative flex w-1.5 h-1.5" { + span class="absolute inline-flex h-full w-full animate-ping rounded-full opacity-60" style="background:var(--accent)" {} + span class="relative inline-flex w-1.5 h-1.5 rounded-full" style="background:var(--accent)" {} + } + span class="text-[11px] font-mono text-slate-400" { "streaming" } + span class="text-[11px] text-slate-600 font-mono" { "\u{b7} live" } + div class="flex-1" {} + div class="flex items-center gap-1" { + span class="chip active" { "all" } + span class="chip" { "info" } + span class="chip" { "warn" } + span class="chip" { "error" } + span class="chip" { "debug" } + } + button class="btn btn-ghost py-1" { (PreEscaped(ICON_PAUSE)) " Pause" } } - td class="px-3 py-2 font-mono text-slate-400" { - @if let Some(ip) = &d.ip { (ip) } - @else { span class="text-slate-600" { "—" } } + div + class="font-mono text-[11.5px] leading-6 px-4 py-2 overflow-auto" + style="background:#050608; height:520px" + hx-ext="sse" + sse-connect={"/devices/" (device.id) "/logs/stream"} + sse-swap="log" + hx-swap="beforeend" { + div class="px-0 py-px italic text-slate-700" { "\u{2014} connecting \u{2014}" } } - td class="px-3 py-2 text-slate-400" { - (d.last_seen.format("%Y-%m-%d %H:%M:%S").to_string()) " UTC" + } + } +} + +fn history_tab(device: &DeviceDetail, _deployment_version: Option<&str>) -> Markup { + let dep_name = device.deployment.as_deref().unwrap_or("edge-gateway"); + html! { + div class="card mt-4" { + table class="tbl" { + thead { + tr { + th { "Deployment" } + th { "Version" } + th { "Outcome" } + th { "Applied" } + th { "Duration" } + } + } + tbody { + tr { + td class="font-mono text-slate-200 whitespace-nowrap" { (dep_name) } + td class="font-mono text-[12px] whitespace-nowrap" { "v2.14.1" } + td { (badges::device_status(DeviceStatus::Healthy)) } + td class="text-slate-400 text-[12px]" { "2026-05-19 04:12" } + td class="font-mono text-[12px] text-slate-500" { "42s" } + } + tr { + td class="font-mono text-slate-200 whitespace-nowrap" { (dep_name) } + td class="font-mono text-[12px] whitespace-nowrap" { "v2.13.4" } + td { (badges::device_status(DeviceStatus::Healthy)) } + td class="text-slate-400 text-[12px]" { "2026-05-12 11:00" } + td class="font-mono text-[12px] text-slate-500" { "38s" } + } + tr { + td class="font-mono text-slate-200 whitespace-nowrap" { "telemetry-collector" } + td class="font-mono text-[12px] whitespace-nowrap" { "v0.4.11" } + td { (badges::device_status(DeviceStatus::Failing)) } + td class="text-slate-400 text-[12px]" { "2026-05-04 14:30" } + td class="font-mono text-[12px] text-slate-500" { "1m 08s" } + } + tr { + td class="font-mono text-slate-200 whitespace-nowrap" { "telemetry-collector" } + td class="font-mono text-[12px] whitespace-nowrap" { "v0.4.10" } + td { (badges::device_status(DeviceStatus::Healthy)) } + td class="text-slate-400 text-[12px]" { "2026-04-30 09:15" } + td class="font-mono text-[12px] text-slate-500" { "29s" } + } + } } - td class="px-3 py-2 text-right" { - @if d.status != DeviceStatus::Blacklisted { + } + } +} + +fn config_tab(device: &DeviceDetail, deployment_version: Option<&str>) -> Markup { + let tags_str = device.tags.join(", "); + let dep_ver = deployment_version.unwrap_or("\u{2014}"); + html! { + div class="card p-5 mt-4" { + div class="section-title mb-2" { "Effective config" } + pre class="font-mono text-[12px] text-slate-300 leading-6 p-4 rounded" style="background:#050608; border:1px solid var(--border)" { + "# generated by harmony-controller @ 2026-05-19 04:12\n" + "device:\n" + " id: " (device.id) "\n" + " region: " (device.region) "\n" + " tags: [" (tags_str) "]\n" + "agent:\n" + " version: " (device.fw) "\n" + " heartbeat_interval: 30s\n" + "deployment:\n" + " name: " @if let Some(dep) = &device.deployment { (dep) } @else { "none" } "\n" + " version: " (dep_ver) "\n" + " tasks:\n" + " - fetch_artifact\n" + " - verify_signature\n" + " - install_deps\n" + " - launch_services\n" + } + } + } +} + +// ── Logs modal (SSE streaming) ───────────────────────────────────────── + +pub fn logs_modal(device_id: &str) -> Markup { + html! { + dialog + id="device-logs-modal" + class="m-auto grid grid-rows-[auto_1fr] h-[88vh] w-[min(96vw,82rem)] overflow-hidden rounded-none border-t-2 border-x-0 border-b-0 p-0 text-slate-100 shadow-[0_32px_64px_rgba(0,0,0,0.9),0_0_0_1px_rgba(148,163,184,0.06)] backdrop:bg-black/85" + style="border-color:var(--accent); background:#080a0c" + onclick="if (event.target === this) this.close()" + onclose="document.getElementById('modal-root').innerHTML = ''" + { + div class="flex items-center justify-between border-b px-5 py-3" style="background:#0c1018; border-color:var(--border)" { + div class="flex items-center gap-3" { + span class="relative flex h-1.5 w-1.5 shrink-0" { + span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-orange-400 opacity-60" {} + span class="relative inline-flex h-1.5 w-1.5 rounded-full" style="background:var(--accent)" {} + } + code class="text-sm font-medium text-slate-100" { (device_id) } + span class="text-[10px] font-semibold uppercase tracking-[0.15em] text-orange-500/60" { "\u{b7} logs" } + } + form method="dialog" { button - class="rounded bg-rose-700 hover:bg-rose-600 px-2 py-1 text-xs font-medium" - hx-post={"/devices/" (d.id) "/blacklist"} - hx-target={"#device-" (d.id)} - hx-swap="outerHTML" - hx-confirm={"Blacklist " (d.id) "?"} - { "Blacklist" } - } @else { - span class="text-xs text-slate-500" { "blacklisted" } + type="submit" + class="flex items-center gap-1.5 text-slate-500 transition-colors hover:text-slate-200" + aria-label="Close" + { + kbd class="rounded border bg-slate-800/60 px-1.5 py-0.5 font-mono text-[10px] text-slate-400" style="border-color:var(--border-strong)" { "esc" } + span class="text-xs" { "close" } + } + } + } + + div + class="overflow-y-auto py-3 font-mono text-[11.5px] leading-6 px-5" + style="background:#050608" + hx-ext="sse" + sse-connect={"/devices/" (device_id) "/logs/stream"} + sse-swap="log" + hx-swap="beforeend" { + div class="py-px italic text-slate-700" { "\u{2014} connecting \u{2014}" } + } + } + script { + (PreEscaped(r#" +(function(){ + var modal = document.getElementById('device-logs-modal'); + modal?.showModal(); + var body = modal?.querySelector('[hx-swap]'); + if (!body) return; + new MutationObserver(function(){ body.scrollTop = body.scrollHeight; }) + .observe(body, { childList: true }); +})(); +"#)) + } + } +} + +// ── Row (for blacklist response) ─────────────────────────────────────── + +pub fn row(d: &DeviceDetail) -> Markup { + html! { + tr id={"device-" (d.id)} hx-get={"/device/" (d.id)} hx-target="body" hx-push-url="true" class="cursor-pointer" { + td { + input type="checkbox" class="accent-(--accent) w-3.5 h-3.5 rounded" onclick="event.stopPropagation()" {} + } + td { + span class="font-mono text-slate-100 hover:text-(--accent-fg) hover:underline underline-offset-2 whitespace-nowrap" { + + (&d.id) + } + } + td { (badges::device_status(d.status)) } + td { + @if let Some(dep) = &d.deployment { span class="font-mono text-[12px] text-slate-300 whitespace-nowrap" { (dep) } } + @else { span class="text-slate-700" { "\u{2014}" } } + } + td { span class="text-[12px] text-slate-400 font-mono whitespace-nowrap" { (&d.region) } } + td { span class="font-mono text-[12px] text-slate-500 whitespace-nowrap" { @if let Some(ip) = &d.ip { (ip) } @else { "\u{2014}" } } } + td { span class="font-mono text-[11px] text-slate-500 whitespace-nowrap" { (&d.fw) } } + td { span class="text-[12px] text-slate-500 tabular-nums" { (time_ago(d.minutes_ago)) } } + td class="text-right" { + div class="inline-flex items-center gap-1" { + button + class="text-slate-400 hover:text-slate-100 px-1.5 py-1 rounded hover:bg-white/4" + hx-get={"/devices/" (d.id) "/logs"} + hx-target="#modal-root" + hx-swap="innerHTML" + onclick="event.stopPropagation()" { (PreEscaped(ICON_LIST)) } + button class="text-slate-400 hover:text-slate-100 px-1.5 py-1 rounded hover:bg-white/4" onclick="event.stopPropagation()" { (PreEscaped(ICON_MORE)) } } } } } } -fn status_badge(s: DeviceStatus) -> Markup { - let (label, classes) = match s { - DeviceStatus::Healthy => ("healthy", "bg-emerald-900 text-emerald-300"), - DeviceStatus::Pending => ("pending", "bg-amber-900 text-amber-300"), - DeviceStatus::Stale => ("stale", "bg-rose-900 text-rose-300"), - DeviceStatus::Blacklisted => ("blacklisted", "bg-slate-800 text-slate-400"), - DeviceStatus::Unknown => ("unknown", "bg-slate-800 text-slate-500"), +// ── Helpers ──────────────────────────────────────────────────────────── + +fn log_line(severity: &str, ts: &str, device_id: &str, message: &str) -> Markup { + let sev_color = match severity { + "info" => "text-cyan-500", + "warn" => "text-amber-400", + "error" => "text-rose-400", + "debug" => "text-slate-600", + _ => "text-slate-500", }; + let sev_label = format!("{:5}", severity.to_uppercase()); html! { - span class={"inline-block rounded px-2 py-0.5 text-xs font-medium " (classes)} { - (label) + div class={"log-line grid grid-cols-[5rem_3rem_1fr] gap-3 px-0 py-px hover:bg-white/2.5 " (sev_color)} { + span class="tabular-nums text-slate-600" { (ts) } + span class={"font-semibold " (sev_color)} { (sev_label) } + span class="text-slate-300" { + span class="text-cyan-500" { (device_id) } + " " (message) + } + } + } +} + +fn time_ago(minutes: i64) -> String { + if minutes < 1 { + "just now".into() + } else if minutes < 60 { + format!("{}m ago", minutes) + } else if minutes < 60 * 24 { + format!("{}h ago", minutes / 60) + } else { + format!("{}d ago", minutes / (60 * 24)) + } +} + +fn metric_card(label: &str, value: &str, color: &str, seed: u8) -> Markup { + let spark = mini_sparkline(seed, color); + html! { + div { + div class="flex items-baseline gap-2" { + span class="text-[11px] text-slate-500 uppercase tracking-wider" { (label) } + } + div class="text-[22px] font-semibold text-slate-100 mt-1 tabular-nums leading-none" { (value) } + div class="mt-2" { + (PreEscaped(spark)) + } + } + } +} + +fn mini_sparkline(seed: u8, color: &str) -> String { + let w = 210.0; + let h = 36.0; + let values: Vec = (0..24) + .map(|i| { + seed as f64 - 15.0 + + (i as f64 / 3.0).sin() * 10.0 + + ((i as f64 * 7.3 + seed as f64 * 1.7).sin() * 4.0) + }) + .collect(); + crate::frontend::views::dashboard::sparkline_svg(&values, color, w, h, &format!("ms{}", seed)) +} + +fn definition(label: &str, value: &str, mono: bool, copyable: bool) -> Markup { + html! { + div class="flex items-center justify-between py-1.5 text-[12px] border-b last:border-b-0" style="border-color:var(--border)" { + span class="text-slate-500" { (label) } + span class={(if mono { "font-mono whitespace-nowrap" } else { "" }) " text-slate-200 flex items-center gap-1.5"} { + (value) + @if copyable { + button class="text-slate-600 hover:text-slate-300" title="Copy" { (PreEscaped(ICON_COPY)) } + } + } } } } diff --git a/fleet/harmony-fleet-operator/src/frontend/views/mod.rs b/fleet/harmony-fleet-operator/src/frontend/views/mod.rs index ec2901b5..7cabd8a0 100644 --- a/fleet/harmony-fleet-operator/src/frontend/views/mod.rs +++ b/fleet/harmony-fleet-operator/src/frontend/views/mod.rs @@ -1,3 +1,6 @@ +pub mod alerts; +pub mod badges; pub mod dashboard; pub mod deployments; pub mod devices; +pub mod settings; diff --git a/fleet/harmony-fleet-operator/src/frontend/views/settings.rs b/fleet/harmony-fleet-operator/src/frontend/views/settings.rs new file mode 100644 index 00000000..66a702c8 --- /dev/null +++ b/fleet/harmony-fleet-operator/src/frontend/views/settings.rs @@ -0,0 +1,70 @@ +use maud::{Markup, PreEscaped, html}; + +pub fn page() -> Markup { + html! { + div class="p-6 max-w-3xl space-y-4" { + div { + h2 class="text-[15px] font-semibold text-slate-200" { "Notification channels" } + p class="text-[12px] text-slate-500 mt-1" { "Where alerts get delivered when something needs your attention." } + } + (channel_row("Email", "email", "alerts@example.com", true)) + (channel_row("Slack", "slack", "#fleet-alerts", true)) + (channel_row("Discord", "discord", "https://discord.com/api/webhooks/\u{2026}", false)) + (channel_row("SMS", "sms", "+1 555 010 0001", true)) + } + } +} + +fn channel_row(name: &str, key: &str, placeholder: &str, enabled: bool) -> Markup { + let enabled_val = if enabled { "var(--ok)" } else { "rgba(148,163,184,0.2)" }; + let translate = if enabled { "18px" } else { "2px" }; + let display_val = if enabled { placeholder } else { "disabled" }; + + html! { + div class="card p-5" { + div class="flex items-center justify-between" { + div class="flex items-center gap-3" { + span class="inline-flex items-center justify-center w-9 h-9 rounded-md" style="background:var(--bg-elev-2); color:var(--accent-fg)" { + (PreEscaped(channel_icon(key))) + } + div { + div class="text-[14px] text-slate-100 font-medium" { (name) } + div class="text-[11px] text-slate-500" { (display_val) } + } + } + button + class="relative w-9 h-5 rounded-full transition-colors" + style={"background:" (enabled_val)} + hx-post={"/settings/toggle/" (key)} + hx-target="closest .card" + hx-swap="outerHTML" { + span class="absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform" style={"transform:translateX(" (translate) ")"} {} + } + } + div class={(if enabled { "mt-3 grid grid-cols-1 md:grid-cols-2 gap-3" } else { "mt-3 grid grid-cols-1 md:grid-cols-2 gap-3 max-h-0 opacity-0 overflow-hidden" })} { + div { + label class="text-[11px] text-slate-500 uppercase tracking-wider" { "Destination" } + input class="input mt-1 w-full" style="padding-left:10px" type="text" placeholder=(placeholder) value=(placeholder) {} + } + div { + label class="text-[11px] text-slate-500 uppercase tracking-wider" { "Notify on" } + div class="mt-1 flex gap-1.5" { + span class="chip active" { "critical" } + span class="chip active" { "warning" } + span class="chip" { "info" } + } + } + } + } + } +} + +fn channel_icon(key: &str) -> String { + match key { + "email" => r#""#.to_string(), + "slack" => r#""#.to_string(), + "discord" => r#""#.to_string(), + "sms" => r#""#.to_string(), + _ => r#""#.to_string(), + } +} diff --git a/fleet/harmony-fleet-operator/src/main.rs b/fleet/harmony-fleet-operator/src/main.rs index 46300ee9..fed7bf34 100644 --- a/fleet/harmony-fleet-operator/src/main.rs +++ b/fleet/harmony-fleet-operator/src/main.rs @@ -106,6 +106,8 @@ enum Command { #[tokio::main] async fn main() -> Result<()> { + dotenvy::dotenv().ok(); + tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .init(); @@ -157,6 +159,7 @@ async fn serve_web( live_reload: bool, ) -> Result<()> { use std::sync::Arc; + use std::time::Duration; use frontend::server::{AppState, Config}; use service::{FleetService, mock::MockFleetService}; @@ -170,11 +173,24 @@ async fn serve_web( ); }; + let cookie_key = harmony_zitadel_auth::cookie_key_from_env(); + let config = harmony_zitadel_auth::config_from_env(); + let http_client = reqwest::Client::new(); + + let jwks = harmony_zitadel_auth::JwksCache::new(&config.zitadel_base, http_client.clone()) + .await + .context("initializing JWKS cache")?; + jwks.spawn_background_refresh(Duration::from_secs(900)); + frontend::server::run( Config::new(AppState { fleet, + cookie_key, css_override: css_from, live_reload, + config, + http_client, + jwks, }) .with_addr(addr), ) diff --git a/fleet/harmony-fleet-operator/src/service/mock.rs b/fleet/harmony-fleet-operator/src/service/mock.rs index 27da4675..1e220584 100644 --- a/fleet/harmony-fleet-operator/src/service/mock.rs +++ b/fleet/harmony-fleet-operator/src/service/mock.rs @@ -1,23 +1,17 @@ -//! In-memory `FleetService` with seeded fake data. -//! -//! Used by `serve-web --mock` for local development without a NATS -//! server or a Kubernetes cluster, and by tests that exercise the -//! presentation layer. - -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Mutex; use async_trait::async_trait; -use chrono::{Duration, Utc}; use super::{ - DashboardSummary, DeploymentStatus, DeploymentSummary, DeviceStatus, DeviceSummary, - FleetService, + Activity, Alert, AlertSeverity, DashboardDetail, DeploymentDetail, DeploymentStatus, + DeviceDetail, DeviceStatus, FleetService, TaskGraph, TaskNode, TaskStatus, }; pub struct MockFleetService { - devices: Mutex>, - deployments: Mutex>, + devices: Mutex>, + deployments: Mutex>, + alerts: Mutex>, } impl Default for MockFleetService { @@ -28,169 +22,639 @@ impl Default for MockFleetService { impl MockFleetService { pub fn with_seeded_data() -> Self { - let now = Utc::now(); - let devices = [ - ( - "pi-001", - DeviceStatus::Healthy, - 30, - Some("kiosk-v3"), - Some("10.0.1.21"), - ), - ( - "pi-002", - DeviceStatus::Healthy, - 45, - Some("kiosk-v3"), - Some("10.0.1.22"), - ), - ( - "pi-003", - DeviceStatus::Healthy, - 12, - Some("kiosk-v3"), - Some("10.0.1.23"), - ), - ( - "pi-004", - DeviceStatus::Pending, - 5, - Some("kiosk-v3"), - Some("10.0.1.24"), - ), - ( - "pi-005", - DeviceStatus::Stale, - 1820, - Some("kiosk-v2"), - Some("10.0.1.25"), - ), - ("pi-006", DeviceStatus::Stale, 2400, Some("kiosk-v2"), None), - ( - "pi-007", - DeviceStatus::Blacklisted, - 600, - None, - Some("10.0.1.27"), - ), - ("pi-008", DeviceStatus::Unknown, 9999, None, None), - ( - "pi-009", - DeviceStatus::Healthy, - 88, - Some("sensor-edge"), - Some("10.0.2.10"), - ), - ( - "pi-010", - DeviceStatus::Pending, - 3, - Some("sensor-edge"), - Some("10.0.2.11"), - ), - ]; - let devices: HashMap = devices - .into_iter() - .map(|(id, status, seconds_ago, deployment, ip)| { - ( - id.to_string(), - DeviceSummary { - id: id.to_string(), - status, - last_seen: now - Duration::seconds(seconds_ago), - deployment: deployment.map(str::to_string), - ip: ip.map(str::to_string), - }, - ) - }) - .collect(); - - let deployments = vec![ - DeploymentSummary { - name: "kiosk-v3".into(), - status: DeploymentStatus::Rolling, - target_devices: 4, - healthy_devices: 3, - }, - DeploymentSummary { - name: "kiosk-v2".into(), - status: DeploymentStatus::Paused, - target_devices: 2, - healthy_devices: 0, - }, - DeploymentSummary { - name: "sensor-edge".into(), - status: DeploymentStatus::Active, - target_devices: 2, - healthy_devices: 1, - }, - DeploymentSummary { - name: "ota-canary".into(), - status: DeploymentStatus::Failing, - target_devices: 1, - healthy_devices: 0, - }, - ]; + let devices = seed_devices(); + let deployments = seed_deployments(); + let alerts = seed_alerts(); Self { devices: Mutex::new(devices), deployments: Mutex::new(deployments), + alerts: Mutex::new(alerts), } } } +// ── Seeded PRNG ──────────────────────────────────────────────────────── + +struct Rng(u32); +impl Iterator for Rng { + type Item = f64; + fn next(&mut self) -> Option { + self.0 = (self.0.wrapping_mul(1103515245).wrapping_add(12345)) & 0x7fffffff; + Some(self.0 as f64 / 0x7fffffff as f64) + } +} + +fn pick<'a, T>(rng: &mut Rng, arr: &'a [T]) -> &'a T { + let i = (rng.next().unwrap() * arr.len() as f64) as usize; + &arr[i.min(arr.len() - 1)] +} + +// ── Device seed ──────────────────────────────────────────────────────── + +fn seed_devices() -> Vec { + let mut rng = Rng(1337); + let hosts = ["edge", "sensor", "gw", "cam", "relay", "meter", "hub"]; + let regions = [ + "eu-paris-1", + "eu-paris-2", + "us-east-1", + "us-west-2", + "apac-tokyo-1", + ]; + let models = [ + "HF-Edge-2", + "HF-Edge-3", + "HF-Sensor-S1", + "HF-Gateway-G2", + "HF-Cam-V1", + ]; + let tags_pool = [ + "prod", "staging", "lab", "eu", "us", "apac", "gpu", "lowpower", "thermal", "pilot", + ]; + + let status_weights: [(DeviceStatus, f64); 5] = [ + (DeviceStatus::Healthy, 0.72), + (DeviceStatus::Pending, 0.10), + (DeviceStatus::Stale, 0.10), + (DeviceStatus::Blacklisted, 0.04), + (DeviceStatus::Unknown, 0.04), + ]; + + let device_deployment: [Option<&str>; 100] = { + let mut arr = [None; 100]; + let dist: [(&str, usize); 7] = [ + ("edge-gateway", 32), + ("sensor-firmware", 41), + ("ingest-pipeline", 8), + ("control-plane", 6), + ("telemetry-collector", 12), + ("gateway-proxy", 4), + ("media-relay", 9), + ]; + let mut idx = 0; + for (name, count) in dist { + for _ in 0..count { + if idx < 100 { + arr[idx] = Some(name); + idx += 1; + } + } + } + arr + }; + + let now = chrono::Utc::now(); + + let mut devices = Vec::with_capacity(100); + for i in 0..100 { + let host = pick(&mut rng, &hosts); + let id = format!("hf-{}-{:03}", host, i + 1); + let status = if i < 4 { + DeviceStatus::Healthy + } else if i == 4 { + DeviceStatus::Failing + } else if i == 5 { + DeviceStatus::Pending + } else { + let r = rng.next().unwrap(); + let mut acc = 0.0; + let mut s = DeviceStatus::Healthy; + for &(st, w) in &status_weights { + acc += w; + if r < acc { + s = st; + break; + } + } + s + }; + + let minutes_ago = match status { + DeviceStatus::Stale => 60 + (rng.next().unwrap() * 4000.0) as i64, + DeviceStatus::Pending => (rng.next().unwrap() * 5.0) as i64, + DeviceStatus::Blacklisted => 600 + (rng.next().unwrap() * 8000.0) as i64, + _ => (rng.next().unwrap() * 12.0) as i64, + }; + let last_seen = now - chrono::Duration::minutes(minutes_ago); + + let ip = format!( + "10.{}.{}.{}", + 20 + (rng.next().unwrap() * 4.0) as u8, + (rng.next().unwrap() * 256.0) as u8, + (rng.next().unwrap() * 256.0) as u8 + ); + + let mut tags = Vec::new(); + let num_tags = 1 + (rng.next().unwrap() * 3.0) as usize; + let mut seen = HashSet::new(); + for _ in 0..num_tags { + let t = pick(&mut rng, &tags_pool).to_string(); + if seen.insert(t.clone()) { + tags.push(t); + } + } + + let model = pick(&mut rng, &models).to_string(); + let region = pick(&mut rng, ®ions).to_string(); + let deployment = device_deployment[i].map(str::to_string); + let fw = format!( + "v{}.{}.{}", + 1 + (rng.next().unwrap() * 3.0) as u8, + (rng.next().unwrap() * 20.0) as u8, + (rng.next().unwrap() * 10.0) as u8 + ); + let uptime_h = if status == DeviceStatus::Stale { + 0 + } else { + (rng.next().unwrap() * 4200.0) as u32 + }; + let cpu = 5 + (rng.next().unwrap() * 70.0) as u8; + let mem = 15 + (rng.next().unwrap() * 70.0) as u8; + + devices.push(DeviceDetail { + id, + status, + last_seen, + minutes_ago, + deployment, + ip: Some(ip), + region, + model, + fw, + tags, + uptime_h, + cpu, + mem, + }); + } + + // Force some control-plane devices to failing + let mut cp_failed = 0; + for d in &mut devices { + if d.deployment.as_deref() == Some("control-plane") && cp_failed < 2 { + d.status = DeviceStatus::Failing; + cp_failed += 1; + } + } + + devices +} + +// ── Deployment seed ──────────────────────────────────────────────────── + +fn seed_deployments() -> Vec { + vec![ + DeploymentDetail { + name: "edge-gateway".into(), + version: "v2.14.1".into(), + status: DeploymentStatus::Active, + target: 32, + healthy: 31, + failing: 0, + pending: 1, + updated_at: "2026-05-19 04:12".into(), + author: "r.tarzalt".into(), + }, + DeploymentDetail { + name: "sensor-firmware".into(), + version: "v0.9.3".into(), + status: DeploymentStatus::Rolling, + target: 41, + healthy: 28, + failing: 1, + pending: 12, + updated_at: "2026-05-19 06:48".into(), + author: "m.lavoie".into(), + }, + DeploymentDetail { + name: "ingest-pipeline".into(), + version: "v1.7.0".into(), + status: DeploymentStatus::Active, + target: 8, + healthy: 8, + failing: 0, + pending: 0, + updated_at: "2026-05-15 11:30".into(), + author: "r.tarzalt".into(), + }, + DeploymentDetail { + name: "control-plane".into(), + version: "v3.2.0".into(), + status: DeploymentStatus::Failing, + target: 6, + healthy: 3, + failing: 2, + pending: 1, + updated_at: "2026-05-19 07:01".into(), + author: "a.singh".into(), + }, + DeploymentDetail { + name: "telemetry-collector".into(), + version: "v0.4.12".into(), + status: DeploymentStatus::Active, + target: 12, + healthy: 12, + failing: 0, + pending: 0, + updated_at: "2026-05-12 09:22".into(), + author: "m.lavoie".into(), + }, + DeploymentDetail { + name: "gateway-proxy".into(), + version: "v1.0.5".into(), + status: DeploymentStatus::Paused, + target: 4, + healthy: 0, + failing: 0, + pending: 4, + updated_at: "2026-05-18 18:14".into(), + author: "r.tarzalt".into(), + }, + DeploymentDetail { + name: "media-relay".into(), + version: "v2.0.0-rc.3".into(), + status: DeploymentStatus::Rolling, + target: 9, + healthy: 5, + failing: 0, + pending: 4, + updated_at: "2026-05-19 06:55".into(), + author: "a.singh".into(), + }, + ] +} + +// ── Alerts seed ──────────────────────────────────────────────────────── + +fn seed_alerts() -> Vec { + vec![ + Alert { + id: "al-1".into(), + severity: AlertSeverity::Critical, + title: "control-plane rollout failing on 2 devices".into(), + deployment: Some("control-plane".into()), + device: Some("hf-gw-018".into()), + at: "2 min ago".into(), + acked: false, + }, + Alert { + id: "al-2".into(), + severity: AlertSeverity::Critical, + title: "hf-sensor-042 unreachable for 14 minutes".into(), + deployment: Some("sensor-firmware".into()), + device: Some("hf-sensor-042".into()), + at: "14 min ago".into(), + acked: false, + }, + Alert { + id: "al-3".into(), + severity: AlertSeverity::Warning, + title: "sensor-firmware rollout stalled at 68%".into(), + deployment: Some("sensor-firmware".into()), + device: None, + at: "22 min ago".into(), + acked: false, + }, + Alert { + id: "al-4".into(), + severity: AlertSeverity::Warning, + title: "hf-cam-011 reporting elevated thermal (78°C)".into(), + deployment: None, + device: Some("hf-cam-011".into()), + at: "1h ago".into(), + acked: false, + }, + Alert { + id: "al-5".into(), + severity: AlertSeverity::Info, + title: "edge-gateway v2.14.1 deployed to 31 devices".into(), + deployment: Some("edge-gateway".into()), + device: None, + at: "3h ago".into(), + acked: true, + }, + ] +} + +// ── Activity feed ───────────────────────────────────────────────────── + +fn activity_feed() -> Vec { + vec![ + Activity { + who: "r.tarzalt".into(), + verb: "started rollout".into(), + target: "sensor-firmware v0.9.3".into(), + at: "07:24".into(), + }, + Activity { + who: "system".into(), + verb: "auto-blacklisted".into(), + target: "hf-sensor-091".into(), + at: "07:18".into(), + }, + Activity { + who: "a.singh".into(), + verb: "paused deployment".into(), + target: "gateway-proxy".into(), + at: "07:02".into(), + }, + Activity { + who: "system".into(), + verb: "detected failure".into(), + target: "hf-gw-018 (control-plane)".into(), + at: "06:51".into(), + }, + Activity { + who: "m.lavoie".into(), + verb: "updated task graph".into(), + target: "telemetry-collector".into(), + at: "06:14".into(), + }, + Activity { + who: "r.tarzalt".into(), + verb: "logged in".into(), + target: String::new(), + at: "06:02".into(), + }, + ] +} + +// ── Trend generation ────────────────────────────────────────────────── + +fn ingest_trend() -> Vec { + let mut rng = Rng(1337); + (0..48) + .map(|i| { + let base = 38.0 + (i as f64 / 4.0).sin() * 8.0 + (rng.next().unwrap() * 6.0); + (base.max(2.0)).round() as u32 + }) + .collect() +} + +fn health_trend() -> Vec { + let mut rng = Rng(1337); + (0..48) + .map(|i| { + let v = 96.0 + + (i as f64 / 6.0).sin() * 1.4 + - if i > 38 && i < 44 { 6.0 } else { 0.0 } + + (rng.next().unwrap() * 0.4); + (v * 10.0).round() / 10.0 + }) + .collect() +} + +// ── Task graph ───────────────────────────────────────────────────────── + +fn task_graph() -> TaskGraph { + let mut positions = HashMap::new(); + positions.insert("t1".into(), (0, 1)); + positions.insert("t2".into(), (1, 1)); + positions.insert("t3".into(), (2, 1)); + positions.insert("t4".into(), (3, 1)); + positions.insert("t5".into(), (4, 1)); + positions.insert("t6".into(), (5, 0)); + positions.insert("t7".into(), (5, 2)); + positions.insert("t8".into(), (6, 1)); + + TaskGraph { + nodes: vec![ + TaskNode { + id: "t1".into(), + label: "fetch artifact".into(), + status: TaskStatus::Done, + duration: "2s".into(), + }, + TaskNode { + id: "t2".into(), + label: "verify signature".into(), + status: TaskStatus::Done, + duration: "0.4s".into(), + }, + TaskNode { + id: "t3".into(), + label: "stop services".into(), + status: TaskStatus::Done, + duration: "1.1s".into(), + }, + TaskNode { + id: "t4".into(), + label: "install deps".into(), + status: TaskStatus::Running, + duration: "12s".into(), + }, + TaskNode { + id: "t5".into(), + label: "mount volumes".into(), + status: TaskStatus::Pending, + duration: "—".into(), + }, + TaskNode { + id: "t6".into(), + label: "launch sensord".into(), + status: TaskStatus::Pending, + duration: "—".into(), + }, + TaskNode { + id: "t7".into(), + label: "launch relayd".into(), + status: TaskStatus::Pending, + duration: "—".into(), + }, + TaskNode { + id: "t8".into(), + label: "health probe".into(), + status: TaskStatus::Pending, + duration: "—".into(), + }, + ], + edges: vec![ + ("t1".into(), "t2".into()), + ("t2".into(), "t3".into()), + ("t3".into(), "t4".into()), + ("t4".into(), "t5".into()), + ("t5".into(), "t6".into()), + ("t5".into(), "t7".into()), + ("t6".into(), "t8".into()), + ("t7".into(), "t8".into()), + ], + positions, + } +} + +// ── FleetService impl ───────────────────────────────────────────────── + #[async_trait] impl FleetService for MockFleetService { - async fn dashboard_summary(&self) -> anyhow::Result { + async fn dashboard_detail(&self) -> anyhow::Result { let devices = self.devices.lock().unwrap(); let deployments = self.deployments.lock().unwrap(); - let mut s = DashboardSummary { + let alerts = self.alerts.lock().unwrap(); + + let mut d = DashboardDetail { devices_total: devices.len() as u32, - deployments_total: deployments.len() as u32, - ..Default::default() + devices_healthy: 0, + devices_pending: 0, + devices_failing: 0, + devices_stale: 0, + devices_blacklisted: 0, + devices_unknown: 0, + deployments_total: deployments.len(), + health_pct: 0, + health_trend: health_trend(), + ingest_rate: *ingest_trend().last().unwrap_or(&0), + ingest_trend: ingest_trend(), + attention_devices: vec![], + activity_feed: activity_feed(), + top_deployments: deployments.clone(), + active_alerts: alerts + .iter() + .filter(|a| !a.acked) + .take(10) + .cloned() + .collect(), + rolling_count: 0, + failing_count: 0, }; - for d in devices.values() { - match d.status { - DeviceStatus::Healthy => s.devices_healthy += 1, - DeviceStatus::Pending => s.devices_pending += 1, - DeviceStatus::Stale => s.devices_stale += 1, - DeviceStatus::Blacklisted => s.devices_blacklisted += 1, - DeviceStatus::Unknown => {} + + for dev in devices.iter() { + match dev.status { + DeviceStatus::Healthy => d.devices_healthy += 1, + DeviceStatus::Pending => d.devices_pending += 1, + DeviceStatus::Stale => d.devices_stale += 1, + DeviceStatus::Failing => d.devices_failing += 1, + DeviceStatus::Blacklisted => d.devices_blacklisted += 1, + DeviceStatus::Unknown => d.devices_unknown += 1, } } - for d in deployments.iter() { - match d.status { - DeploymentStatus::Active | DeploymentStatus::Rolling => s.deployments_active += 1, - DeploymentStatus::Failing => s.deployments_failing += 1, - DeploymentStatus::Paused => {} + d.health_pct = + ((d.devices_healthy as f64 / d.devices_total as f64) * 100.0).round() as u32; + + d.attention_devices = devices + .iter() + .filter(|d| { + d.status == DeviceStatus::Failing + || d.status == DeviceStatus::Stale + || d.status == DeviceStatus::Pending + }) + .take(12) + .cloned() + .collect(); + + for dep in deployments.iter() { + match dep.status { + DeploymentStatus::Rolling => d.rolling_count += 1, + DeploymentStatus::Failing => d.failing_count += 1, + _ => {} } } - Ok(s) + + d.top_deployments.truncate(4); + Ok(d) } - async fn list_devices(&self) -> anyhow::Result> { - let mut out: Vec<_> = self.devices.lock().unwrap().values().cloned().collect(); - out.sort_by(|a, b| a.id.cmp(&b.id)); - Ok(out) + async fn list_devices(&self) -> anyhow::Result> { + Ok(self.devices.lock().unwrap().clone()) } - async fn get_device(&self, id: &str) -> anyhow::Result> { - Ok(self.devices.lock().unwrap().get(id).cloned()) + async fn get_device(&self, id: &str) -> anyhow::Result> { + Ok(self + .devices + .lock() + .unwrap() + .iter() + .find(|d| d.id == id) + .cloned()) } - async fn list_deployments(&self) -> anyhow::Result> { + async fn list_deployments(&self) -> anyhow::Result> { Ok(self.deployments.lock().unwrap().clone()) } - async fn blacklist_device(&self, id: &str) -> anyhow::Result { + async fn get_deployment(&self, name: &str) -> anyhow::Result> { + Ok(self + .deployments + .lock() + .unwrap() + .iter() + .find(|d| d.name == name) + .cloned()) + } + + async fn get_deployment_devices(&self, name: &str) -> anyhow::Result> { + Ok(self + .devices + .lock() + .unwrap() + .iter() + .filter(|d| d.deployment.as_deref() == Some(name)) + .cloned() + .collect()) + } + + async fn blacklist_device(&self, id: &str) -> anyhow::Result { let mut devices = self.devices.lock().unwrap(); let dev = devices - .get_mut(id) + .iter_mut() + .find(|d| d.id == id) .ok_or_else(|| anyhow::anyhow!("device {id} not found"))?; dev.status = DeviceStatus::Blacklisted; dev.deployment = None; Ok(dev.clone()) } + + async fn list_alerts(&self) -> anyhow::Result> { + Ok(self.alerts.lock().unwrap().clone()) + } + + async fn ack_alert(&self, id: &str) -> anyhow::Result { + let mut alerts = self.alerts.lock().unwrap(); + if let Some(a) = alerts.iter_mut().find(|a| a.id == id) { + a.acked = true; + Ok(true) + } else { + Ok(false) + } + } + + async fn get_task_graph(&self, _deployment: &str) -> anyhow::Result { + Ok(task_graph()) + } + + async fn filtered_devices( + &self, + status: Option, + deployment: Option, + region: Option, + search: Option, + ) -> anyhow::Result> { + let devices = self.devices.lock().unwrap(); + let mut out: Vec = devices.iter().cloned().filter(|d| { + if let Some(s) = status { + if d.status != s { return false; } + } + if let Some(ref dep) = deployment { + if d.deployment.as_deref() != Some(dep.as_str()) { return false; } + } + if let Some(ref reg) = region { + if d.region != *reg { return false; } + } + if let Some(ref q) = search { + let q = q.to_lowercase(); + if !d.id.to_lowercase().contains(&q) + && !d.deployment.as_deref().unwrap_or("").to_lowercase().contains(&q) + && !d.ip.as_deref().unwrap_or("").contains(&q) + && !d.tags.iter().any(|t| t.to_lowercase().contains(&q)) + { + return false; + } + } + true + }).collect(); + out.sort_by(|a, b| a.id.cmp(&b.id)); + Ok(out) + } } #[cfg(test)] @@ -198,24 +662,33 @@ mod tests { use super::*; #[tokio::test] - async fn dashboard_summary_counts_by_status() { + async fn dashboard_detail_counts() { let svc = MockFleetService::default(); - let s = svc.dashboard_summary().await.unwrap(); - assert_eq!(s.devices_total, 10); - assert_eq!(s.devices_healthy, 4); - assert_eq!(s.devices_pending, 2); - assert_eq!(s.devices_stale, 2); - assert_eq!(s.devices_blacklisted, 1); + let d = svc.dashboard_detail().await.unwrap(); + assert_eq!(d.devices_total, 100); + assert!(d.devices_healthy > 0); + assert!(d.health_pct > 0); + assert!(!d.activity_feed.is_empty()); } #[tokio::test] async fn blacklist_flips_status() { let svc = MockFleetService::default(); - let before = svc.get_device("pi-001").await.unwrap().unwrap(); - assert_eq!(before.status, DeviceStatus::Healthy); - svc.blacklist_device("pi-001").await.unwrap(); - let after = svc.get_device("pi-001").await.unwrap().unwrap(); + let dev = svc.get_device("hf-edge-001").await.unwrap().unwrap(); + assert_eq!(dev.status, DeviceStatus::Healthy); + svc.blacklist_device("hf-edge-001").await.unwrap(); + let after = svc.get_device("hf-edge-001").await.unwrap().unwrap(); assert_eq!(after.status, DeviceStatus::Blacklisted); assert!(after.deployment.is_none()); } + + #[tokio::test] + async fn filtered_devices_by_status() { + let svc = MockFleetService::default(); + let failing = svc + .filtered_devices(Some(DeviceStatus::Failing), None, None, None) + .await + .unwrap(); + assert!(failing.iter().all(|d| d.status == DeviceStatus::Failing)); + } } diff --git a/fleet/harmony-fleet-operator/src/service/mod.rs b/fleet/harmony-fleet-operator/src/service/mod.rs index 50ebf351..3c927826 100644 --- a/fleet/harmony-fleet-operator/src/service/mod.rs +++ b/fleet/harmony-fleet-operator/src/service/mod.rs @@ -1,17 +1,3 @@ -//! Domain-level fleet query/command surface. -//! -//! Presentation (the `frontend` module) and any future CLI both call -//! into this trait. Implementations: -//! -//! - [`mock::MockFleetService`] — in-memory fake data, for `serve-web --mock` -//! and tests. Reachable without NATS or a Kubernetes cluster. -//! - `real::KubeNatsFleetService` (TODO) — wraps the operator's real -//! data sources (kube client + NATS JetStream KV). - -// The whole module is dead code when neither the web frontend nor any -// future CLI is compiled in — it's intentionally a library surface. -#![allow(dead_code)] - pub mod mock; use async_trait::async_trait; @@ -20,28 +6,51 @@ use serde::Serialize; #[async_trait] pub trait FleetService: Send + Sync + 'static { - async fn dashboard_summary(&self) -> anyhow::Result; - async fn list_devices(&self) -> anyhow::Result>; - async fn get_device(&self, id: &str) -> anyhow::Result>; - async fn list_deployments(&self) -> anyhow::Result>; - async fn blacklist_device(&self, id: &str) -> anyhow::Result; + async fn dashboard_detail(&self) -> anyhow::Result; + async fn list_devices(&self) -> anyhow::Result>; + async fn get_device(&self, id: &str) -> anyhow::Result>; + async fn list_deployments(&self) -> anyhow::Result>; + async fn get_deployment(&self, name: &str) -> anyhow::Result>; + async fn get_deployment_devices(&self, name: &str) -> anyhow::Result>; + async fn blacklist_device(&self, id: &str) -> anyhow::Result; + async fn list_alerts(&self) -> anyhow::Result>; + async fn ack_alert(&self, id: &str) -> anyhow::Result; + async fn get_task_graph(&self, deployment: &str) -> anyhow::Result; + async fn filtered_devices( + &self, + status: Option, + deployment: Option, + region: Option, + search: Option, + ) -> anyhow::Result>; } +// ── Device ───────────────────────────────────────────────────────────── + #[derive(Debug, Clone, Serialize)] -pub struct DeviceSummary { +pub struct DeviceDetail { pub id: String, pub status: DeviceStatus, pub last_seen: DateTime, + pub minutes_ago: i64, pub deployment: Option, pub ip: Option, + pub region: String, + pub model: String, + pub fw: String, + pub tags: Vec, + pub uptime_h: u32, + pub cpu: u8, + pub mem: u8, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "kebab-case")] pub enum DeviceStatus { Healthy, Pending, Stale, + Failing, Blacklisted, Unknown, } @@ -49,24 +58,32 @@ pub enum DeviceStatus { impl DeviceStatus { pub fn label(self) -> &'static str { match self { - DeviceStatus::Healthy => "healthy", - DeviceStatus::Pending => "pending", - DeviceStatus::Stale => "stale", - DeviceStatus::Blacklisted => "blacklisted", - DeviceStatus::Unknown => "unknown", + Self::Healthy => "healthy", + Self::Pending => "pending", + Self::Stale => "stale", + Self::Failing => "failing", + Self::Blacklisted => "blacklisted", + Self::Unknown => "unknown", } } } +// ── Deployment ───────────────────────────────────────────────────────── + #[derive(Debug, Clone, Serialize)] -pub struct DeploymentSummary { +pub struct DeploymentDetail { pub name: String, + pub version: String, pub status: DeploymentStatus, - pub target_devices: u32, - pub healthy_devices: u32, + pub target: u32, + pub healthy: u32, + pub failing: u32, + pub pending: u32, + pub updated_at: String, + pub author: String, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "kebab-case")] pub enum DeploymentStatus { Active, @@ -78,22 +95,101 @@ pub enum DeploymentStatus { impl DeploymentStatus { pub fn label(self) -> &'static str { match self { - DeploymentStatus::Active => "active", - DeploymentStatus::Rolling => "rolling", - DeploymentStatus::Failing => "failing", - DeploymentStatus::Paused => "paused", + Self::Active => "active", + Self::Rolling => "rolling", + Self::Failing => "failing", + Self::Paused => "paused", } } } -#[derive(Debug, Clone, Default, Serialize)] -pub struct DashboardSummary { +// ── Dashboard ────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize)] +pub struct DashboardDetail { pub devices_total: u32, pub devices_healthy: u32, pub devices_pending: u32, + pub devices_failing: u32, pub devices_stale: u32, pub devices_blacklisted: u32, - pub deployments_total: u32, - pub deployments_active: u32, - pub deployments_failing: u32, + pub devices_unknown: u32, + pub deployments_total: usize, + pub health_pct: u32, + pub health_trend: Vec, + pub ingest_rate: u32, + pub ingest_trend: Vec, + pub attention_devices: Vec, + pub activity_feed: Vec, + pub top_deployments: Vec, + pub active_alerts: Vec, + pub rolling_count: usize, + pub failing_count: usize, +} + +// ── Alert ────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize)] +pub struct Alert { + pub id: String, + pub severity: AlertSeverity, + pub title: String, + pub deployment: Option, + pub device: Option, + pub at: String, + pub acked: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum AlertSeverity { + Critical, + Warning, + Info, +} + +impl AlertSeverity { + pub fn label(self) -> &'static str { + match self { + Self::Critical => "critical", + Self::Warning => "warning", + Self::Info => "info", + } + } +} + +// ── Activity ─────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize)] +pub struct Activity { + pub who: String, + pub verb: String, + pub target: String, + pub at: String, +} + +// ── Task Graph ───────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize)] +pub struct TaskGraph { + pub nodes: Vec, + pub edges: Vec<(String, String)>, + pub positions: std::collections::HashMap, +} + +#[derive(Debug, Clone, Serialize)] +pub struct TaskNode { + pub id: String, + pub label: String, + pub status: TaskStatus, + pub duration: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum TaskStatus { + Done, + Running, + Pending, + Failed, } diff --git a/fleet/harmony-fleet-operator/style/input.css b/fleet/harmony-fleet-operator/style/input.css index 41db48a4..3363275b 100644 --- a/fleet/harmony-fleet-operator/style/input.css +++ b/fleet/harmony-fleet-operator/style/input.css @@ -2,3 +2,105 @@ @source "../src"; @source "../style"; + +/* ── CSS Custom Properties (default theme) ─────────────────────────── */ +:root { + --bg: #07090c; + --bg-elev: #0c1018; + --bg-elev-2: #11151f; + --border: rgba(148, 163, 184, 0.08); + --border-strong: rgba(148, 163, 184, 0.16); + --accent: #f97316; /* orange-500 */ + --accent-soft: rgba(249, 115, 22, 0.14); + --accent-fg: #fdba74; + --ok: #34d399; + --ok-soft: rgba(52, 211, 153, 0.13); + --warn: #fbbf24; + --warn-soft: rgba(251, 191, 36, 0.13); + --bad: #fb7185; + --bad-soft: rgba(251, 113, 133, 0.13); + --info: #60a5fa; + --info-soft: rgba(96, 165, 250, 0.13); + --row-h: 38px; +} + +html, body { background: var(--bg); } +body { font-family: 'Inter', sans-serif; color: #e2e8f0; -webkit-font-smoothing: antialiased; } + +::selection { background: var(--accent-soft); color: #fff; } + +/* ── Scrollbar ──────────────────────────────────────────────────────── */ +*::-webkit-scrollbar { width: 10px; height: 10px; } +*::-webkit-scrollbar-track { background: transparent; } +*::-webkit-scrollbar-thumb { background: rgba(148,163,184,0.14); border-radius: 999px; border: 2px solid transparent; background-clip: content-box; } +*::-webkit-scrollbar-thumb:hover { background: rgba(148,163,184,0.28); background-clip: content-box; border: 2px solid transparent; } + +/* ── Animations ─────────────────────────────────────────────────────── */ +@keyframes ping-soft { 0% { transform: scale(1); opacity: .55; } 75%, 100% { transform: scale(2.4); opacity: 0; } } +.pulse-dot::after { content:''; position:absolute; inset:0; border-radius:9999px; background:currentColor; animation: ping-soft 1.8s cubic-bezier(0,0,.2,1) infinite; } +.pulse-dot { position: relative; } + +@keyframes log-in { from { opacity:0; transform: translateY(2px); } to { opacity:1; transform: translateY(0); } } +.log-line { animation: log-in .22s ease-out both; } + +@keyframes draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } } +.spark-path { stroke-dasharray: 1; stroke-dashoffset: 1; animation: draw 1.4s ease-out forwards; } + +@keyframes toast-in { from { opacity:0; transform: translateY(8px) scale(.98); } to { opacity:1; transform: translateY(0) scale(1); } } +.toast-in { animation: toast-in .25s cubic-bezier(.2,.7,.3,1) both; } +@keyframes toast-out { to { opacity:0; transform: translateY(-6px) scale(.98); } } +.toast-out { animation: toast-out .22s ease-in both; } + +@keyframes roll-marquee { 0% { transform: translateX(-100%); } 100% { transform: translateX(400%); } } + +/* ── Grid background ────────────────────────────────────────────────── */ +.grid-bg { + background-image: + linear-gradient(rgba(148,163,184,0.04) 1px, transparent 1px), + linear-gradient(90deg, rgba(148,163,184,0.04) 1px, transparent 1px); + background-size: 32px 32px; + background-position: -1px -1px; +} + +/* ── Density ────────────────────────────────────────────────────────── */ +.density-compact { --row-h: 32px; } +.density-comfort { --row-h: 44px; } + +/* ── Buttons ────────────────────────────────────────────────────────── */ +.btn { display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border-radius:7px; font-size:12px; font-weight:500; transition: all .15s; cursor: pointer; border: 1px solid transparent; } +.btn-primary { background: var(--accent); color: #0c0c0c; } +.btn-primary:hover { filter: brightness(1.1); } +.btn-ghost { background: transparent; color: #cbd5e1; border-color: var(--border-strong); } +.btn-ghost:hover { background: rgba(148,163,184,0.06); color:#f1f5f9; } +.btn-danger { background: rgba(244, 63, 94, 0.12); color: #fb7185; border-color: rgba(244,63,94,0.25); } +.btn-danger:hover { background: rgba(244, 63, 94, 0.2); color:#fda4af; } + +/* ── Cards ──────────────────────────────────────────────────────────── */ +.card { background: var(--bg-elev); border: 1px solid var(--border); border-radius: 10px; } +.card-flush { border-radius: 10px; overflow: hidden; } + +/* ── Tables ─────────────────────────────────────────────────────────── */ +.tbl { width: 100%; font-size: 13px; } +.tbl thead th { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em; color: #64748b; font-weight: 600; padding: 10px 14px; text-align: left; background: rgba(148,163,184,0.02); border-bottom: 1px solid var(--border); } +.tbl tbody td { padding: 0 14px; height: var(--row-h); border-bottom: 1px solid var(--border); color: #cbd5e1; } +.tbl tbody tr:hover { background: rgba(148,163,184,0.025); } +.tbl tbody tr.selected { background: var(--accent-soft); } +.tbl tbody tr.selected td { color: #f1f5f9; } + +/* ── Inputs ─────────────────────────────────────────────────────────── */ +.input { background: var(--bg-elev-2); border: 1px solid var(--border-strong); border-radius: 7px; padding: 6px 10px 6px 30px; font-size: 13px; color: #e2e8f0; outline: none; transition: border .15s; } +.input:focus { border-color: var(--accent); } + +/* ── Chips ──────────────────────────────────────────────────────────── */ +.chip { display:inline-flex; align-items:center; gap:6px; padding: 4px 9px; border-radius: 999px; font-size: 11px; font-weight: 500; border: 1px solid var(--border-strong); background: rgba(148,163,184,0.03); color:#cbd5e1; cursor:pointer; } +.chip.active { background: var(--accent-soft); color: var(--accent-fg); border-color: rgba(249,115,22,0.35); } +.chip:hover:not(.active) { color:#f1f5f9; background: rgba(148,163,184,0.07); } + +/* ── Section title ──────────────────────────────────────────────────── */ +.section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 600; color: #64748b; } + +/* ── Progress bar ───────────────────────────────────────────────────── */ +.progress-bg { background: rgba(148,163,184,0.1); } + +/* ── Font helpers ───────────────────────────────────────────────────── */ +.id-mono { font-family: 'JetBrains Mono', ui-monospace, monospace; white-space: nowrap; } diff --git a/fleet/harmony-fleet-operator/vendor/app.js b/fleet/harmony-fleet-operator/vendor/app.js new file mode 100644 index 00000000..218b0e6f --- /dev/null +++ b/fleet/harmony-fleet-operator/vendor/app.js @@ -0,0 +1,3 @@ +document.body.addEventListener('htmx:configRequest', (event) => { + event.detail.headers['x-csrf-token'] = '1'; +}); diff --git a/harmony_assets/src/store/local.rs b/harmony_assets/src/store/local.rs index 0a6486a4..76fded28 100644 --- a/harmony_assets/src/store/local.rs +++ b/harmony_assets/src/store/local.rs @@ -174,6 +174,7 @@ mod tests { #[cfg(feature = "reqwest")] mod download_tests { use super::*; + use crate::ChecksumAlgo; use httptest::{Expectation, Server, matchers::request, responders::*}; fn test_asset_with_url(url: &str, checksum: &str) -> Asset { diff --git a/harmony_zitadel_auth/Cargo.toml b/harmony_zitadel_auth/Cargo.toml new file mode 100644 index 00000000..7fef2c30 --- /dev/null +++ b/harmony_zitadel_auth/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "harmony_zitadel_auth" +edition = "2024" +version.workspace = true +readme.workspace = true +license.workspace = true + +[features] +default = [] +axum = ["dep:axum", "dep:axum-extra"] + +[dependencies] +anyhow.workspace = true +base64.workspace = true +chrono = { workspace = true, features = ["serde"] } +rand.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2 = "0.10" +url.workspace = true +tokio = { workspace = true, features = ["time"] } +arc-swap = "1" +time = "0.3" +tracing = { workspace = true } + +jsonwebtoken = "9" +openidconnect = { version = "4", default-features = false, features = ["reqwest", "rustls-tls"] } +axum = { version = "0.8", optional = true } +axum-extra = { version = "0.10", features = ["cookie", "cookie-private"], optional = true } diff --git a/harmony_zitadel_auth/src/axum_login_flow.rs b/harmony_zitadel_auth/src/axum_login_flow.rs new file mode 100644 index 00000000..96a9391f --- /dev/null +++ b/harmony_zitadel_auth/src/axum_login_flow.rs @@ -0,0 +1,164 @@ +use anyhow::Result; +use axum::extract::{Query, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Redirect, Response}; +use axum_extra::extract::cookie::{Cookie, PrivateCookieJar, SameSite}; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; + +use crate::config::ZitadelAuthConfig; +use crate::jwks::JwksCache; +use crate::login::{ + AuthCallbackQuery, RawAuthCallbackQuery, TokenResponse, build_login_attempt, build_logout_url, + exchange_code_for_token, jwt_exp, validate_callback_state, +}; +use crate::session::LoginAttemptCookie; + +pub const LOGIN_ATTEMPT_COOKIE: &str = "harmony_fleet_login_attempt"; +pub const HARMONY_SESSION_COOKIE: &str = "harmony_fleet_session"; + +/// Session cookie holds the raw Zitadel JWT. The `PrivateCookieJar` (AES-GCM) +/// encrypts both the login-attempt cookie (PKCE verifier) and the session cookie +/// (id_token), so the JWT is never exposed in plaintext on the wire. +pub async fn login_handler( + jar: PrivateCookieJar, + State(config): State, +) -> Response { + match build_login_response(jar, &config) { + Ok(r) => r.into_response(), + Err(e) => auth_error_response(e), + } +} + +fn build_login_response( + jar: PrivateCookieJar, + config: &ZitadelAuthConfig, +) -> Result { + let attempt = build_login_attempt(config)?; + let cookie_payload = LoginAttemptCookie::from(&attempt); + let cookie_value = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&cookie_payload)?); + + let mut builder = Cookie::build((LOGIN_ATTEMPT_COOKIE, cookie_value)) + .http_only(true) + .same_site(SameSite::Lax) + .path("/") + .max_age(time::Duration::minutes(10)); + if config.use_secure_cookies() { + builder = builder.secure(true); + } + Ok(( + jar.add(builder.build()), + Redirect::temporary(&attempt.authorize_url), + )) +} + +pub async fn logout_handler( + session_jar: PrivateCookieJar, + State(config): State, +) -> Response { + match build_logout_response(session_jar, &config) { + Ok(r) => r.into_response(), + Err(e) => auth_error_response(e), + } +} + +fn build_logout_response( + session_jar: PrivateCookieJar, + config: &ZitadelAuthConfig, +) -> Result { + // The session cookie value IS the raw JWT (id_token), used as the Zitadel logout hint. + let id_token = session_jar + .get(HARMONY_SESSION_COOKIE) + .map(|c| c.value().to_string()) + .unwrap_or_default(); + let session_jar = session_jar.remove(Cookie::build(HARMONY_SESSION_COOKIE).path("/").build()); + let logout_url = build_logout_url(config, &id_token)?; + Ok((session_jar, Redirect::to(logout_url.as_str()))) +} + +pub async fn callback_handler( + jar: PrivateCookieJar, + session_jar: PrivateCookieJar, + State(config): State, + State(http_client): State, + State(jwks): State, + Query(raw): Query, +) -> Response { + match build_callback_response(jar, session_jar, raw, &config, &http_client, &jwks).await { + Ok(r) => r, + Err(e) => auth_error_response(e), + } +} + +async fn build_callback_response( + jar: PrivateCookieJar, + session_jar: PrivateCookieJar, + raw: RawAuthCallbackQuery, + config: &ZitadelAuthConfig, + http_client: &reqwest::Client, + jwks: &JwksCache, +) -> Result { + match AuthCallbackQuery::try_from(raw)? { + AuthCallbackQuery::Success { code, state } => { + let attempt = read_login_attempt_cookie(&jar)?; + let jar = jar.remove(Cookie::from(LOGIN_ATTEMPT_COOKIE)); + validate_callback_state(&attempt, &state)?; + + let tokens = + exchange_code_for_token(http_client, config, &attempt.pkce_code_verifier, &code) + .await?; + let verified = jwks.verify(&tokens.id_token, config).await?; + if verified.nonce.as_deref() != Some(attempt.nonce.as_str()) { + anyhow::bail!("auth callback nonce mismatch; start again at /login"); + } + + let session_jar = session_jar.add(session_cookie(&tokens, config)); + Ok((jar, session_jar, Redirect::to("/")).into_response()) + } + AuthCallbackQuery::Failure { + error, + error_description, + } => { + anyhow::bail!( + "SSO callback returned an error: {error} {}", + error_description.unwrap_or_default() + ) + } + } +} + +fn session_cookie(tokens: &TokenResponse, config: &ZitadelAuthConfig) -> Cookie<'static> { + let max_age_secs = + jwt_exp(&tokens.id_token).map(|exp| (exp - chrono::Utc::now().timestamp()).max(0)); + + let mut builder = Cookie::build((HARMONY_SESSION_COOKIE, tokens.id_token.clone())) + .http_only(true) + .same_site(SameSite::Lax) + .path("/"); + if config.use_secure_cookies() { + builder = builder.secure(true); + } + if let Some(secs) = max_age_secs { + builder = builder.max_age(time::Duration::seconds(secs)); + } + builder.build() +} + +pub fn read_login_attempt_cookie(jar: &PrivateCookieJar) -> Result { + let cookie = jar + .get(LOGIN_ATTEMPT_COOKIE) + .ok_or_else(|| anyhow::anyhow!("missing login attempt cookie; start again at /login"))?; + let bytes = URL_SAFE_NO_PAD + .decode(cookie.value()) + .map_err(|e| anyhow::anyhow!("invalid login attempt cookie encoding: {e}"))?; + serde_json::from_slice::(&bytes) + .map_err(|e| anyhow::anyhow!("invalid login attempt cookie payload: {e}")) +} + +fn auth_error_response(e: anyhow::Error) -> Response { + ( + StatusCode::BAD_REQUEST, + format!("SSO login failed\nError: {e}\n"), + ) + .into_response() +} diff --git a/harmony_zitadel_auth/src/config.rs b/harmony_zitadel_auth/src/config.rs new file mode 100644 index 00000000..52019426 --- /dev/null +++ b/harmony_zitadel_auth/src/config.rs @@ -0,0 +1,75 @@ +#[derive(Debug, Clone)] +pub struct ZitadelAuthConfig { + pub zitadel_base: String, + pub base_url: String, + pub client_id: String, + pub scope: String, + pub trusted_audiences: Vec, + pub logout_redirect_uri: String, +} + +impl ZitadelAuthConfig { + pub fn issuer_url(&self) -> String { + self.zitadel_base.clone() + } + pub fn authorize_url(&self) -> String { + format!("{}/oauth/v2/authorize", self.zitadel_base) + } + pub fn token_url(&self) -> String { + format!("{}/oauth/v2/token", self.zitadel_base) + } + pub fn logout_url(&self) -> String { + format!("{}/oidc/v1/end_session", self.zitadel_base) + } + pub fn redirect_uri(&self) -> String { + format!("{}/auth/callback", self.base_url) + } + pub fn logout_redirect_uri(&self) -> String { + self.logout_redirect_uri.clone() + } + /// Whether to set the `Secure` flag on cookies. True when `base_url` is HTTPS. + pub fn use_secure_cookies(&self) -> bool { + self.base_url.starts_with("https://") + } +} + +pub const ZITADEL_BASE_ENV: &str = "FLEET_AUTH_ZITADEL_BASE"; +pub const BASE_URL_ENV: &str = "BASE_URL"; +pub const CLIENT_ID_ENV: &str = "FLEET_AUTH_CLIENT_ID"; +pub const SCOPE_ENV: &str = "FLEET_AUTH_SCOPE"; +pub const TRUSTED_AUDIENCES_ENV: &str = "FLEET_AUTH_TRUSTED_AUDIENCES"; +pub const LOGOUT_REDIRECT_URI_ENV: &str = "FLEET_AUTH_LOGOUT_REDIRECT_URI"; +pub const COOKIE_KEY_ENV: &str = "FLEET_OPERATOR_COOKIE_KEY_B64"; + +pub fn config_from_env() -> ZitadelAuthConfig { + ZitadelAuthConfig { + zitadel_base: required_env(ZITADEL_BASE_ENV), + base_url: required_env(BASE_URL_ENV), + client_id: required_env(CLIENT_ID_ENV), + scope: required_env(SCOPE_ENV), + trusted_audiences: required_env(TRUSTED_AUDIENCES_ENV) + .split(',') + .map(str::to_string) + .collect(), + logout_redirect_uri: required_env(LOGOUT_REDIRECT_URI_ENV), + } +} + +#[cfg(feature = "axum")] +pub fn cookie_key_from_env() -> axum_extra::extract::cookie::Key { + use base64::Engine; + use base64::engine::general_purpose::STANDARD; + + let encoded = required_env(COOKIE_KEY_ENV); + let bytes = STANDARD + .decode(encoded.trim()) + .unwrap_or_else(|e| panic!("{COOKIE_KEY_ENV} must be standard base64: {e}")); + if bytes.len() < 64 { + panic!("{COOKIE_KEY_ENV} must decode to at least 64 bytes for private cookies"); + } + axum_extra::extract::cookie::Key::from(&bytes) +} + +fn required_env(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("missing required environment variable {name}")) +} diff --git a/harmony_zitadel_auth/src/jwks.rs b/harmony_zitadel_auth/src/jwks.rs new file mode 100644 index 00000000..ed8947cf --- /dev/null +++ b/harmony_zitadel_auth/src/jwks.rs @@ -0,0 +1,210 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use serde::Deserialize; + +use crate::config::ZitadelAuthConfig; +use crate::session::VerifiedSession; + +struct JwksCacheInner { + set: jsonwebtoken::jwk::JwkSet, + last_forced_refresh: Option, +} + +/// Cached Zitadel JWKS for per-request JWT verification. +/// +/// Reads are lock-free via `ArcSwap` — only refreshes pay any coordination +/// cost. `Clone` is cheap; the inner state is `Arc`-wrapped. +#[derive(Clone)] +pub struct JwksCache { + inner: Arc>, + jwks_uri: Arc, + http: reqwest::Client, +} + +impl JwksCache { + /// Fetch the JWKS via OIDC discovery and build the cache. + pub async fn new(issuer_url: &str, http: reqwest::Client) -> Result { + let jwks_uri = discover_jwks_uri(issuer_url, &http).await?; + let set = fetch_jwks(&jwks_uri, &http).await?; + tracing::debug!(%jwks_uri, keys = set.keys.len(), "JWKS loaded"); + Ok(Self { + inner: Arc::new(arc_swap::ArcSwap::from_pointee(JwksCacheInner { + set, + last_forced_refresh: None, + })), + jwks_uri: jwks_uri.into(), + http, + }) + } + + /// Spawn a background task that refreshes the JWKS on the given `interval`. + /// + /// On failure the stale keys are kept and a warning is logged — a Zitadel + /// blip must not log everyone out. + pub fn spawn_background_refresh(&self, interval: Duration) { + let cache = self.clone(); + tokio::spawn(async move { + let mut ticker = tokio::time::interval(interval); + ticker.tick().await; // skip the first immediate tick + loop { + ticker.tick().await; + match fetch_jwks(&cache.jwks_uri, &cache.http).await { + Ok(new_set) => { + let last_forced = cache.inner.load().last_forced_refresh; + cache.inner.store(Arc::new(JwksCacheInner { + set: new_set, + last_forced_refresh: last_forced, + })); + tracing::debug!("JWKS background refresh succeeded"); + } + Err(e) => { + tracing::warn!(error = %e, "JWKS background refresh failed; keeping stale keys") + } + } + } + }); + } + + /// Verify a raw JWT string and return the validated session claims. + /// + /// On unknown `kid`, performs one forced JWKS refresh (rate-limited to + /// once per 60 s) before giving up, to handle key rotation gracefully. + pub async fn verify(&self, token: &str, config: &ZitadelAuthConfig) -> Result { + let header = jsonwebtoken::decode_header(token) + .map_err(|e| anyhow::anyhow!("invalid JWT header: {e}"))?; + let kid = header.kid.as_deref().unwrap_or(""); + + // Fast path: lock-free read — ArcSwap guard must not be held across awaits. + { + let inner = self.inner.load(); + if let Some(result) = try_verify_with_set(token, &inner.set, kid, config) { + return result; + } + } + + // Slow path: kid not found — maybe Zitadel rotated keys. + let should_refresh = self + .inner + .load() + .last_forced_refresh + .map(|t| t.elapsed() > Duration::from_secs(60)) + .unwrap_or(true); + + if should_refresh { + match fetch_jwks(&self.jwks_uri, &self.http).await { + Ok(new_set) => { + self.inner.store(Arc::new(JwksCacheInner { + set: new_set, + last_forced_refresh: Some(Instant::now()), + })); + let inner = self.inner.load(); + if let Some(result) = try_verify_with_set(token, &inner.set, kid, config) { + return result; + } + } + Err(e) => tracing::warn!(error = %e, "JWKS forced refresh failed"), + } + } + + anyhow::bail!("unknown JWT signing key (kid={kid:?})") + } +} + +fn try_verify_with_set( + token: &str, + set: &jsonwebtoken::jwk::JwkSet, + kid: &str, + config: &ZitadelAuthConfig, +) -> Option> { + let jwk = if kid.is_empty() { + set.keys.first()? + } else { + set.keys + .iter() + .find(|k| k.common.key_id.as_deref() == Some(kid))? + }; + Some(verify_with_jwk(token, jwk, config)) +} + +fn verify_with_jwk( + token: &str, + jwk: &jsonwebtoken::jwk::Jwk, + config: &ZitadelAuthConfig, +) -> Result { + use jsonwebtoken::jwk::AlgorithmParameters; + use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; + + let decoding_key = + DecodingKey::from_jwk(jwk).map_err(|e| anyhow::anyhow!("invalid JWK: {e}"))?; + + // Algorithm is determined from the JWK (server-controlled), not the token header, + // to avoid algorithm-confusion attacks. + let alg = match &jwk.algorithm { + AlgorithmParameters::RSA(_) => Algorithm::RS256, + AlgorithmParameters::EllipticCurve(ec) => { + use jsonwebtoken::jwk::EllipticCurve; + match ec.curve { + EllipticCurve::P256 => Algorithm::ES256, + EllipticCurve::P384 => Algorithm::ES384, + ref c => anyhow::bail!("unsupported elliptic curve: {c:?}"), + } + } + other => anyhow::bail!("unsupported JWK key type: {other:?}"), + }; + + let mut validation = Validation::new(alg); + validation.set_audience(&config.trusted_audiences); + validation.set_issuer(&[&config.zitadel_base]); + + #[derive(Deserialize)] + struct Claims { + sub: String, + exp: i64, + email: Option, + name: Option, + nonce: Option, + } + + let claims = decode::(token, &decoding_key, &validation) + .map_err(|e| anyhow::anyhow!("JWT verification failed: {e}"))? + .claims; + + Ok(VerifiedSession { + subject: claims.sub, + email: claims.email, + name: claims.name, + expires_at: claims.exp, + nonce: claims.nonce, + }) +} + +async fn discover_jwks_uri(issuer_url: &str, http: &reqwest::Client) -> Result { + let url = format!( + "{}/.well-known/openid-configuration", + issuer_url.trim_end_matches('/') + ); + #[derive(Deserialize)] + struct Discovery { + jwks_uri: String, + } + let disc: Discovery = http + .get(&url) + .send() + .await? + .error_for_status()? + .json() + .await?; + Ok(disc.jwks_uri) +} + +async fn fetch_jwks(jwks_uri: &str, http: &reqwest::Client) -> Result { + Ok(http + .get(jwks_uri) + .send() + .await? + .error_for_status()? + .json::() + .await?) +} diff --git a/harmony_zitadel_auth/src/lib.rs b/harmony_zitadel_auth/src/lib.rs new file mode 100644 index 00000000..f5cd0e78 --- /dev/null +++ b/harmony_zitadel_auth/src/lib.rs @@ -0,0 +1,23 @@ +#[cfg(feature = "axum")] +pub mod axum_login_flow; +pub mod config; +pub mod jwks; +pub mod login; +pub mod session; + +#[cfg(feature = "axum")] +pub use config::cookie_key_from_env; +pub use config::{ + BASE_URL_ENV, CLIENT_ID_ENV, COOKIE_KEY_ENV, LOGOUT_REDIRECT_URI_ENV, SCOPE_ENV, + TRUSTED_AUDIENCES_ENV, ZITADEL_BASE_ENV, ZitadelAuthConfig, config_from_env, +}; + +pub use jwks::JwksCache; + +pub use login::{ + AuthCallbackQuery, LoginAttempt, RawAuthCallbackQuery, TokenResponse, ValidatedUser, + build_login_attempt, build_logout_url, exchange_code_for_token, jwt_exp, + validate_callback_state, validate_id_token, +}; + +pub use session::{LoginAttemptCookie, VerifiedSession}; diff --git a/harmony_zitadel_auth/src/login.rs b/harmony_zitadel_auth/src/login.rs new file mode 100644 index 00000000..6c744fee --- /dev/null +++ b/harmony_zitadel_auth/src/login.rs @@ -0,0 +1,228 @@ +use std::str::FromStr; + +use anyhow::Result; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use openidconnect::Nonce; +use openidconnect::core::{CoreClient, CoreIdToken, CoreProviderMetadata}; +use openidconnect::{ClientId, IssuerUrl}; +use rand::random; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use url::Url; + +use crate::config::ZitadelAuthConfig; +use crate::session::LoginAttemptCookie; + +#[derive(Debug, Clone)] +pub struct ValidatedUser { + pub subject: String, + pub email: Option, + pub name: Option, +} + +#[derive(Debug, Clone)] +pub struct LoginAttempt { + pub authorize_url: String, + pub state: String, + pub pkce_code_verifier: String, + pub nonce: String, +} + +#[derive(Debug, Deserialize)] +pub struct TokenResponse { + pub access_token: String, + pub id_token: String, + pub token_type: String, + pub expires_in: Option, +} + +#[derive(Debug, Deserialize)] +pub struct RawAuthCallbackQuery { + pub code: Option, + pub state: Option, + pub error: Option, + pub error_description: Option, +} + +#[derive(Debug)] +pub enum AuthCallbackQuery { + Success { + code: String, + state: String, + }, + Failure { + error: String, + error_description: Option, + }, +} + +impl From<&LoginAttempt> for LoginAttemptCookie { + fn from(attempt: &LoginAttempt) -> Self { + Self { + state: attempt.state.clone(), + pkce_code_verifier: attempt.pkce_code_verifier.clone(), + nonce: attempt.nonce.clone(), + } + } +} + +impl TryFrom for AuthCallbackQuery { + type Error = anyhow::Error; + + fn try_from(raw: RawAuthCallbackQuery) -> Result { + match raw { + RawAuthCallbackQuery { + code: Some(code), + state: Some(state), + error: None, + error_description: None, + } => Ok(Self::Success { code, state }), + RawAuthCallbackQuery { + code: None, + state: _, + error: Some(error), + error_description, + } => Ok(Self::Failure { + error, + error_description, + }), + _ => Err(anyhow::anyhow!("invalid auth callback query shape")), + } + } +} + +/// Full OIDC-compliant id_token validation. Used once per login callback; not +/// the per-request hot path (use `JwksCache::verify` for that). +pub async fn validate_id_token( + id_token: &str, + http_client: &reqwest::Client, + config: &ZitadelAuthConfig, +) -> Result { + let provider_metadata = + CoreProviderMetadata::discover_async(IssuerUrl::new(config.issuer_url())?, http_client) + .await?; + + let client = CoreClient::from_provider_metadata( + provider_metadata, + ClientId::new(config.client_id.clone()), + None, + ); + + let id_token = CoreIdToken::from_str(id_token)?; + let trusted_audiences = config.trusted_audiences.clone(); + let verifier = client + .id_token_verifier() + .set_other_audience_verifier_fn(move |aud| trusted_audiences.contains(&aud.to_string())); + let claims = id_token.claims(&verifier, |_: Option<&Nonce>| Ok(()))?; + + Ok(ValidatedUser { + subject: claims.subject().to_string(), + email: claims.email().map(|e| e.to_string()), + name: claims + .name() + .and_then(|l| l.get(None)) + .map(|n| n.to_string()), + }) +} + +pub fn build_logout_url(config: &ZitadelAuthConfig, id_token: &str) -> Result { + let mut url = Url::parse(&config.logout_url())?; + url.query_pairs_mut() + .append_pair("post_logout_redirect_uri", &config.logout_redirect_uri()) + .append_pair("id_token_hint", id_token); + Ok(url) +} + +pub fn build_login_attempt(config: &ZitadelAuthConfig) -> Result { + let state = random_url_token(32); + let pkce_code_verifier = random_url_token(32); + let nonce = random_url_token(32); + let code_challenge = pkce_s256_challenge(&pkce_code_verifier); + + let mut url = Url::parse(&config.authorize_url())?; + url.query_pairs_mut() + .append_pair("client_id", &config.client_id) + .append_pair("redirect_uri", &config.redirect_uri()) + .append_pair("response_type", "code") + .append_pair("scope", &config.scope) + .append_pair("code_challenge", &code_challenge) + .append_pair("code_challenge_method", "S256") + .append_pair("state", &state) + .append_pair("nonce", &nonce); + + Ok(LoginAttempt { + authorize_url: url.into(), + state, + pkce_code_verifier, + nonce, + }) +} + +pub async fn exchange_code_for_token( + client: &reqwest::Client, + config: &ZitadelAuthConfig, + pkce_code_verifier: &str, + code: &str, +) -> Result { + let response = client + .post(&config.token_url()) + .form(&[ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", &config.redirect_uri()), + ("client_id", &config.client_id), + ("code_verifier", pkce_code_verifier), + ]) + .send() + .await?; + + if !response.status().is_success() { + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + anyhow::bail!("failed to exchange code for token: {status} {body}"); + } + + Ok(response.json::().await?) +} + +pub fn validate_callback_state(attempt: &LoginAttemptCookie, returned_state: &str) -> Result<()> { + if attempt.state != returned_state { + anyhow::bail!("auth callback state mismatch; start again at /login"); + } + Ok(()) +} + +/// Decode the JWT payload (without verification) to extract `exp` for cookie `Max-Age`. +pub fn jwt_exp(token: &str) -> Option { + let payload = token.split('.').nth(1)?; + let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?; + let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + value.get("exp")?.as_i64() +} + +fn pkce_s256_challenge(code_verifier: &str) -> String { + let digest = Sha256::digest(code_verifier.as_bytes()); + URL_SAFE_NO_PAD.encode(digest) +} + +fn random_url_token(byte_len: usize) -> String { + let mut bytes = vec![0u8; byte_len]; + for chunk in bytes.chunks_mut(32) { + let random_bytes: [u8; 32] = random(); + chunk.copy_from_slice(&random_bytes[..chunk.len()]); + } + URL_SAFE_NO_PAD.encode(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pkce_s256_challenge_test() { + let code_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + let challenge = pkce_s256_challenge(code_verifier); + assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); + } +} diff --git a/harmony_zitadel_auth/src/session.rs b/harmony_zitadel_auth/src/session.rs new file mode 100644 index 00000000..8e5f73c3 --- /dev/null +++ b/harmony_zitadel_auth/src/session.rs @@ -0,0 +1,21 @@ +use serde::{Deserialize, Serialize}; + +/// Claims extracted from a verified session cookie JWT on each request. +#[derive(Debug, Clone)] +pub struct VerifiedSession { + pub subject: String, + pub email: Option, + pub name: Option, + pub expires_at: i64, + /// OIDC nonce from the ID token, used to bind callback tokens to login attempts. + pub nonce: Option, +} + +/// PKCE state persisted in the encrypted login-attempt cookie during the +/// Zitadel redirect dance. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoginAttemptCookie { + pub state: String, + pub pkce_code_verifier: String, + pub nonce: String, +} -- 2.39.5