all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks
Date: Sun, 15 Nov 2026 20:40:37 +0100	[thread overview]
Message-ID: <20261115194043.3947825-17-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261115194043.3947825-1-t.lamprecht@proxmox.com>

Counterpart of the datacenter-wide token-policy option introduced
for PVE with #7805, so that products building on this crate can
centrally require expiration dates for API tokens, limit the maximum
token lifetime, and forbid extending the expiration date of existing
tokens. Compliance rules like PCI DSS, SOC 2, or ISO 27001 often
require such limits.

Products opt in by overriding the new AccessControlConfig method to
return the policy from their configuration; by default, no policy is
enforced. Existing tokens are not re-validated, and an update only
gets checked if it changes the expiration date, so opting into a
policy neither invalidates deployed tokens nor blocks unrelated edits
of them. Only the expiry settings are ported: tokens in this stack
always use separate ACLs, so PVE's privilege separation setting only
matters once PVE moves over to this implementation.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---

changes since v1:
- adapt to 'disallow-expiry-extension'
- split the check into one for new tokens and one for updates, letting
  an unchanged date pass
- use u64 for the maximum lifetime
- document that token_policy() is called with the user config locked

 proxmox-access-control/src/init.rs  |  14 ++
 proxmox-access-control/src/types.rs | 215 ++++++++++++++++++++++++++++
 2 files changed, 229 insertions(+)

diff --git a/proxmox-access-control/src/init.rs b/proxmox-access-control/src/init.rs
index 52c3393a..c453c55f 100644
--- a/proxmox-access-control/src/init.rs
+++ b/proxmox-access-control/src/init.rs
@@ -6,6 +6,8 @@ use anyhow::{Error, format_err};
 use proxmox_auth_api::types::{Authid, Userid};
 use proxmox_section_config::SectionConfigData;
 
+use crate::types::TokenPolicy;
+
 static ACCESS_CONF: OnceLock<&'static dyn AccessControlConfig> = OnceLock::new();
 
 /// This trait specifies the functions a product needs to implement to get ACL tree based access
@@ -101,6 +103,18 @@ pub trait AccessControlConfig: Send + Sync {
     fn allow_partial_permission_match(&self) -> bool {
         true
     }
+
+    /// Returns the token policy to enforce when API tokens are created or updated, if any.
+    ///
+    /// Override this to return the policy from the product's configuration. Return an error if that
+    /// configuration cannot be loaded, so token creation and expiration date updates fail instead
+    /// of silently proceeding without the policy. The token API calls this while holding the user
+    /// configuration lock, so implementations must not acquire that lock.
+    ///
+    /// Default: Returns `Ok(None)`, no policy is enforced.
+    fn token_policy(&self) -> Result<Option<TokenPolicy>, Error> {
+        Ok(None)
+    }
 }
 
 pub fn init_access_config(config: &'static dyn AccessControlConfig) -> Result<(), Error> {
diff --git a/proxmox-access-control/src/types.rs b/proxmox-access-control/src/types.rs
index 875b3d93..ce117376 100644
--- a/proxmox-access-control/src/types.rs
+++ b/proxmox-access-control/src/types.rs
@@ -1,3 +1,4 @@
+use anyhow::{Error, bail};
 use serde::{Deserialize, Serialize};
 
 use const_format::concatcp;
@@ -174,6 +175,95 @@ pub struct TokenApiEntry {
     pub token: ApiToken,
 }
 
+#[api(
+    properties: {
+        "require-expiry": {
+            optional: true,
+            default: false,
+        },
+        "max-lifetime": {
+            optional: true,
+            minimum: 1,
+        },
+        "disallow-expiry-extension": {
+            optional: true,
+            default: false,
+        },
+    },
+)]
+#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize, Updater)]
+#[serde(rename_all = "kebab-case")]
+/// Policy for the creation and update of API tokens.
+///
+/// Only token creation and updates are checked against the policy. Existing tokens stay valid, so
+/// enabling a policy does not invalidate already deployed tokens.
+pub struct TokenPolicy {
+    /// Require an expiration date for new API tokens and when changing the expiration date of
+    /// existing ones.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub require_expiry: Option<bool>,
+
+    /// Maximum lifetime of API tokens in seconds, counted from when the expiration date is set,
+    /// that is on creation or when an update changes it. Implies `require-expiry`.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub max_lifetime: Option<u64>,
+
+    /// Disallow moving the expiration date of existing API tokens later or removing it, so that
+    /// `max-lifetime` cannot be circumvented by extending tokens repeatedly. Shortening it, or
+    /// setting one for a token without, stays possible, and tokens can still be deleted and
+    /// recreated.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub disallow_expiry_extension: Option<bool>,
+}
+
+impl TokenPolicy {
+    /// Check the expiration date of a new token against the policy, 0 meaning none.
+    pub fn check_new_expiry(&self, expire: i64, now: i64) -> Result<(), Error> {
+        self.check_expiry_bounds(expire, now)
+    }
+
+    /// Check an update of the expiration date of an existing token against the policy.
+    ///
+    /// `expire` is the submitted and `current` the stored expiration date, 0 meaning none for both.
+    /// An unchanged date always passes, so updates of tokens that predate the policy keep working.
+    pub fn check_expiry_update(&self, expire: i64, current: i64, now: i64) -> Result<(), Error> {
+        if expire == current {
+            return Ok(());
+        }
+
+        // removing the expiration date or moving it later extends the token
+        if self.disallow_expiry_extension.unwrap_or_default()
+            && current != 0
+            && (expire == 0 || expire > current)
+        {
+            bail!(
+                "the token policy does not allow extending the expiration date of an existing token"
+            );
+        }
+
+        self.check_expiry_bounds(expire, now)
+    }
+
+    fn check_expiry_bounds(&self, expire: i64, now: i64) -> Result<(), Error> {
+        // a token that never expires exceeds any maximum lifetime
+        if expire == 0 && (self.require_expiry.unwrap_or_default() || self.max_lifetime.is_some()) {
+            bail!("the token policy requires an expiration date");
+        }
+
+        if let Some(max_lifetime) = self.max_lifetime {
+            // saturate, as an extreme configured lifetime would overflow
+            if expire > now.saturating_add_unsigned(max_lifetime) {
+                bail!(
+                    "the expiration date exceeds the maximum token lifetime of {max_lifetime} \
+                     seconds set by the token policy"
+                );
+            }
+        }
+
+        Ok(())
+    }
+}
+
 #[api(
     properties: {
         userid: {
@@ -316,3 +406,128 @@ pub const REGENERATE_TOKEN_SCHEMA: Schema =
     BooleanSchema::new("Regenerate token secret while keeping permissions.")
         .default(false)
         .schema();
+
+#[cfg(test)]
+mod tests {
+    use super::TokenPolicy;
+
+    // fixed reference time and a 90 day maximum lifetime for deterministic bounds checks
+    const NOW: i64 = 1_000_000_000;
+    const MAX: i64 = 90 * 24 * 60 * 60;
+
+    // the expiration date of the existing token in the update cases
+    const CURRENT: i64 = NOW + 100;
+
+    const EMPTY: TokenPolicy = TokenPolicy {
+        require_expiry: None,
+        max_lifetime: None,
+        disallow_expiry_extension: None,
+    };
+
+    const REQUIRE_EXPIRY: TokenPolicy = TokenPolicy {
+        require_expiry: Some(true),
+        ..EMPTY
+    };
+
+    const MAX_LIFETIME: TokenPolicy = TokenPolicy {
+        max_lifetime: Some(MAX as u64),
+        ..EMPTY
+    };
+
+    const NO_EXTENSION: TokenPolicy = TokenPolicy {
+        disallow_expiry_extension: Some(true),
+        ..EMPTY
+    };
+
+    fn create_ok(policy: &TokenPolicy, expire: i64) -> bool {
+        policy.check_new_expiry(expire, NOW).is_ok()
+    }
+
+    fn update_ok(policy: &TokenPolicy, expire: i64, current: i64) -> bool {
+        policy.check_expiry_update(expire, current, NOW).is_ok()
+    }
+
+    #[test]
+    fn empty_policy_allows_everything() {
+        assert!(create_ok(&EMPTY, 0));
+        assert!(create_ok(&EMPTY, NOW + 100));
+        assert!(update_ok(&EMPTY, 0, CURRENT));
+    }
+
+    #[test]
+    fn require_expiry() {
+        assert!(!create_ok(&REQUIRE_EXPIRY, 0));
+        assert!(create_ok(&REQUIRE_EXPIRY, NOW + 100));
+        assert!(!update_ok(&REQUIRE_EXPIRY, 0, CURRENT));
+        assert!(update_ok(&REQUIRE_EXPIRY, NOW + 200, CURRENT));
+    }
+
+    #[test]
+    fn max_lifetime_implies_require_expiry() {
+        assert!(!create_ok(&MAX_LIFETIME, 0));
+        let explicitly_not_required = TokenPolicy {
+            require_expiry: Some(false),
+            ..MAX_LIFETIME
+        };
+        assert!(!create_ok(&explicitly_not_required, 0));
+    }
+
+    #[test]
+    fn max_lifetime_bounds() {
+        assert!(create_ok(&MAX_LIFETIME, NOW + 100));
+        assert!(create_ok(&MAX_LIFETIME, NOW + MAX));
+        assert!(!create_ok(&MAX_LIFETIME, NOW + MAX + 1));
+        // an expiration date in the past is odd, but within any bound
+        assert!(create_ok(&MAX_LIFETIME, NOW - 100));
+        assert!(update_ok(&MAX_LIFETIME, NOW + 200, CURRENT));
+        assert!(!update_ok(&MAX_LIFETIME, NOW + MAX + 1, CURRENT));
+    }
+
+    #[test]
+    fn extreme_max_lifetime_does_not_overflow() {
+        let policy = TokenPolicy {
+            max_lifetime: Some(u64::MAX),
+            ..EMPTY
+        };
+        assert!(create_ok(&policy, NOW + 100));
+        assert!(create_ok(&policy, i64::MAX));
+    }
+
+    #[test]
+    fn unchanged_expiry_passes() {
+        assert!(update_ok(&REQUIRE_EXPIRY, 0, 0));
+        assert!(update_ok(&MAX_LIFETIME, NOW + MAX + 1, NOW + MAX + 1));
+    }
+
+    #[test]
+    fn disallow_expiry_extension() {
+        // moving the expiration date later or removing it is rejected
+        assert!(!update_ok(&NO_EXTENSION, CURRENT + 1, CURRENT));
+        assert!(!update_ok(&NO_EXTENSION, 0, CURRENT));
+        // shortening it, even into the past, stays allowed
+        assert!(update_ok(&NO_EXTENSION, CURRENT - 1, CURRENT));
+        assert!(update_ok(&NO_EXTENSION, NOW - 100, CURRENT));
+        // as does setting one on a token without any
+        assert!(update_ok(&NO_EXTENSION, NOW + 100, 0));
+        // creation is unaffected
+        assert!(create_ok(&NO_EXTENSION, NOW + 100));
+        assert!(create_ok(&NO_EXTENSION, 0));
+    }
+
+    #[test]
+    fn disallow_expiry_extension_combined() {
+        let policy = TokenPolicy {
+            require_expiry: Some(true),
+            ..NO_EXTENSION
+        };
+        // a compliant new date still gets rejected as an extension
+        assert!(!update_ok(&policy, NOW + 200, CURRENT));
+        assert!(create_ok(&policy, NOW + 200));
+        // shortening under a maximum lifetime stays allowed as well
+        let policy = TokenPolicy {
+            max_lifetime: Some(MAX as u64),
+            ..NO_EXTENSION
+        };
+        assert!(update_ok(&policy, CURRENT - 1, CURRENT));
+    }
+}
-- 
2.47.3





  parent reply	other threads:[~2026-11-15 19:43 UTC|newest]

Thread overview: 26+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 2/19] datacenter config: token policy: add default-to-max-lifetime setting Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 3/19] datacenter config: token policy: allow extension on regeneration Thomas Lamprecht
2026-11-17 13:30   ` Shannon Sterz
2026-11-15 19:40 ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
2026-11-17 13:30   ` Shannon Sterz
2026-11-15 19:40 ` [PATCH v2 access-control 5/19] api: token: apply the default lifetime from the " Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 access-control 6/19] api: token: allow extending tokens on secret regeneration Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 docs 7/19] user management: document the API token policy Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 docs 8/19] user management: document the default-to-max-lifetime setting Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 docs 9/19] user management: document extending tokens on secret regeneration Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 10/19] ui: token edit: only submit the expiration date when changed Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 11/19] api: cluster options: return token-policy without Sys.Audit Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 12/19] ui: dc options: allow editing the API token policy Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 13/19] ui: token edit: adapt to the datacenter " Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 14/19] ui: token policy: expose the default-to-max-lifetime setting Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 15/19] ui: token policy: allow extension on secret regeneration Thomas Lamprecht
2026-11-15 19:40 ` Thomas Lamprecht [this message]
2026-11-17 13:29   ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Shannon Sterz
2026-11-15 19:40 ` [PATCH v2 proxmox 17/19] access-control: enforce token policy on token create and update Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 proxmox 18/19] access-control: apply a default token lifetime from the policy Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 proxmox 19/19] access-control: allow extending tokens on secret regeneration Thomas Lamprecht
2026-11-17 13:29   ` Shannon Sterz
2026-11-17 13:29 ` [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Shannon Sterz
2026-11-18  2:17 ` applied: " Thomas Lamprecht

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=20261115194043.3947825-17-t.lamprecht@proxmox.com \
    --to=t.lamprecht@proxmox.com \
    --cc=pve-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