all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Christoph Heiss <c.heiss@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [PATCH installer v2 09/16] post-hook: support creating API token if requested in answer file
Date: Wed, 26 Aug 2026 13:04:52 +0200	[thread overview]
Message-ID: <20260826110504.1339934-10-c.heiss@proxmox.com> (raw)
In-Reply-To: <20260826110504.1339934-1-c.heiss@proxmox.com>

If `global.post-installation-webhook.api-token` is set and we're
installing either PVE or PBS, create a new API token with the given
name, and include it in the info sent back.

Signed-off-by: Christoph Heiss <c.heiss@proxmox.com>
---
Depends on the `proxmox-installer-types` changes and an accompanying
dependency bump.

Changes v1 -> v2:
  * document create_api_token()
  * use Result::inspect_err() for simplifying error handling

 Cargo.toml                    |   4 +-
 debian/control                |   1 +
 proxmox-post-hook/Cargo.toml  |   3 +-
 proxmox-post-hook/src/main.rs | 125 +++++++++++++++++++++++++++++++++-
 4 files changed, 128 insertions(+), 5 deletions(-)

diff --git a/Cargo.toml b/Cargo.toml
index a134ffb..55d2192 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -28,12 +28,14 @@ serde_plain = "1.0"
 sha2 = "0.10"
 toml = "0.8"
 proxmox-auto-installer.path = "./proxmox-auto-installer"
-proxmox-installer-common.path = "./proxmox-installer-common"
 proxmox-network-types = "1.1"
+proxmox-installer-common.path = "./proxmox-installer-common"
 proxmox-installer-types = { version = "0.1.1", features = ["legacy"] }
+proxmox-time = "2.1"
 
 # Local path overrides
 # NOTE: You must run `cargo update` after changing this for it to take effect!
 [patch.crates-io]
 # proxmox-network-types.path = "../proxmox/proxmox-network-types"
 # proxmox-installer-types.path = "../proxmox/proxmox-installer-types"
+# proxmox-time.path = "../proxmox/proxmox-time"
diff --git a/debian/control b/debian/control
index 7565c2a..cc1f278 100644
--- a/debian/control
+++ b/debian/control
@@ -22,6 +22,7 @@ Build-Depends: cargo:native,
                librust-proxmox-installer-types-0.1+legacy-dev (>= 0.1.1-~~),
                librust-proxmox-network-types-1-dev (>= 1.1-~~),
                librust-proxmox-sys+crypt-dev,
+               librust-proxmox-time-dev,
                librust-regex-1+default-dev (>= 1.7~~),
                librust-rustls-0.23-dev,
                librust-rustls-native-certs-dev,
diff --git a/proxmox-post-hook/Cargo.toml b/proxmox-post-hook/Cargo.toml
index b6d9ce5..82a23c4 100644
--- a/proxmox-post-hook/Cargo.toml
+++ b/proxmox-post-hook/Cargo.toml
@@ -13,8 +13,9 @@ homepage = "https://www.proxmox.com"
 [dependencies]
 anyhow.workspace = true
 proxmox-installer-common = { workspace = true, features = ["http"] }
-proxmox-network-types.workspace = true
 proxmox-installer-types.workspace = true
+proxmox-network-types.workspace = true
+proxmox-time.workspace = true
 rustls.workspace = true
 serde = { workspace = true, features = ["derive"] }
 serde_json.workspace = true
diff --git a/proxmox-post-hook/src/main.rs b/proxmox-post-hook/src/main.rs
index e4f1fec..6455838 100644
--- a/proxmox-post-hook/src/main.rs
+++ b/proxmox-post-hook/src/main.rs
@@ -49,8 +49,8 @@ mod detail {
             AutoInstallerConfig, FqdnConfig, FqdnFromDhcpConfig, FqdnSourceMode, SchemaVersion,
         },
         post_hook::{
-            BootInfo, CpuInfo, DiskInfo, KernelVersionInformation, NetworkInterfaceInfo,
-            PostHookInfo, PostHookInfoSchema, ProductInfo, SchemaVersion, SshPublicHostKeys,
+            BootInfo, CpuInfo, CreatedApiToken, DiskInfo, KernelVersionInformation,
+            NetworkInterfaceInfo, PostHookInfo, PostHookInfoSchema, ProductInfo, SshPublicHostKeys,
         },
     };
 
@@ -140,6 +140,20 @@ mod detail {
             None
         };
 
+        let api_token = if let Some(name) = answer
+            .post_installation_webhook
+            .as_ref()
+            .and_then(|p| p.api_token_name.as_ref())
+            && schema_1_3_supported
+            && setup_info.config.product.supports_api_token_creation()
+        {
+            create_api_token(name, target_path, setup_info.config.product, &run_cmd)
+                .inspect_err(|err| eprintln!("could not create API token: {err:#}"))
+                .ok()
+        } else {
+            None
+        };
+
         Ok(PostHookInfo {
             schema: PostHookInfoSchema {
                 version: super::POST_HOOK_SCHEMA_VERSION.to_owned(),
@@ -212,7 +226,7 @@ mod detail {
             },
             reboot_mode: answer.global.reboot_mode,
             cert_fingerprint,
-            api_token: None,
+            api_token,
         })
     }
 
@@ -633,6 +647,111 @@ mod detail {
         }
     }
 
+    /// Creates a new, fully privileged API token with the given `name` for the target system.
+    ///
+    /// The token is set to never expire, and the comment will include that it was created during
+    /// installation, as well as the creation time.
+    ///
+    /// # Returns
+    ///
+    /// The ID and secret of the created API token.
+    pub fn create_api_token(
+        name: &str,
+        target_path: &str,
+        product: ProxmoxProduct,
+        run_cmd: &dyn Fn(&[&str]) -> Result<String>,
+    ) -> Result<CreatedApiToken> {
+        const USER: &str = "root@pam";
+        let date = proxmox_time::epoch_to_rfc2822(proxmox_time::epoch_i64())?;
+        let comment = format!("auto-generated during installation on {date}");
+
+        println!("Creating API token '{name}' for '{USER}' ..");
+        match product {
+            ProxmoxProduct::Pve => with_pmxcfs(target_path, |_| {
+                run_cmd(&[
+                    "pveum",
+                    "user",
+                    "token",
+                    "add",
+                    USER,
+                    name,
+                    "-privsep=0",
+                    "-expire=0",
+                    "-comment",
+                    &comment,
+                    "-output-format=json",
+                ])
+                .map_err(|err| anyhow!(err))
+                .and_then(|s| {
+                    serde_json::from_str::<serde_json::Value>(&s).map_err(|err| anyhow!(err))
+                })
+                .and_then(|v| {
+                    Ok(CreatedApiToken {
+                        id: v["full-tokenid"]
+                            .as_str()
+                            .ok_or_else(|| anyhow!("expected string for tokenid"))?
+                            .parse()?,
+                        secret: v["value"]
+                            .as_str()
+                            .ok_or_else(|| anyhow!("expected string for secret"))?
+                            .to_owned(),
+                    })
+                })
+                .context("generating API token")
+            }),
+            ProxmoxProduct::Pbs => {
+                let token = run_cmd(&[
+                    "proxmox-backup-manager",
+                    "user",
+                    "generate-token",
+                    USER,
+                    name,
+                    "--comment",
+                    &comment,
+                    "--expire=0",
+                    // TODO: once `user generate-token` supports it, switch to `--output-format
+                    // json` and drop the rather ugly trim() hack below.
+                ])
+                .map_err(|err| anyhow!(err))
+                .and_then(|s| {
+                    serde_json::from_str::<serde_json::Value>(
+                        s.trim_start_matches("Result:").trim(),
+                    )
+                    .map_err(|err| anyhow!(err))
+                })
+                .and_then(|v| {
+                    Ok(CreatedApiToken {
+                        id: v["tokenid"]
+                            .as_str()
+                            .ok_or_else(|| anyhow!("expected string for tokenid"))?
+                            .parse()?,
+                        secret: v["value"]
+                            .as_str()
+                            .ok_or_else(|| anyhow!("expected string for secret"))?
+                            .to_owned(),
+                    })
+                })
+                .context("generating API token")?;
+
+                // Give the token full privileges - same as the PDM wizard
+                run_cmd(&[
+                    "proxmox-backup-manager",
+                    "acl",
+                    "update",
+                    "/",
+                    "Admin",
+                    "--auth-id",
+                    &token.id.to_string(),
+                    "--propagate=true",
+                ])
+                .context("setting up API token ACL")?;
+
+                Ok(token)
+            }
+            _ => bail!("cannot create API token for {}", product.full_name()),
+        }
+    }
+
     fn is_path_a_mountpoint(path: impl AsRef<Path>) -> Result<bool> {
         let path = path.as_ref();
 
-- 
2.55.0





  parent reply	other threads:[~2026-08-26 11:06 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-08-26 11:04 [PATCH datacenter-manager/installer/proxmox v2 00/16] auto-installer: add installed target systems as new remotes Christoph Heiss
2026-08-26 11:04 ` [PATCH proxmox v2 01/16] installer-types: drop unnecessary clippy attribute Christoph Heiss
2026-08-26 11:04 ` [PATCH proxmox v2 02/16] installer-types: post-hook: factor schema version into proper struct Christoph Heiss
2026-08-26 11:04 ` [PATCH proxmox v2 03/16] installer-types: post-hook: allow additional properties on api schema Christoph Heiss
2026-08-26 11:04 ` [PATCH proxmox v2 04/16] installer-types: post-hook: add api-token and cert-fingerprint options Christoph Heiss
2026-08-26 11:04 ` [PATCH proxmox v2 05/16] installer-types: systeminfo: add check for API token creation capability Christoph Heiss
2026-08-26 11:04 ` [PATCH installer v2 06/16] chroot: print full error if bind-mounting fails Christoph Heiss
2026-08-26 11:04 ` [PATCH installer v2 07/16] post-hook: re-use low-level config retrieval from proxmox-chroot Christoph Heiss
2026-08-26 11:04 ` [PATCH installer v2 08/16] post-hook: generate and retrieve node certificate fingerprint Christoph Heiss
2026-08-26 11:04 ` Christoph Heiss [this message]
2026-08-26 11:04 ` [PATCH installer v2 10/16] auto: enforce https for post hook when generating an API token Christoph Heiss
2026-08-26 11:04 ` [PATCH installer v2 11/16] assistant: validate-answer: also verify post-hook settings if set Christoph Heiss
2026-08-26 11:04 ` [PATCH datacenter-manager v2 12/16] ui: auto-installer: spell out Proxmox Datacenter Manager Christoph Heiss
2026-08-26 11:04 ` [PATCH datacenter-manager v2 13/16] config: auto-install: add optional `post-hook-add-as-remote` field Christoph Heiss
2026-08-26 11:04 ` [PATCH datacenter-manager v2 14/16] api: auto-installer: add option for adding new remotes to PDM Christoph Heiss
2026-08-26 11:04 ` [PATCH datacenter-manager v2 15/16] ui: auto-installer: wizard: add checkbox to add target as new remote Christoph Heiss
2026-08-26 11:04 ` [PATCH datacenter-manager v2 16/16] docs: auto-installer: document adding targets as remotes afterwards Christoph Heiss

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260826110504.1339934-10-c.heiss@proxmox.com \
    --to=c.heiss@proxmox.com \
    --cc=pdm-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal