From mboxrd@z Thu Jan  1 00:00:00 1970
Return-Path: <pdm-devel-bounces@lists.proxmox.com>
Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68])
	by lore.proxmox.com (Postfix) with ESMTPS id 858141FF15C
	for <inbox@lore.proxmox.com>; Fri, 16 May 2025 15:36:02 +0200 (CEST)
Received: from firstgate.proxmox.com (localhost [127.0.0.1])
	by firstgate.proxmox.com (Proxmox) with ESMTP id EC30ED9F0;
	Fri, 16 May 2025 15:36:21 +0200 (CEST)
From: Dominik Csapak <d.csapak@proxmox.com>
To: pdm-devel@lists.proxmox.com
Date: Fri, 16 May 2025 15:36:02 +0200
Message-Id: <20250516133611.3499075-13-d.csapak@proxmox.com>
X-Mailer: git-send-email 2.39.5
In-Reply-To: <20250516133611.3499075-1-d.csapak@proxmox.com>
References: <20250516133611.3499075-1-d.csapak@proxmox.com>
MIME-Version: 1.0
X-SPAM-LEVEL: Spam detection results:  0
 AWL 0.022 Adjusted score from AWL reputation of From: address
 BAYES_00                 -1.9 Bayes spam probability is 0 to 1%
 DMARC_MISSING             0.1 Missing DMARC policy
 KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment
 SPF_HELO_NONE           0.001 SPF: HELO does not publish an SPF Record
 SPF_PASS               -0.001 SPF: sender matches SPF record
Subject: [pdm-devel] [PATCH datacenter-manager 12/21] ui: pve wizard: nodes:
 probe hosts to verify fingerprint settings
X-BeenThere: pdm-devel@lists.proxmox.com
X-Mailman-Version: 2.1.29
Precedence: list
List-Id: Proxmox Datacenter Manager development discussion
 <pdm-devel.lists.proxmox.com>
List-Unsubscribe: <https://lists.proxmox.com/cgi-bin/mailman/options/pdm-devel>, 
 <mailto:pdm-devel-request@lists.proxmox.com?subject=unsubscribe>
List-Archive: <http://lists.proxmox.com/pipermail/pdm-devel/>
List-Post: <mailto:pdm-devel@lists.proxmox.com>
List-Help: <mailto:pdm-devel-request@lists.proxmox.com?subject=help>
List-Subscribe: <https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel>, 
 <mailto:pdm-devel-request@lists.proxmox.com?subject=subscribe>
Reply-To: Proxmox Datacenter Manager development discussion
 <pdm-devel@lists.proxmox.com>
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Errors-To: pdm-devel-bounces@lists.proxmox.com
Sender: "pdm-devel" <pdm-devel-bounces@lists.proxmox.com>

when advancing the wizard.

* check each host if the fingerprint is correct
* for hosts without fingerprint configured, will prompt the user to
  use the fingerprints if the certificates are not trusted

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
 ui/Cargo.toml                       |   1 +
 ui/src/remotes/wizard_page_nodes.rs | 239 ++++++++++++++++++++++++++--
 2 files changed, 229 insertions(+), 11 deletions(-)

diff --git a/ui/Cargo.toml b/ui/Cargo.toml
index cf50a32..3de092b 100644
--- a/ui/Cargo.toml
+++ b/ui/Cargo.toml
@@ -32,6 +32,7 @@ pwt-macros = "0.3"
 
 proxmox-yew-comp = { version = "0.4.5", features = ["apt", "dns", "network", "rrd"] }
 
+proxmox-acme-api = { version = "0.1", features = [] }
 proxmox-client = "0.5"
 proxmox-human-byte = "0.1.3"
 proxmox-login = "0.2"
diff --git a/ui/src/remotes/wizard_page_nodes.rs b/ui/src/remotes/wizard_page_nodes.rs
index ce73f6e..aa7eb94 100644
--- a/ui/src/remotes/wizard_page_nodes.rs
+++ b/ui/src/remotes/wizard_page_nodes.rs
@@ -1,15 +1,22 @@
+use std::collections::HashMap;
 use std::rc::Rc;
 
-use pdm_client::types::Remote;
-use pwt::css::FlexFit;
+use proxmox_schema::property_string::PropertyString;
+use serde_json::Value;
 use yew::virtual_dom::{VComp, VNode};
 
-use pwt::prelude::*;
-use pwt::widget::Container;
+use pwt::css::{FlexFit, FontStyle, JustifyContent, Overflow};
+use pwt::widget::{error_message, Button, Column, Container, Dialog, Mask, Row};
+use pwt::{prelude::*, AsyncAbortGuard};
+use pwt_macros::builder;
 
-use proxmox_yew_comp::WizardPageRenderInfo;
+use proxmox_yew_comp::{KVGrid, KVGridRow, WizardPageRenderInfo};
 
-use pwt_macros::builder;
+use pdm_api_types::{
+    remotes::{NodeUrl, ScanResult},
+    CertificateInfo,
+};
+use pdm_client::types::Remote;
 
 use super::NodeUrlList;
 
@@ -29,14 +36,193 @@ impl WizardPageNodes {
     }
 }
 
-pub struct PdmWizardPageNodes {}
+pub enum Msg {
+    Scan,
+    ScanResult(Vec<(String, Result<ScanResult, proxmox_client::Error>)>),
+    ConfirmResult(bool),
+}
+
+pub struct PdmWizardPageNodes {
+    scan_results: Vec<(String, Result<ScanResult, proxmox_client::Error>)>,
+    scan_guard: Option<AsyncAbortGuard>,
+    loading: bool,
+    certificate_rows: Rc<Vec<KVGridRow>>,
+}
+
+impl PdmWizardPageNodes {
+    fn create_certificate_confirmation_dialog(
+        &self,
+        ctx: &Context<Self>,
+        certificates: Vec<(&String, &CertificateInfo)>,
+    ) -> Dialog {
+        let link = ctx.link();
+        Dialog::new(tr!("Connection Certificate"))
+            .on_close(link.callback(|_| Msg::ConfirmResult(false)))
+            .with_child(
+                Column::new()
+                    .padding(2)
+                    .gap(2)
+                    .class(FlexFit)
+                    .with_child(Container::new().with_child(tr!(
+                        "The following certificates of remote servers are not trusted."
+                    )))
+                    .with_child(Container::new().with_child(tr!(
+                        "Do you want to trust them by saving their fingerprint?"
+                    )))
+                    .with_child(
+                        Column::new()
+                            .max_height(400)
+                            .gap(1)
+                            .padding(2)
+                            .class(Overflow::Auto)
+                            .children(certificates.into_iter().map(|(hostname, certificate)| {
+                                Column::new()
+                                    .with_child(
+                                        Container::new().class(FontStyle::TitleSmall).with_child(
+                                            format!("{}: {hostname}", tr!("Server Address")),
+                                        ),
+                                    )
+                                    .with_child(
+                                        KVGrid::new()
+                                            .class(FlexFit)
+                                            .borderless(true)
+                                            .striped(false)
+                                            .rows(self.certificate_rows.clone())
+                                            .data(Rc::new(
+                                                serde_json::to_value(certificate)
+                                                    .unwrap_or_default(),
+                                            )),
+                                    )
+                                    .into()
+                            })),
+                    )
+                    .with_child(
+                        Row::new()
+                            .gap(2)
+                            .class(JustifyContent::Center)
+                            .with_child(
+                                Button::new(tr!("Yes"))
+                                    .onclick(link.callback(|_| Msg::ConfirmResult(true))),
+                            )
+                            .with_child(
+                                Button::new(tr!("No"))
+                                    .onclick(link.callback(|_| Msg::ConfirmResult(false))),
+                            ),
+                    ),
+            )
+    }
+}
 
 impl Component for PdmWizardPageNodes {
-    type Message = ();
+    type Message = Msg;
     type Properties = WizardPageNodes;
 
     fn create(_ctx: &Context<Self>) -> Self {
-        Self {}
+        _ctx.props().info.on_next({
+            let link = _ctx.link().clone();
+            move |_| {
+                link.send_message(Msg::Scan);
+                false
+            }
+        });
+        Self {
+            scan_results: Vec::new(),
+            scan_guard: None,
+            loading: false,
+            certificate_rows: Rc::new(rows()),
+        }
+    }
+
+    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
+        let props = ctx.props();
+        match msg {
+            Msg::Scan => {
+                self.loading = true;
+                let link = ctx.link().clone();
+                let nodes = props.info.form_ctx.read().get_field_value("nodes");
+                let Some(Value::Array(nodes)) = nodes else {
+                    return true;
+                };
+                self.scan_guard = Some(AsyncAbortGuard::spawn(async move {
+                    let futures = nodes.into_iter().filter_map(|node| {
+                        let node = match serde_json::from_value::<PropertyString<NodeUrl>>(node) {
+                            Ok(node) => node.into_inner(),
+                            Err(_) => return None,
+                        };
+
+                        let future = async move {
+                            let res = crate::pdm_client()
+                                .pve_probe_tls(&node.hostname, node.fingerprint.as_deref())
+                                .await;
+                            (node.hostname, res)
+                        };
+                        Some(future)
+                    });
+
+                    let res = futures::future::join_all(futures).await;
+                    link.send_message(Msg::ScanResult(res));
+                }));
+            }
+            Msg::ScanResult(scan_results) => {
+                self.loading = false;
+                self.scan_results = scan_results;
+                let mut success = true;
+                for (_hostname, result) in &self.scan_results {
+                    match result {
+                        Ok(ScanResult::TlsResult(None)) => {}
+                        _ => success = false,
+                    }
+                }
+
+                if success {
+                    props.info.go_to_next_page();
+                }
+            }
+            Msg::ConfirmResult(confirm) => {
+                if confirm {
+                    // update connect information with gathered certificate information
+                    // and navigate to next page
+                    let mut map = HashMap::new();
+                    for (hostname, res) in self.scan_results.drain(..) {
+                        if let Ok(ScanResult::TlsResult(Some(cert))) = res {
+                            if let Some(fp) = cert.fingerprint {
+                                map.insert(hostname, fp);
+                            }
+                        }
+                    }
+
+                    let mut form = props.info.form_ctx.write();
+                    let value = form
+                        .get_field_value("nodes")
+                        .unwrap_or(Value::Array(Vec::new()));
+
+                    let value = match serde_json::from_value::<Vec<PropertyString<NodeUrl>>>(value)
+                    {
+                        Ok(mut nodes) => {
+                            for node in nodes.iter_mut() {
+                                if node.fingerprint.is_none() && map.contains_key(&node.hostname) {
+                                    node.fingerprint =
+                                        Some(map.get(&node.hostname).unwrap().to_uppercase());
+                                }
+                            }
+                            // this should never fail
+                            serde_json::to_value(nodes).unwrap()
+                        }
+                        Err(_) => {
+                            // data from field is wrong, this should not happen
+                            unreachable!("internal data in node field is wrong");
+                        }
+                    };
+
+                    form.set_field_value("nodes", value);
+                    drop(form);
+                    props.info.go_to_next_page();
+                } else {
+                    self.scan_results.clear();
+                }
+            }
+        }
+        true
     }
 
     fn view(&self, ctx: &Context<Self>) -> Html {
@@ -46,7 +232,25 @@ impl Component for PdmWizardPageNodes {
             .as_ref()
             .map(|info| info.nodes.clone())
             .unwrap_or_default();
-        Container::new()
+
+        let mut errors = Vec::new();
+        let mut certificates = Vec::new();
+
+        for (hostname, result) in &self.scan_results {
+            match result {
+                Ok(ScanResult::TlsResult(Some(cert))) => {
+                    certificates.push((hostname, cert));
+                }
+                Ok(_) => {}
+                Err(err) => {
+                    errors.push(error_message(&format!("{hostname} - {err}")).into());
+                }
+            }
+        }
+
+        let has_errors = !errors.is_empty();
+
+        let content = Container::new()
             .class(FlexFit)
             .padding(4)
             .with_child(Container::new().padding(4).with_child(tr!(
@@ -61,10 +265,23 @@ impl Component for PdmWizardPageNodes {
                     .key("nodes")
                     .required(true),
             )
-            .into()
+            .with_optional_child((has_errors).then_some(Column::new().children(errors)))
+            .with_optional_child(
+                (!has_errors && !certificates.is_empty())
+                    .then_some(self.create_certificate_confirmation_dialog(ctx, certificates)),
+            );
+        Mask::new(content).visible(self.loading).into()
     }
 }
 
+fn rows() -> Vec<KVGridRow> {
+    vec![
+        KVGridRow::new("fingerprint", tr!("Fingerprint")),
+        KVGridRow::new("issuer", tr!("Issuer")),
+        KVGridRow::new("subject", tr!("Subject")),
+    ]
+}
+
 impl Into<VNode> for WizardPageNodes {
     fn into(self) -> VNode {
         let comp = VComp::new::<PdmWizardPageNodes>(Rc::new(self), None);
-- 
2.39.5



_______________________________________________
pdm-devel mailing list
pdm-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel