public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
Search results ordered by [date|relevance]  view[summary|nested|Atom feed]
thread overview below | download mbox.gz: |
* applied: [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy
  2026-11-15 19:40 17% [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] " Thomas Lamprecht
                   ` (3 preceding siblings ...)
  2026-11-17 13:29  8% ` [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 17% ` Thomas Lamprecht
  4 siblings, 0 replies; 17+ results
From: Thomas Lamprecht @ 2026-11-18  2:17 UTC (permalink / raw)
  To: pve-devel, Thomas Lamprecht

On Sun, 15 Nov 2026 20:40:21 +0100, Thomas Lamprecht wrote:
> Compliance rules like PCI DSS, SOC 2, or ISO 27001 often require
> that credentials have a limited lifetime, but there is no central way
> to enforce that for API tokens.
> 
> Add an optional token-policy option to datacenter.cfg to require an
> expiration date, limit the maximum token lifetime, forbid extending
> the expiration date of existing tokens, and require privilege
> separation. Two further opt-in settings help tools that manage their
> own tokens: one gives tokens created without an expiration date the
> maximum lifetime, the other allows extending a token if its secret is
> regenerated in the same request.
> 
> [...]

Applied with @Shannon's latest findings (and a bit more) addressed,
thanks for the review here.

[cluster] applied to pve-cluster.git (master)
[1/3] datacenter config: add token-policy option
      https://git.proxmox.com/?p=pve-cluster.git;a=commitdiff;h=86d121f77d0d7d050ec77ba163bc46eba72b5f63
[2/3] datacenter config: token policy: add default-to-max-lifetime setting
      https://git.proxmox.com/?p=pve-cluster.git;a=commitdiff;h=99e00f926e36b4c018ae378f0f3c43a649253f16
[3/3] datacenter config: token policy: allow extension on regeneration
      https://git.proxmox.com/?p=pve-cluster.git;a=commitdiff;h=15a7665ec979da04bc946414690be8f66f06e00f

[access-control] applied to git/pve-access-control.git (master)
[1/3] fix #7805: api: token: enforce datacenter token policy
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=5550002b8523195ad1f5ca53a238c055db556529
[2/3] api: token: apply the default lifetime from the token policy
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=b41b744e9de677d202d8c7db00b3789946299f00
[3/3] api: token: allow extending tokens on secret regeneration
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=26fda76df278d1dbebf6484a6ede52da4909ef94

[docs] applied to pve-docs.git (master)
[1/3] user management: document the API token policy
      https://git.proxmox.com/?p=pve-docs.git;a=commitdiff;h=e11934fca3459fc4e7d83f4167d3ccbeadde1596
[2/3] user management: document the default-to-max-lifetime setting
      https://git.proxmox.com/?p=pve-docs.git;a=commitdiff;h=7772c77dd855043647602e53cde0bd17765c45bd
[3/3] user management: document extending tokens on secret regeneration
      https://git.proxmox.com/?p=pve-docs.git;a=commitdiff;h=286fa3f1639fdd8c85d3cbb0765486c3290ce6cf

[manager] applied to pve-manager.git (master)
[1/6] ui: token edit: only submit the expiration date when changed
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=123d8fca229c8c576a6e9dd76569dffa6a8b859a
[2/6] api: cluster options: return token-policy without Sys.Audit
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=33d36aab9e3c0bd9cad7b7cd2fff661feb060f12
[3/6] ui: dc options: allow editing the API token policy
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=acf6773e5500b7b770423162a96180e0ae0e1c8c
[4/6] ui: token edit: adapt to the datacenter API token policy
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=684b10c9341b9006bcb5f3bd338e7d821aa4e46b
[5/6] ui: token policy: expose the default-to-max-lifetime setting
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=4735a0bf4c673106ed62fc84d5c6646502c1a7ba
[6/6] ui: token policy: allow extension on secret regeneration
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=ab96a34a1c041442172b1a45776955ad14bb43ff

[proxmox] applied to git/proxmox.git (master)
[1/4] access-control: add API token policy type with expiry checks
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=bf06cacdead7ecf014c759b5b1b0cd150bec7ed5
[2/4] access-control: enforce token policy on token create and update
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=61c9e069436194eb1551c9c241429501816ed64b
[3/4] access-control: apply a default token lifetime from the policy
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=af2980f62fc9ebfd2485fa7df9d3612634c03c53
[4/4] access-control: allow extending tokens on secret regeneration
      https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=3f925ad1ecc38fb4233e96cc509bf865de1749b4




^ permalink raw reply	[relevance 17%]

* Re: [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy
  2026-11-15 19:40 25% ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
@ 2026-11-17 13:30  8%   ` Shannon Sterz
  0 siblings, 0 replies; 17+ results
From: Shannon Sterz @ 2026-11-17 13:30 UTC (permalink / raw)
  To: Thomas Lamprecht, pve-devel

this patch no longer applies for me

On Sun Nov 15, 2026 at 8:40 PM CET, Thomas Lamprecht wrote:
> Check the new datacenter.cfg token-policy option on API token
> creation and update, so admins can centrally require expiration
> dates, bound the maximum token lifetime, forbid extending existing
> expiration dates, and require privilege separation, as commonly
> mandated by compliance rules like PCI DSS, SOC 2, or ISO 27001.
>
> Existing tokens stay valid, and an update only checks settings it
> actually changes, so unrelated edits or clients resubmitting
> unchanged fields are not rejected for tokens that predate the policy.
> The check runs before the secret is generated to avoid leaving an
> orphaned entry in token.cfg on rejection. Regenerating the secret of
> an existing token is deliberately not restricted: rotation does not
> extend validity, and blocking it would only discourage rotating old
> credentials.
>
> Changing the policy itself requires Sys.Modify on '/', like any
> other datacenter option. No extra auth-specific privilege is added
> for now, as it would end up in the same built-in roles that already
> carry Sys.Modify and thus allow the same users, and anyone allowed to
> change datacenter options can adapt the policy in any case.
>
> Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
> ---
>
> changes since v1:
> - pass the current expiration date instead of 'is-update', so that
>   'disallow-expiry-extension' only rejects extending it
> - use v5.36 in the tests

-->8 snip 8<--




^ permalink raw reply	[relevance 8%]

* Re: [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks
  2026-11-15 19:40 18% ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
@ 2026-11-17 13:29  5%   ` Shannon Sterz
  0 siblings, 0 replies; 17+ results
From: Shannon Sterz @ 2026-11-17 13:29 UTC (permalink / raw)
  To: Thomas Lamprecht, pve-devel

On Sun Nov 15, 2026 at 8:40 PM CET, Thomas Lamprecht wrote:
> 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)

nit: here ...

> +        {
> +            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()) {

and here, might want to do a `expire <= 0`. while the api schema should
forbid expire to be negative, if anything calls the update function
directly that may not be enforced. to protect to this scenario and match
the behavior of the api endpoint check for `<= 0` here.

-->8 snip 8<--




^ permalink raw reply	[relevance 5%]

* Re: [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy
  2026-11-15 19:40 17% [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] " Thomas Lamprecht
                   ` (2 preceding siblings ...)
  2026-11-15 19:40 18% ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
@ 2026-11-17 13:29  8% ` Shannon Sterz
  2026-11-18  2:17 17% ` applied: " Thomas Lamprecht
  4 siblings, 0 replies; 17+ results
From: Shannon Sterz @ 2026-11-17 13:29 UTC (permalink / raw)
  To: Thomas Lamprecht, pve-devel

On Sun Nov 15, 2026 at 8:40 PM CET, Thomas Lamprecht wrote:
> Compliance rules like PCI DSS, SOC 2, or ISO 27001 often require
> that credentials have a limited lifetime, but there is no central way
> to enforce that for API tokens.
>
> Add an optional token-policy option to datacenter.cfg to require an
> expiration date, limit the maximum token lifetime, forbid extending
> the expiration date of existing tokens, and require privilege
> separation. Two further opt-in settings help tools that manage their
> own tokens: one gives tokens created without an expiration date the
> maximum lifetime, the other allows extending a token if its secret is
> regenerated in the same request.
>
> The policy is only checked when a token is created or updated, and
> only for values that actually change, so existing tokens stay valid
> even if their lifetime exceeds a newly configured maximum one.
> Extending the expiration date within the limit stays possible, unless
> the opt-in 'disallow-expiry-extension' switch is set (see [0] for the
> rationale).
>
> The web UI exposes these options under Datacenter -> Options and
> adjusts the token dialogs to the policy. Changing the policy requires
> Sys.Modify on '/', like any other datacenter option; an extra
> auth-specific privilege check was skipped for now, for the current
> built-in roles it would land in the same roles as Sys.Modify, adding new
> built-in roles here is IMO scope creep and this can still be done later
> (with some more thoughts on how to handle all these datacenter options).
>
> FWIW, the first manager patch (10/19 overall) fixes a pre-existing issue
> w.r.t. only submitting the expiration date when changed, which the
> policy checks would expose more often, but it'd also make sense on its
> own and could be applied independently already.
>
> The last four patches port the backend part to the common rust stack, so
> PBS and PDM can opt in through their AccessControlConfig, and to prepare
> moving pve-access-control over to rust later. Only the expiry parts
> apply there, tokens in the rust stack always use separate ACLs, i.e. no
> sharing with the underlying users there.
>
> Dependencies: access-control needs the cluster patches, manager needs
> both, and building manager needs the pve-doc-generator with the new
> online-help anchor from the docs patches (or ALLOW_MISSING=1), which is
> why the docs patches come before the manager ones; the proxmox patches
> are independent. d/control needs the respective versioned dependency
> bumps added on applying, and the generated datacenter option reference
> in pve-docs needs the usual make update once the cluster side is
> packaged.
>
> Changes since v1 (thanks @Shannon for the review):
> - rename 'disallow-expiry-changes' to 'disallow-expiry-extension', which
>   only rejects removing the expiration date or moving it later
> - add the two settings for tools managing their own tokens, suggested by
>   Shannon. They are part of this series, not a follow-up, as nodes not
>   knowing them would drop the whole policy
> - docs: warn to only configure the policy once all nodes are upgraded
> - token dialog: follow the server clock, not the browser's
> - rebase on current master; smaller changes are noted per patch
>
> [0]: https://bugzilla.proxmox.com/show_bug.cgi?id=7805

thanks for the quick v2, looks good to me. just left a few nits, but
nothing really worth blocking this over. couldn't test it as the patches
for pve-access-control don't apply for me anymore, but consider this:

Reviewed-by: Shannon Sterz <s.sterz@proxmox.com>




^ permalink raw reply	[relevance 8%]

* superseded: [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy
  2026-09-23 20:59 17% [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
                   ` (3 preceding siblings ...)
  2026-11-10 15:05 12% ` [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Shannon Sterz
@ 2026-11-15 23:38  8% ` Thomas Lamprecht
  4 siblings, 0 replies; 17+ results
From: Thomas Lamprecht @ 2026-11-15 23:38 UTC (permalink / raw)
  To: pve-devel

superseded-by: https://lore.proxmox.com/pve-devel/20261115194043.3947825-1-t.lamprecht@proxmox.com/




^ permalink raw reply	[relevance 8%]

* [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy
  2026-11-15 19:40 17% [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] " Thomas Lamprecht
  2026-11-15 19:40 19% ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
@ 2026-11-15 19:40 25% ` Thomas Lamprecht
  2026-11-17 13:30  8%   ` Shannon Sterz
  2026-11-15 19:40 18% ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
                   ` (2 subsequent siblings)
  4 siblings, 1 reply; 17+ results
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
  To: pve-devel

Check the new datacenter.cfg token-policy option on API token
creation and update, so admins can centrally require expiration
dates, bound the maximum token lifetime, forbid extending existing
expiration dates, and require privilege separation, as commonly
mandated by compliance rules like PCI DSS, SOC 2, or ISO 27001.

Existing tokens stay valid, and an update only checks settings it
actually changes, so unrelated edits or clients resubmitting
unchanged fields are not rejected for tokens that predate the policy.
The check runs before the secret is generated to avoid leaving an
orphaned entry in token.cfg on rejection. Regenerating the secret of
an existing token is deliberately not restricted: rotation does not
extend validity, and blocking it would only discourage rotating old
credentials.

Changing the policy itself requires Sys.Modify on '/', like any
other datacenter option. No extra auth-specific privilege is added
for now, as it would end up in the same built-in roles that already
carry Sys.Modify and thus allow the same users, and anyone allowed to
change datacenter options can adapt the policy in any case.

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

changes since v1:
- pass the current expiration date instead of 'is-update', so that
  'disallow-expiry-extension' only rejects extending it
- use v5.36 in the tests

 src/PVE/API2/User.pm              |  31 +++-
 src/PVE/AccessControl.pm          |  62 ++++++++
 src/test/Makefile                 |   2 +
 src/test/token-policy-api-test.pl | 115 ++++++++++++++
 src/test/token-policy-test.pl     | 242 ++++++++++++++++++++++++++++++
 5 files changed, 449 insertions(+), 3 deletions(-)
 create mode 100644 src/test/token-policy-api-test.pl
 create mode 100644 src/test/token-policy-test.pl

diff --git a/src/PVE/API2/User.pm b/src/PVE/API2/User.pm
index 31cf44b..78e5fc9 100644
--- a/src/PVE/API2/User.pm
+++ b/src/PVE/API2/User.pm
@@ -806,14 +806,20 @@ __PACKAGE__->register_method({
             die "Token already exists.\n"
                 if defined(PVE::AccessControl::check_token_exist($usercfg, $userid, $tokenid, 1));
 
-            $full_tokenid = PVE::AccessControl::join_tokenid($userid, $tokenid);
-            $value = PVE::TokenConfig::generate_token($full_tokenid);
-
             $token = {};
             $token->{privsep} = defined($param->{privsep}) ? $param->{privsep} : 1;
             $token->{expire} = $param->{expire} if defined($param->{expire});
             $token->{comment} = $param->{comment} if $param->{comment};
 
+            # check policy before generating the secret to avoid leaving an orphan in token.cfg
+            PVE::AccessControl::assert_token_policy({
+                expire => $token->{expire} // 0,
+                'privilege-separation' => $token->{privsep},
+            });
+
+            $full_tokenid = PVE::AccessControl::join_tokenid($userid, $tokenid);
+            $value = PVE::TokenConfig::generate_token($full_tokenid);
+
             $usercfg->{users}->{$userid}->{tokens}->{$tokenid} = $token;
             cfs_write_file("user.cfg", $usercfg);
         };
@@ -899,11 +905,30 @@ __PACKAGE__->register_method({
                 $usercfg = cfs_read_file("user.cfg");
                 $token = PVE::AccessControl::check_token_exist($usercfg, $userid, $tokenid);
 
+                my $old_expire = $token->{expire} // 0;
+                my $old_privilege_separation = $token->{privsep} // 0;
+
                 $token->{privsep} = $param->{privsep} if defined($param->{privsep});
                 $token->{expire} = $param->{expire} if defined($param->{expire});
                 $token->{comment} = $param->{comment} if defined($param->{comment});
                 delete $token->{comment} if (!length $token->{comment});
 
+                my $new_expire = $token->{expire} // 0;
+                my $new_privilege_separation = $token->{privsep} // 0;
+
+                # only check what this update changes, so that tokens that predate the policy
+                # stay editable
+                my $expire_change = $new_expire != $old_expire ? $new_expire : undef;
+                my $privilege_separation_change =
+                    $new_privilege_separation != $old_privilege_separation
+                    ? $new_privilege_separation
+                    : undef;
+                PVE::AccessControl::assert_token_policy({
+                    expire => $expire_change,
+                    'privilege-separation' => $privilege_separation_change,
+                    'current-expire' => $old_expire,
+                });
+
                 my $deletable = {
                     comment => 1,
                 };
diff --git a/src/PVE/AccessControl.pm b/src/PVE/AccessControl.pm
index a4e1c36..e2027cf 100644
--- a/src/PVE/AccessControl.pm
+++ b/src/PVE/AccessControl.pm
@@ -21,6 +21,7 @@ use PVE::OTP;
 use PVE::Ticket;
 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
+use PVE::DataCenterConfig; # ensure the 'datacenter.cfg' cfs parser is registered
 use PVE::JSONSchema qw(register_standard_option get_standard_option);
 
 use PVE::RS::TFA;
@@ -691,6 +692,67 @@ sub check_user_enabled {
     return 1; # enabled and not expired
 }
 
+# Assert that a token's expiration date and privilege separation setting conform to the
+# datacenter token policy. Dies with a descriptive message on violation.
+#
+# Takes a hash reference with the following keys:
+# - expire: the expiration date to check (epoch seconds, 0 for none); undef skips the expiration
+#   date checks
+# - privilege-separation: the privilege separation flag to check; undef skips that check
+# - current-expire: the expiration date of an existing token before the update, 0 for none
+# - ctime, policy: override the reference time for the maximum lifetime and the policy from the
+#   datacenter config, for testing
+#
+# Callers pass only the values an operation sets or changes, so that unrelated updates do not
+# reject tokens that predate the policy.
+sub assert_token_policy {
+    my ($param) = @_;
+
+    # integer API parameters keep their submitted spelling, and zero spellings like '00' or '-0'
+    # are true in Perl, so numify to not mistake them for a set expiration date
+    my $expire = defined($param->{expire}) ? int($param->{expire}) : undef;
+    my $privilege_separation = $param->{'privilege-separation'};
+
+    return if !defined($expire) && !defined($privilege_separation);
+
+    my $policy = $param->{policy} // cfs_read_file('datacenter.cfg')->{'token-policy'};
+    return if !$policy;
+
+    if (defined($expire)) {
+        # removing the expiration date or moving it later extends the token
+        my $current_expire = $param->{'current-expire'};
+        if (
+            $policy->{'disallow-expiry-extension'}
+            && $current_expire
+            && (!$expire || $expire > $current_expire)
+        ) {
+            die "the datacenter token policy does not allow extending the expiration date of an"
+                . " existing token\n";
+        }
+
+        my $ctime = $param->{ctime} // time();
+        my $max_lifetime = $policy->{'max-lifetime'};
+        # a token that never expires exceeds any maximum lifetime
+        my $require_expiry = $policy->{'require-expiry'} || $max_lifetime;
+
+        die "the datacenter token policy requires an expiration date\n"
+            if $require_expiry && !$expire;
+
+        if ($max_lifetime && $expire && $expire > $ctime + $max_lifetime) {
+            die "the expiration date exceeds the maximum token lifetime of $max_lifetime seconds"
+                . " set by the datacenter token policy\n";
+        }
+    }
+
+    if (
+        defined($privilege_separation)
+        && $policy->{'require-privilege-separation'}
+        && !$privilege_separation
+    ) {
+        die "the datacenter token policy requires privilege separation\n";
+    }
+}
+
 sub check_token_exist {
     my ($usercfg, $username, $tokenid, $noerr) = @_;
 
diff --git a/src/test/Makefile b/src/test/Makefile
index 8f3ba47..357bb02 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -16,6 +16,8 @@ check:
 	perl -I.. realm_sync_test.pl
 	perl -I.. pve-realm-password-hash-test.pl
 	perl -I.. pool-name-0-test.pl
+	perl -I.. token-policy-test.pl
+	perl -I.. token-policy-api-test.pl
 	perl -I.. user-api-groups-test.pl
 	perl -I.. acl-api-members-test.pl
 	perl -I.. realm-group-name-0-test.pl
diff --git a/src/test/token-policy-api-test.pl b/src/test/token-policy-api-test.pl
new file mode 100644
index 0000000..5af4e58
--- /dev/null
+++ b/src/test/token-policy-api-test.pl
@@ -0,0 +1,115 @@
+#!/usr/bin/perl
+
+use v5.36;
+
+use Test::More;
+use Test::MockModule;
+
+use PVE::AccessControl;
+use PVE::API2::User;
+
+# Exercise the token create and update API handlers with the real schema validation and user
+# config parser/writer, mocking out the cluster file system and secret generation. The integer
+# schema accepts zero spellings like '00', '+0', or '-0' without canonicalizing them, so the
+# policy enforcement at the API boundary must not mistake them for a set expiration date.
+
+my ($policy, $user_cfg_raw, $secret_calls);
+
+my $read = sub {
+    my ($file) = @_;
+    return PVE::AccessControl::parse_user_config($file, $user_cfg_raw) if $file eq 'user.cfg';
+    return { 'token-policy' => $policy } if $file eq 'datacenter.cfg';
+    die "unexpected cfs_read_file('$file') call\n";
+};
+
+my $access_control_module = Test::MockModule->new('PVE::AccessControl');
+$access_control_module->mock(cfs_read_file => $read);
+$access_control_module->mock(lock_user_config => sub { $_[0]->() });
+
+my $api_user_module = Test::MockModule->new('PVE::API2::User');
+$api_user_module->mock(cfs_read_file => $read);
+$api_user_module->mock(
+    cfs_write_file => sub {
+        my ($file, $cfg) = @_;
+        die "unexpected cfs_write_file('$file') call\n" if $file ne 'user.cfg';
+        $user_cfg_raw = PVE::AccessControl::write_user_config($file, $cfg);
+    },
+);
+
+my $token_config_module = Test::MockModule->new('PVE::TokenConfig');
+$token_config_module->mock(
+    generate_token => sub {
+        $secret_calls++;
+        return 'test-secret';
+    },
+);
+
+my $reset = sub {
+    my ($test_policy, $expire) = @_;
+    $policy = $test_policy;
+    $user_cfg_raw = "user:test\@pve:1:0::::::\n";
+    $user_cfg_raw .= "token:test\@pve!old:$expire:1:some comment:\n" if defined($expire);
+    $secret_calls = 0;
+};
+
+my $invoke = sub {
+    my ($method, $param) = @_;
+    my $ok = eval {
+        PVE::API2::User->$method({ userid => 'test@pve', %$param });
+        1;
+    };
+    return ($ok, $@);
+};
+
+my $now = time();
+
+for my $policy_variant ({ 'require-expiry' => 1 }, { 'max-lifetime' => 86400 }) {
+    my $desc = join(',', map { "$_=$policy_variant->{$_}" } sort keys $policy_variant->%*);
+
+    for my $zero ('0', '00', '+0', '-0') {
+        $reset->($policy_variant);
+        my ($ok, $err) = $invoke->('generate_token', { tokenid => 'new', expire => $zero });
+        ok(
+            !$ok && $err =~ /requires an expiration date/,
+            "$desc: create with expire=$zero rejected",
+        );
+        is($secret_calls, 0, "$desc: rejected create generates no secret");
+        ok($user_cfg_raw !~ /!new/, "$desc: rejected create writes no token");
+
+        $reset->($policy_variant, $now + 600);
+        my $before = $user_cfg_raw;
+        ($ok, $err) =
+            $invoke->('update_token_info', { tokenid => 'old', expire => $zero, regenerate => 1 });
+        ok(
+            !$ok && $err =~ /requires an expiration date/, "$desc: update to expire=$zero rejected",
+        );
+        is($secret_calls, 0, "$desc: rejected update rotates no secret");
+        is($user_cfg_raw, $before, "$desc: rejected update writes nothing");
+    }
+
+    $reset->($policy_variant);
+    my ($ok, $err) = $invoke->('generate_token', { tokenid => 'new', expire => $now + 600 });
+    ok($ok, "$desc: compliant create accepted") or diag($err);
+    is($secret_calls, 1, "$desc: accepted create generates a secret");
+}
+
+# unrelated updates of a token that predates the policy must keep working
+$reset->({ 'require-expiry' => 1 }, 0);
+my ($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', comment => 'changed' });
+ok($ok, 'unrelated update of a non-conforming token stays allowed') or diag($err);
+
+# disallow-expiry-extension only forbids what would prolong a token
+$reset->({ 'disallow-expiry-extension' => 1 }, $now + 600);
+($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', expire => $now + 1200 });
+ok(!$ok && $err =~ /does not allow extending/, 'extending the expiry is rejected');
+($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', expire => 0 });
+ok(!$ok && $err =~ /does not allow extending/, 'removing the expiry is rejected');
+($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', expire => $now + 300 });
+ok($ok, 'shortening the expiry stays allowed') or diag($err);
+($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', expire => $now + 300 });
+ok($ok, 'resubmitting the unchanged expiry stays allowed') or diag($err);
+$reset->({ 'disallow-expiry-extension' => 1 }, 0);
+($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', expire => $now + 600 });
+ok($ok, 'setting an expiry on a token without one stays allowed') or diag($err);
+
+done_testing();
diff --git a/src/test/token-policy-test.pl b/src/test/token-policy-test.pl
new file mode 100644
index 0000000..d29c781
--- /dev/null
+++ b/src/test/token-policy-test.pl
@@ -0,0 +1,242 @@
+#!/usr/bin/perl
+
+use v5.36;
+
+use Test::More;
+use Test::MockModule;
+
+use PVE::AccessControl;
+
+# tests pass the policy explicitly; keep the fallback read of datacenter.cfg from hitting a
+# real pmxcfs so the cases without a policy exercise that path against an empty config
+my $access_control_module = Test::MockModule->new('PVE::AccessControl');
+$access_control_module->mock(
+    cfs_read_file => sub {
+        my ($file) = @_;
+        die "unexpected cfs_read_file('$file') call\n" if $file ne 'datacenter.cfg';
+        return {};
+    },
+);
+
+# fixed reference time and a 90-day maximum lifetime for deterministic bounds checks
+my $now = 1_000_000_000;
+my $max = 90 * 24 * 60 * 60;
+
+sub check {
+    my ($desc, $policy, $param, $should_die) = @_;
+
+    my $err;
+    eval {
+        PVE::AccessControl::assert_token_policy({
+            ctime => $now,
+            policy => $policy,
+            $param->%*,
+        });
+        1;
+    } or $err = $@;
+
+    if ($should_die) {
+        ok($err, "$desc: rejected") or diag("expected rejection but call succeeded");
+    } else {
+        ok(!$err, "$desc: accepted") or diag("unexpected rejection: $err");
+    }
+}
+
+# no policy configured -> everything is allowed
+check(
+    'no policy, never-expiring full-priv token',
+    undef,
+    { expire => 0, 'privilege-separation' => 0 },
+    0,
+);
+check('no policy, undef dimensions', undef, {}, 0);
+check(
+    'empty policy, never-expiring full-priv token',
+    {},
+    { expire => 0, 'privilege-separation' => 0 },
+    0,
+);
+
+# require-expiry
+my $req_expire = { 'require-expiry' => 1 };
+check('require-expiry, no expiry', $req_expire, { expire => 0 }, 1);
+check('require-expiry, future expiry', $req_expire, { expire => $now + 100 }, 0);
+check('require-expiry, expiry dimension not touched', $req_expire, {}, 0);
+check(
+    'require-expiry, update removing the expiry',
+    $req_expire,
+    { expire => 0, 'current-expire' => $now + 50 },
+    1,
+);
+check(
+    'require-expiry, does not constrain privsep',
+    $req_expire,
+    { expire => $now + 100, 'privilege-separation' => 0 },
+    0,
+);
+
+# max-lifetime implies an expiry is required and bounds how far it may reach
+my $max_life = { 'max-lifetime' => $max };
+check('max-lifetime, never-expiring is rejected', $max_life, { expire => 0 }, 1);
+check('max-lifetime, within bound', $max_life, { expire => $now + 100 }, 0);
+check('max-lifetime, exactly at bound', $max_life, { expire => $now + $max }, 0);
+check('max-lifetime, one second past bound', $max_life, { expire => $now + $max + 1 }, 1);
+check('max-lifetime, expiry dimension not touched', $max_life, {}, 0);
+check(
+    'max-lifetime, update prolonging past the bound',
+    $max_life,
+    { expire => $now + $max + 1, 'current-expire' => $now + 50 },
+    1,
+);
+check('max-lifetime, expiry in the past accepted', $max_life, { expire => $now - 100 }, 0);
+check(
+    'max-lifetime with explicit require-expiry=0 still requires an expiry',
+    { 'require-expiry' => 0, 'max-lifetime' => $max },
+    { expire => 0 },
+    1,
+);
+
+# the integer schema passes zero spellings like '00' through with their submitted string
+# spelling, and those are true as Perl scalars; they must still count as "no expiration date"
+for my $zero ('0', '00', '+0', '-0') {
+    check("require-expiry, create with zero spelling '$zero'", $req_expire, { expire => $zero }, 1);
+    check(
+        "require-expiry, update removing the expiry via zero spelling '$zero'",
+        $req_expire,
+        { expire => $zero, 'current-expire' => $now + 50 },
+        1,
+    );
+    check("max-lifetime, create with zero spelling '$zero'", $max_life, { expire => $zero }, 1);
+}
+
+# disallow-expiry-extension rejects removing or moving the expiration date later on update,
+# but neither shortening it, the initial expiration date on creation, nor updates that leave the
+# expiration date untouched
+my $no_extension = { 'disallow-expiry-extension' => 1 };
+check(
+    'disallow-expiry-extension, update extending expiry',
+    $no_extension,
+    { expire => $now + 200, 'current-expire' => $now + 100 },
+    1,
+);
+check(
+    'disallow-expiry-extension, update extending expiry by one second',
+    $no_extension,
+    { expire => $now + 101, 'current-expire' => $now + 100 },
+    1,
+);
+check(
+    'disallow-expiry-extension, update removing expiry',
+    $no_extension,
+    { expire => 0, 'current-expire' => $now + 100 },
+    1,
+);
+check(
+    'disallow-expiry-extension, update shortening expiry',
+    $no_extension,
+    { expire => $now + 100, 'current-expire' => $now + 200 },
+    0,
+);
+check(
+    'disallow-expiry-extension, update moving expiry into the past',
+    $no_extension,
+    { expire => $now - 100, 'current-expire' => $now + 100 },
+    0,
+);
+check(
+    'disallow-expiry-extension, update setting an expiry on a token without one',
+    $no_extension,
+    { expire => $now + 100, 'current-expire' => 0 },
+    0,
+);
+check(
+    'disallow-expiry-extension, update not touching expiry',
+    $no_extension,
+    { 'current-expire' => $now + 100 },
+    0,
+);
+check('disallow-expiry-extension, creation sets expiry', $no_extension, { expire => $now + 100 },
+    0);
+check('disallow-expiry-extension, creation without expiry', $no_extension, { expire => 0 }, 0);
+check(
+    'disallow-expiry-extension, does not constrain privsep',
+    $no_extension,
+    { 'privilege-separation' => 0, 'current-expire' => $now + 100 },
+    0,
+);
+check(
+    'disallow-expiry-extension wins over a compliant extension under require-expiry',
+    { 'disallow-expiry-extension' => 1, 'require-expiry' => 1 },
+    { expire => $now + 200, 'current-expire' => $now + 100 },
+    1,
+);
+check(
+    'disallow-expiry-extension, shortening under max-lifetime stays allowed',
+    { 'disallow-expiry-extension' => 1, 'max-lifetime' => $max },
+    { expire => $now + 100, 'current-expire' => $now + 200 },
+    0,
+);
+
+# require-privilege-separation
+my $require_privilege_separation = { 'require-privilege-separation' => 1 };
+check(
+    'require-privilege-separation, full-priv token rejected',
+    $require_privilege_separation,
+    { 'privilege-separation' => 0 },
+    1,
+);
+check(
+    'require-privilege-separation, privsep token accepted',
+    $require_privilege_separation,
+    { 'privilege-separation' => 1 },
+    0,
+);
+check(
+    'require-privilege-separation, privsep dimension not touched',
+    $require_privilege_separation,
+    {},
+    0,
+);
+check(
+    'require-privilege-separation, does not constrain expiry',
+    $require_privilege_separation,
+    { expire => 0, 'privilege-separation' => 1 },
+    0,
+);
+
+# combined policy, as an admin would set for a compliance baseline
+my $full = { 'require-expiry' => 1, 'max-lifetime' => $max, 'require-privilege-separation' => 1 };
+check(
+    'full policy, compliant token',
+    $full,
+    { expire => $now + 100, 'privilege-separation' => 1 },
+    0,
+);
+check('full policy, missing expiry', $full, { expire => 0, 'privilege-separation' => 1 }, 1);
+check(
+    'full policy, expiry too far out',
+    $full,
+    { expire => $now + $max + 1, 'privilege-separation' => 1 },
+    1,
+);
+check(
+    'full policy, full-priv token',
+    $full,
+    { expire => $now + 100, 'privilege-separation' => 0 },
+    1,
+);
+# partial updates only check what they change
+check(
+    'full policy, update touching only a valid expiry',
+    $full,
+    { expire => $now + 100, 'current-expire' => $now + 50 },
+    0,
+);
+check(
+    'full policy, update touching only privsep',
+    $full,
+    { 'privilege-separation' => 1, 'current-expire' => $now + 50 },
+    0,
+);
+
+done_testing();
-- 
2.47.3





^ permalink raw reply related	[relevance 25%]

* [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks
  2026-11-15 19:40 17% [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] " Thomas Lamprecht
  2026-11-15 19:40 19% ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
  2026-11-15 19:40 25% ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
@ 2026-11-15 19:40 18% ` Thomas Lamprecht
  2026-11-17 13:29  5%   ` Shannon Sterz
  2026-11-17 13:29  8% ` [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 17% ` applied: " Thomas Lamprecht
  4 siblings, 1 reply; 17+ results
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
  To: pve-devel

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





^ permalink raw reply related	[relevance 18%]

* [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy
@ 2026-11-15 19:40 17% Thomas Lamprecht
  2026-11-15 19:40 19% ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
                   ` (4 more replies)
  0 siblings, 5 replies; 17+ results
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
  To: pve-devel

Compliance rules like PCI DSS, SOC 2, or ISO 27001 often require
that credentials have a limited lifetime, but there is no central way
to enforce that for API tokens.

Add an optional token-policy option to datacenter.cfg to require an
expiration date, limit the maximum token lifetime, forbid extending
the expiration date of existing tokens, and require privilege
separation. Two further opt-in settings help tools that manage their
own tokens: one gives tokens created without an expiration date the
maximum lifetime, the other allows extending a token if its secret is
regenerated in the same request.

The policy is only checked when a token is created or updated, and
only for values that actually change, so existing tokens stay valid
even if their lifetime exceeds a newly configured maximum one.
Extending the expiration date within the limit stays possible, unless
the opt-in 'disallow-expiry-extension' switch is set (see [0] for the
rationale).

The web UI exposes these options under Datacenter -> Options and
adjusts the token dialogs to the policy. Changing the policy requires
Sys.Modify on '/', like any other datacenter option; an extra
auth-specific privilege check was skipped for now, for the current
built-in roles it would land in the same roles as Sys.Modify, adding new
built-in roles here is IMO scope creep and this can still be done later
(with some more thoughts on how to handle all these datacenter options).

FWIW, the first manager patch (10/19 overall) fixes a pre-existing issue
w.r.t. only submitting the expiration date when changed, which the
policy checks would expose more often, but it'd also make sense on its
own and could be applied independently already.

The last four patches port the backend part to the common rust stack, so
PBS and PDM can opt in through their AccessControlConfig, and to prepare
moving pve-access-control over to rust later. Only the expiry parts
apply there, tokens in the rust stack always use separate ACLs, i.e. no
sharing with the underlying users there.

Dependencies: access-control needs the cluster patches, manager needs
both, and building manager needs the pve-doc-generator with the new
online-help anchor from the docs patches (or ALLOW_MISSING=1), which is
why the docs patches come before the manager ones; the proxmox patches
are independent. d/control needs the respective versioned dependency
bumps added on applying, and the generated datacenter option reference
in pve-docs needs the usual make update once the cluster side is
packaged.

Changes since v1 (thanks @Shannon for the review):
- rename 'disallow-expiry-changes' to 'disallow-expiry-extension', which
  only rejects removing the expiration date or moving it later
- add the two settings for tools managing their own tokens, suggested by
  Shannon. They are part of this series, not a follow-up, as nodes not
  knowing them would drop the whole policy
- docs: warn to only configure the policy once all nodes are upgraded
- token dialog: follow the server clock, not the browser's
- rebase on current master; smaller changes are noted per patch

[0]: https://bugzilla.proxmox.com/show_bug.cgi?id=7805

cluster:

Thomas Lamprecht (3):
  datacenter config: add token-policy option
  datacenter config: token policy: add default-to-max-lifetime setting
  datacenter config: token policy: allow extension on regeneration

 src/PVE/DataCenterConfig.pm   | 69 +++++++++++++++++++++++++++++++++++++++
 src/test/Makefile             |  6 +++-
 src/test/test_token_policy.pl | 75 +++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 149 insertions(+), 1 deletion(-)

access-control:

Thomas Lamprecht (3):
  fix #7805: api: token: enforce datacenter token policy
  api: token: apply the default lifetime from the token policy
  api: token: allow extending tokens on secret regeneration

 src/PVE/API2/User.pm              |  37 ++++-
 src/PVE/AccessControl.pm          |  80 ++++++++++
 src/test/Makefile                 |   2 +
 src/test/token-policy-api-test.pl | 148 +++++++++++++++++++
 src/test/token-policy-test.pl     | 304 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 568 insertions(+), 3 deletions(-)

docs:

Thomas Lamprecht (3):
  user management: document the API token policy
  user management: document the default-to-max-lifetime setting
  user management: document extending tokens on secret regeneration

 pveum.adoc | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 63 insertions(+)

manager:

Thomas Lamprecht (6):
  ui: token edit: only submit the expiration date when changed
  api: cluster options: return token-policy without Sys.Audit
  ui: dc options: allow editing the API token policy
  ui: token edit: adapt to the datacenter API token policy
  ui: token policy: expose the default-to-max-lifetime setting
  ui: token policy: allow extension on secret regeneration

 PVE/API2/Cluster.pm           |   2 +-
 www/manager6/UIOptions.js     |  23 ++++-
 www/manager6/dc/OptionView.js | 195 ++++++++++++++++++++++++++++++++++++++++++
 www/manager6/dc/TokenEdit.js  | 193 ++++++++++++++++++++++++++++++++++++++++-
 www/manager6/dc/TokenView.js  |  36 ++++----
 5 files changed, 431 insertions(+), 18 deletions(-)

proxmox:

Thomas Lamprecht (4):
  access-control: add API token policy type with expiry checks
  access-control: enforce token policy on token create and update
  access-control: apply a default token lifetime from the policy
  access-control: allow extending tokens on secret regeneration

 proxmox-access-control/src/api/tokens.rs |  24 +++
 proxmox-access-control/src/init.rs       |  14 ++
 proxmox-access-control/src/types.rs      | 309 +++++++++++++++++++++++++++++++
 3 files changed, 347 insertions(+)

-- 
2.47.3




^ permalink raw reply	[relevance 17%]

* [PATCH v2 cluster 1/19] datacenter config: add token-policy option
  2026-11-15 19:40 17% [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] " Thomas Lamprecht
@ 2026-11-15 19:40 19% ` Thomas Lamprecht
  2026-11-15 19:40 25% ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
                   ` (3 subsequent siblings)
  4 siblings, 0 replies; 17+ results
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
  To: pve-devel

Compliance rules like PCI DSS, SOC 2, or ISO 27001 commonly mandate
bounded credential lifetimes, but without a central policy every
token creator must remember to set an expiration date manually.

Add an optional cluster-wide policy that can require an expiration
date, bound the maximum token lifetime, forbid extending the expiration
date of existing tokens, and require privilege separation for API
tokens. It is enforced by pve-access-control on token creation and
update only; existing tokens deliberately stay untouched, so opting in
does not invalidate already deployed tokens, and (by default)
prolonging a token within the bounds stays possible as a deliberate
act (see #7805).

Note that an unparsable policy is dropped with a warning and the rest
of datacenter.cfg still loads, the same as for every other property
string here, so a typo leaves tokens unrestricted rather than locked
down.

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

changes since v1:
- rename 'disallow-expiry-changes' to 'disallow-expiry-extension', which
  only rejects removing or moving the expiration date later
- use v5.36 in the test

 src/PVE/DataCenterConfig.pm   | 52 ++++++++++++++++++++++++++
 src/test/Makefile             |  6 ++-
 src/test/test_token_policy.pl | 69 +++++++++++++++++++++++++++++++++++
 3 files changed, 126 insertions(+), 1 deletion(-)
 create mode 100644 src/test/test_token_policy.pl

diff --git a/src/PVE/DataCenterConfig.pm b/src/PVE/DataCenterConfig.pm
index 004122e..13d388f 100644
--- a/src/PVE/DataCenterConfig.pm
+++ b/src/PVE/DataCenterConfig.pm
@@ -268,6 +268,42 @@ my $webauthn_format = {
     },
 };
 
+my $token_policy_format = {
+    'require-expiry' => {
+        type => 'boolean',
+        optional => 1,
+        default => 0,
+        description => "Require an expiration date for new API tokens and when changing the"
+            . " expiration date of existing ones.",
+    },
+    'max-lifetime' => {
+        type => 'integer',
+        optional => 1,
+        minimum => 1,
+        format_description => 'seconds',
+        description => "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'.",
+    },
+    'disallow-expiry-extension' => {
+        type => 'boolean',
+        optional => 1,
+        default => 0,
+        description => "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.",
+    },
+    'require-privilege-separation' => {
+        type => 'boolean',
+        optional => 1,
+        default => 0,
+        description => "Require privilege separation for new API tokens and when changing that"
+            . " setting on existing ones, that is, disallow tokens with the full privileges of"
+            . " their user.",
+    },
+};
+
 PVE::JSONSchema::register_format('mac-prefix', \&pve_verify_mac_prefix);
 
 sub pve_verify_mac_prefix {
@@ -510,6 +546,13 @@ my $datacenter_schema = {
             format => $webauthn_format,
             description => 'webauthn configuration',
         },
+        'token-policy' => {
+            optional => 1,
+            type => 'string',
+            format => $token_policy_format,
+            description => "Cluster-wide policy for creating and updating API tokens, for"
+                . " example to enforce an expiration date or privilege separation.",
+        },
         description => {
             type => 'string',
             description =>
@@ -614,6 +657,10 @@ sub parse_datacenter_config {
         $res->{webauthn} = parse_property_string($webauthn_format, $webauthn);
     }
 
+    if (my $token_policy = $res->{'token-policy'}) {
+        $res->{'token-policy'} = parse_property_string($token_policy_format, $token_policy);
+    }
+
     if (my $tag_style = $res->{'tag-style'}) {
         $res->{'tag-style'} = parse_property_string($tag_style_format, $tag_style);
     }
@@ -707,6 +754,11 @@ sub write_datacenter_config {
         $cfg->{webauthn} = PVE::JSONSchema::print_property_string($webauthn, $webauthn_format);
     }
 
+    if (ref(my $token_policy = $cfg->{'token-policy'})) {
+        $cfg->{'token-policy'} =
+            PVE::JSONSchema::print_property_string($token_policy, $token_policy_format);
+    }
+
     if (ref(my $tag_style = $cfg->{'tag-style'})) {
         $cfg->{'tag-style'} = PVE::JSONSchema::print_property_string($tag_style, $tag_style_format);
     }
diff --git a/src/test/Makefile b/src/test/Makefile
index cdd37d0..3a47b8c 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -4,7 +4,7 @@ cpgtest: cpgtest.c
 	gcc -Wall cpgtest.c $(shell pkg-config --cflags --libs libcpg libqb) -o cpgtest
 
 .PHONY: check install clean distclean
-check: corosync-parser-test test-mac-prefix
+check: corosync-parser-test test-mac-prefix test-token-policy
 
 .PHONY: corosync-parser-test
 corosync-parser-test:
@@ -14,5 +14,9 @@ corosync-parser-test:
 test-mac-prefix:
 	perl test_mac_prefix.pl
 
+.PHONY: test-token-policy
+test-token-policy:
+	perl test_token_policy.pl
+
 distclean: clean
 clean:
diff --git a/src/test/test_token_policy.pl b/src/test/test_token_policy.pl
new file mode 100644
index 0000000..0128aad
--- /dev/null
+++ b/src/test/test_token_policy.pl
@@ -0,0 +1,69 @@
+use v5.36;
+
+use Test::More;
+
+use lib ('.', '..');
+
+use PVE::DataCenterConfig;
+
+# the policy is a property string, so it has to survive a parse and write round trip and it must
+# not accept values that the enforcing side would not be able to interpret
+
+my $parse = sub {
+    my ($value) = @_;
+    my $raw = (defined($value) ? "token-policy: $value\n" : '') . "keyboard: en-us\n";
+    return PVE::DataCenterConfig::parse_datacenter_config('datacenter.cfg', $raw);
+};
+
+my $policy = $parse->('require-expiry=1,max-lifetime=86400')->{'token-policy'};
+is($policy->{'require-expiry'}, 1, 'require-expiry is parsed');
+is($policy->{'max-lifetime'}, 86400, 'max-lifetime is parsed');
+
+$policy = $parse->('disallow-expiry-extension=1,require-privilege-separation=1')->{'token-policy'};
+is($policy->{'disallow-expiry-extension'}, 1, 'disallow-expiry-extension is parsed');
+is($policy->{'require-privilege-separation'}, 1, 'require-privilege-separation is parsed');
+
+is($parse->(undef)->{'token-policy'}, undef, 'an absent token-policy is not invented');
+
+# an unusable policy has to be dropped, never half applied, and must not take the rest of the
+# configuration down with it
+for my $invalid (
+    'max-lifetime=0',
+    'max-lifetime=-1',
+    'max-lifetime=forever',
+    'require-expiry=maybe',
+    'unknown-key=1',
+) {
+    my $cfg;
+    {
+        local $SIG{__WARN__} = sub { };
+        $cfg = $parse->($invalid);
+    }
+    is($cfg->{'token-policy'}, undef, "'$invalid' does not yield a policy");
+    is($cfg->{keyboard}, 'en-us', "'$invalid' does not break the rest of the config");
+}
+
+# writing has to turn the parsed hash back into the property string
+my $raw = PVE::DataCenterConfig::write_datacenter_config(
+    'datacenter.cfg',
+    {
+        'token-policy' => {
+            'require-expiry' => 1,
+            'max-lifetime' => 86400,
+        },
+    },
+);
+like(
+    $raw,
+    qr/^token-policy:\s*(require-expiry=1,max-lifetime=86400|max-lifetime=86400,require-expiry=1)$/m,
+    'the policy is written back as a property string',
+);
+
+my $round_tripped = PVE::DataCenterConfig::parse_datacenter_config('datacenter.cfg', $raw);
+is_deeply(
+    $round_tripped->{'token-policy'},
+    { 'require-expiry' => 1, 'max-lifetime' => 86400 },
+    'the policy survives a write and parse round trip',
+);
+
+done_testing();
-- 
2.47.3





^ permalink raw reply related	[relevance 19%]

* Re: [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy
  2026-11-10 15:05 12% ` [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Shannon Sterz
@ 2026-11-10 15:28  8%   ` Thomas Lamprecht
  0 siblings, 0 replies; 17+ results
From: Thomas Lamprecht @ 2026-11-10 15:28 UTC (permalink / raw)
  To: Shannon Sterz, pve-devel

Hi, and thanks for your comments - appreciated!

Am 10.11.26 um 16:05 schrieb Shannon Sterz:
> one high level question: If I didn't miss anything, adding a token
> policy would break compatibility with PDM to an extend, since its wizard
> doesn't currently set any expiry. This is mostly relevant when using
> PDM's wizard for adding remotes and manually adding a token as a
> workaround should still work, but an expiry policy makes this
> cumbersome.
> 
> A nice follow up here might be adding an option that automatically set
> the current max token lifetime as the expiry. PDM could also be taught
> to rotate token secrets automatically somewhat analogously to my TLS
> certificate rotation series. For that an option to allow expiry
> extension on secret rotation only would be useful.

Yeah, that seems sensible, then the backend can abstract support for
this away and we do not need to differentiate in the frontend.

> IMO, the security impact of allowing an extension when the secret is
> regenerated is essentially 0 as creating a new token with a long expiry
> as is left for the old token is always possible. It would also encourage
> setting less broad permissions as they don't have to be re-added every
> time the token expires.
> 
> What do you think?

Agree fully, would be a sensible approach. I'll see if I can prepate this
for the v2 already, probably as dedicated series that builds upon this
here.




^ permalink raw reply	[relevance 8%]

* Re: [PATCH proxmox 8/9] access-control: add API token policy type with expiry checks
  2026-09-23 20:59 18% ` [PATCH proxmox 8/9] access-control: add API token policy type with expiry checks Thomas Lamprecht
@ 2026-11-10 15:05  4%   ` Shannon Sterz
  0 siblings, 0 replies; 17+ results
From: Shannon Sterz @ 2026-11-10 15:05 UTC (permalink / raw)
  To: Thomas Lamprecht, pve-devel

On Wed Sep 23, 2026 at 10:59 PM CEST, Thomas Lamprecht wrote:
> 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 changing 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 none is
> enforced. The check is meant to be called only with an expiration
> date an operation actually sets or changes, existing tokens stay
> valid on purpose, so opting into a policy does not invalidate already
> deployed tokens. Only the expiry-related settings are ported, tokens
> in this stack always use separate ACLs, so PVE's privilege
> separation setting only becomes relevant once it moves over to
> this implementation.
>
> Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
> ---
>  proxmox-access-control/src/init.rs  |  15 ++
>  proxmox-access-control/src/types.rs | 227 ++++++++++++++++++++++++++++
>  2 files changed, 242 insertions(+)
>
> diff --git a/proxmox-access-control/src/init.rs b/proxmox-access-control/src/init.rs
> index 52c3393a..b8bcdafd 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,19 @@ 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.
> +    ///
> +    /// Existing tokens are deliberately never re-validated against a policy, so enabling one
> +    /// does not invalidate already deployed tokens. 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.
> +    ///
> +    /// 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..7fef5adc 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,82 @@ pub struct TokenApiEntry {
>      pub token: ApiToken,
>  }
>
> +#[api(
> +    properties: {
> +        "require-expiry": {
> +            optional: true,
> +            default: false,
> +        },
> +        "max-lifetime": {
> +            optional: true,
> +            minimum: 1,
> +        },
> +        "disallow-expiry-changes": {
> +            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.
> +///
> +/// The policy is enforced when API tokens are created or updated only, existing tokens are
> +/// deliberately not affected, 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<i64>,

nit: the above already sets `minimum: 1`, this could probably be `u64`.

> +
> +    /// Disallow changing the expiration date of existing API tokens, so that `max-lifetime`
> +    /// cannot be circumvented by extending tokens repeatedly. Such tokens can still be deleted
> +    /// and recreated.
> +    #[serde(default, skip_serializing_if = "Option::is_none")]
> +    pub disallow_expiry_changes: Option<bool>,

see my notes on the perl version of this patch

> +}
> +
> +impl TokenPolicy {
> +    /// Check a new or changed token expiration date against the policy.
> +    ///
> +    /// Must only be called when an operation actually sets or changes the expiration date, with
> +    /// an `expire` of 0 meaning no expiration date. This lets callers enforce the policy only for
> +    /// the expiration date an operation sets, so unrelated updates do not retroactively reject
> +    /// tokens that predate the policy. `is_update` distinguishes updating an existing token from
> +    /// creating a new one, `now` is the reference time the maximum lifetime is bound against.
> +    pub fn check_expiry_change(&self, expire: i64, is_update: bool, now: i64) -> Result<(), Error> {
> +        if is_update && self.disallow_expiry_changes.unwrap_or(false) {
> +            bail!(
> +                "the token policy does not allow changing the expiration date of an existing token"
> +            );
> +        }
> +
> +        // a token that never expires trivially exceeds any finite maximum lifetime, so a set
> +        // maximum lifetime also requires an expiration date
> +        if expire == 0 && (self.require_expiry.unwrap_or(false) || self.max_lifetime.is_some()) {

nit: should probably use `unwrap_or_default`

> +            bail!("the token policy requires an expiration date");
> +        }
> +
> +        if let Some(max_lifetime) = self.max_lifetime {
> +            // an extreme configured lifetime must not overflow, which panics in debug builds and
> +            // wraps into a bound rejecting everything otherwise
> +            if expire > 0 && expire > now.saturating_add(max_lifetime) {

nit: the `expire > 0` seems redundant now + max_lifetime should always
be a positive value afaict, so if that's true `expire > 0` holds
trivially. `expire == 0` is also checked above.

> +                bail!(
> +                    "the expiration date exceeds the maximum token lifetime of {max_lifetime} \
> +                     seconds set by the token policy"
> +                );
> +            }
> +        }
> +
> +        Ok(())
> +    }
> +}
> +
>  #[api(
>      properties: {
>          userid: {
> @@ -316,3 +393,153 @@ 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;
> +
> +    const EMPTY: TokenPolicy = TokenPolicy {
> +        require_expiry: None,
> +        max_lifetime: None,
> +        disallow_expiry_changes: None,
> +    };
> +
> +    const REQUIRE_EXPIRY: TokenPolicy = TokenPolicy {
> +        require_expiry: Some(true),
> +        ..EMPTY
> +    };
> +
> +    const MAX_LIFETIME: TokenPolicy = TokenPolicy {
> +        max_lifetime: Some(MAX),
> +        ..EMPTY
> +    };
> +
> +    const FIXED_EXPIRY: TokenPolicy = TokenPolicy {
> +        disallow_expiry_changes: Some(true),
> +        ..EMPTY
> +    };
> +
> +    #[test]
> +    fn empty_policy_allows_everything() {
> +        assert!(EMPTY.check_expiry_change(0, false, NOW).is_ok());
> +        assert!(EMPTY.check_expiry_change(NOW + 100, false, NOW).is_ok());
> +        assert!(EMPTY.check_expiry_change(0, true, NOW).is_ok());
> +    }
> +
> +    #[test]
> +    fn require_expiry() {
> +        assert!(REQUIRE_EXPIRY.check_expiry_change(0, false, NOW).is_err());
> +        assert!(
> +            REQUIRE_EXPIRY
> +                .check_expiry_change(NOW + 100, false, NOW)
> +                .is_ok()
> +        );
> +        // an update removing the expiration date is a change and gets rejected as well
> +        assert!(REQUIRE_EXPIRY.check_expiry_change(0, true, NOW).is_err());
> +        // while a compliant expiration date change on update stays allowed
> +        assert!(
> +            REQUIRE_EXPIRY
> +                .check_expiry_change(NOW + 100, true, NOW)
> +                .is_ok()
> +        );
> +    }
> +
> +    #[test]
> +    fn max_lifetime_implies_require_expiry() {
> +        assert!(MAX_LIFETIME.check_expiry_change(0, false, NOW).is_err());
> +        let explicitly_not_required = TokenPolicy {
> +            require_expiry: Some(false),
> +            ..MAX_LIFETIME
> +        };
> +        assert!(
> +            explicitly_not_required
> +                .check_expiry_change(0, false, NOW)
> +                .is_err()
> +        );
> +    }
> +
> +    #[test]
> +    fn max_lifetime_bounds() {
> +        assert!(
> +            MAX_LIFETIME
> +                .check_expiry_change(NOW + 100, false, NOW)
> +                .is_ok()
> +        );
> +        assert!(
> +            MAX_LIFETIME
> +                .check_expiry_change(NOW + MAX, false, NOW)
> +                .is_ok()
> +        );
> +        assert!(
> +            MAX_LIFETIME
> +                .check_expiry_change(NOW + MAX + 1, false, NOW)
> +                .is_err()
> +        );
> +        // prolonging past the bound on update is rejected just the same
> +        assert!(
> +            MAX_LIFETIME
> +                .check_expiry_change(NOW + MAX + 1, true, NOW)
> +                .is_err()
> +        );
> +        // an expiration date in the past is odd, but within any bound
> +        assert!(
> +            MAX_LIFETIME
> +                .check_expiry_change(NOW - 100, false, NOW)
> +                .is_ok()
> +        );
> +        // prolonging within the bound on update stays allowed
> +        assert!(
> +            MAX_LIFETIME
> +                .check_expiry_change(NOW + 100, true, NOW)
> +                .is_ok()
> +        );
> +    }
> +
> +    #[test]
> +    fn extreme_max_lifetime_does_not_overflow() {
> +        let policy = TokenPolicy {
> +            max_lifetime: Some(i64::MAX),
> +            ..EMPTY
> +        };
> +        assert!(policy.check_expiry_change(NOW + 100, false, NOW).is_ok());
> +        assert!(policy.check_expiry_change(i64::MAX, false, NOW).is_ok());
> +    }
> +
> +    #[test]
> +    fn disallow_expiry_changes() {
> +        // any change on update is rejected: prolonging, shortening and removal
> +        assert!(
> +            FIXED_EXPIRY
> +                .check_expiry_change(NOW + 100, true, NOW)
> +                .is_err()
> +        );
> +        assert!(
> +            FIXED_EXPIRY
> +                .check_expiry_change(NOW - 100, true, NOW)
> +                .is_err()
> +        );
> +        assert!(FIXED_EXPIRY.check_expiry_change(0, true, NOW).is_err());
> +        // creation is unaffected, with or without an expiration date
> +        assert!(
> +            FIXED_EXPIRY
> +                .check_expiry_change(NOW + 100, false, NOW)
> +                .is_ok()
> +        );
> +        assert!(FIXED_EXPIRY.check_expiry_change(0, false, NOW).is_ok());
> +    }
> +
> +    #[test]
> +    fn disallow_expiry_changes_wins_over_compliant_expiry() {
> +        let policy = TokenPolicy {
> +            require_expiry: Some(true),
> +            disallow_expiry_changes: Some(true),
> +            ..EMPTY
> +        };
> +        assert!(policy.check_expiry_change(NOW + 100, true, NOW).is_err());
> +        assert!(policy.check_expiry_change(NOW + 100, false, NOW).is_ok());
> +    }
> +}





^ permalink raw reply	[relevance 4%]

* Re: [PATCH cluster 1/9] datacenter config: add token-policy option
  2026-09-23 20:59 19% ` [PATCH cluster 1/9] datacenter config: add token-policy option Thomas Lamprecht
@ 2026-11-10 15:05  6%   ` Shannon Sterz
  0 siblings, 0 replies; 17+ results
From: Shannon Sterz @ 2026-11-10 15:05 UTC (permalink / raw)
  To: Thomas Lamprecht, pve-devel

On Wed Sep 23, 2026 at 10:59 PM CEST, Thomas Lamprecht wrote:
> Compliance rules like PCI DSS, SOC 2, or ISO 27001 commonly mandate
> bounded credential lifetimes, but without a central policy every
> token creator must remember to set an expiration date manually.
>
> Add an optional cluster-wide policy that can require an expiration
> date, bound the maximum token lifetime, forbid changing the expiration
> date of existing tokens, and require privilege separation for API
> tokens. It is enforced by pve-access-control on token creation and
> update only; existing tokens deliberately stay untouched, so opting in
> does not invalidate already deployed tokens, and (by default)
> prolonging a token within the bounds stays possible as a deliberate
> act (see #7805).
>
> Note that an unparsable policy is dropped with a warning and the rest
> of datacenter.cfg still loads, the same as for every other property
> string here, so a typo leaves tokens unrestricted rather than locked
> down.
>
> Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
> ---
>  src/PVE/DataCenterConfig.pm   | 51 +++++++++++++++++++++++++
>  src/test/Makefile             |  6 ++-
>  src/test/test_token_policy.pl | 72 +++++++++++++++++++++++++++++++++++
>  3 files changed, 128 insertions(+), 1 deletion(-)
>  create mode 100644 src/test/test_token_policy.pl
>
> diff --git a/src/PVE/DataCenterConfig.pm b/src/PVE/DataCenterConfig.pm
> index 004122e..a01ef47 100644
> --- a/src/PVE/DataCenterConfig.pm
> +++ b/src/PVE/DataCenterConfig.pm
> @@ -268,6 +268,41 @@ my $webauthn_format = {
>      },
>  };
>
> +my $token_policy_format = {
> +    'require-expiry' => {
> +        type => 'boolean',
> +        optional => 1,
> +        default => 0,
> +        description => "Require an expiration date for new API tokens and when changing the"
> +            . " expiration date of existing ones.",
> +    },
> +    'max-lifetime' => {
> +        type => 'integer',
> +        optional => 1,
> +        minimum => 1,
> +        format_description => 'seconds',
> +        description => "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'.",
> +    },
> +    'disallow-expiry-changes' => {
> +        type => 'boolean',
> +        optional => 1,
> +        default => 0,
> +        description => "Disallow changing the expiration date of existing API tokens, so that"
> +            . " 'max-lifetime' cannot be circumvented by extending tokens repeatedly. Such"
> +            . " tokens can still be deleted and recreated.",

currently this also seems to disallow setting an expiry for old tokens
or shortening the lifetime of an existing token with a pre-existing
expiry. while this may be intentional, id argue this makes compliance
less convenient to achieve.

auditors may want an admin to set an expiry asap on a token without one.
this option would allow only removing the old token and creating a new
one as an option. creating a new token with specific permissions may be
cumbersome.

since there is no downside to shortening a token lifetime, im not sure
what the value here is. especially if we do decide to allow lifetime
extensions by secret regeneration.

the rational here also only talks about avoid lifetime extension, so at
the very least it should maybe also mention why lifetime shortening is
also disallowed.

> +    },
> +    'require-privilege-separation' => {
> +        type => 'boolean',
> +        optional => 1,
> +        default => 0,
> +        description => "Require privilege separation for new API tokens and when changing that"
> +            . " setting on existing ones, that is, disallow tokens with the full privileges of"
> +            . " their user.",
> +    },
> +};
> +
>  PVE::JSONSchema::register_format('mac-prefix', \&pve_verify_mac_prefix);
>
>  sub pve_verify_mac_prefix {
> @@ -510,6 +545,13 @@ my $datacenter_schema = {
>              format => $webauthn_format,
>              description => 'webauthn configuration',
>          },
> +        'token-policy' => {
> +            optional => 1,
> +            type => 'string',
> +            format => $token_policy_format,
> +            description => "Cluster-wide policy for creating and updating API tokens, for"
> +                . " example to enforce an expiration date or privilege separation.",
> +        },
>          description => {
>              type => 'string',
>              description =>
> @@ -614,6 +656,10 @@ sub parse_datacenter_config {
>          $res->{webauthn} = parse_property_string($webauthn_format, $webauthn);
>      }
>
> +    if (my $token_policy = $res->{'token-policy'}) {
> +        $res->{'token-policy'} = parse_property_string($token_policy_format, $token_policy);
> +    }
> +
>      if (my $tag_style = $res->{'tag-style'}) {
>          $res->{'tag-style'} = parse_property_string($tag_style_format, $tag_style);
>      }
> @@ -707,6 +753,11 @@ sub write_datacenter_config {
>          $cfg->{webauthn} = PVE::JSONSchema::print_property_string($webauthn, $webauthn_format);
>      }
>
> +    if (ref(my $token_policy = $cfg->{'token-policy'})) {
> +        $cfg->{'token-policy'} =
> +            PVE::JSONSchema::print_property_string($token_policy, $token_policy_format);
> +    }
> +
>      if (ref(my $tag_style = $cfg->{'tag-style'})) {
>          $cfg->{'tag-style'} = PVE::JSONSchema::print_property_string($tag_style, $tag_style_format);
>      }
> diff --git a/src/test/Makefile b/src/test/Makefile
> index cdd37d0..3a47b8c 100644
> --- a/src/test/Makefile
> +++ b/src/test/Makefile
> @@ -4,7 +4,7 @@ cpgtest: cpgtest.c
>  	gcc -Wall cpgtest.c $(shell pkg-config --cflags --libs libcpg libqb) -o cpgtest
>
>  .PHONY: check install clean distclean
> -check: corosync-parser-test test-mac-prefix
> +check: corosync-parser-test test-mac-prefix test-token-policy
>
>  .PHONY: corosync-parser-test
>  corosync-parser-test:
> @@ -14,5 +14,9 @@ corosync-parser-test:
>  test-mac-prefix:
>  	perl test_mac_prefix.pl
>
> +.PHONY: test-token-policy
> +test-token-policy:
> +	perl test_token_policy.pl
> +
>  distclean: clean
>  clean:
> diff --git a/src/test/test_token_policy.pl b/src/test/test_token_policy.pl
> new file mode 100644
> index 0000000..269dc14
> --- /dev/null
> +++ b/src/test/test_token_policy.pl
> @@ -0,0 +1,72 @@
> +use strict;
> +use warnings;

small nit: this could just do `use v5.36` instead. the other test cases
could adopt this as well, but i won't mention it each time as it's
minor.

> +use Test::More;
> +
> +use lib ('.', '..');
> +
> +use PVE::DataCenterConfig;
> +
> +# the policy is a property string, so it has to survive a parse and write round trip and it must
> +# not accept values that the enforcing side would not be able to interpret
> +
> +my $parse = sub {
> +    my ($value) = @_;
> +    my $raw = defined($value) ? "token-policy: $value\n" : '';
> +    my $cfg = PVE::DataCenterConfig::parse_datacenter_config('datacenter.cfg',
> +        $raw . "keyboard: en-us\n");
> +    return $cfg;
> +};
> +
> +my $policy = $parse->('require-expiry=1,max-lifetime=86400')->{'token-policy'};
> +is($policy->{'require-expiry'}, 1, 'require-expiry is parsed');
> +is($policy->{'max-lifetime'}, 86400, 'max-lifetime is parsed');
> +
> +$policy = $parse->('disallow-expiry-changes=1,require-privilege-separation=1')->{'token-policy'};
> +is($policy->{'disallow-expiry-changes'}, 1, 'disallow-expiry-changes is parsed');
> +is($policy->{'require-privilege-separation'}, 1, 'require-privilege-separation is parsed');
> +
> +is($parse->(undef)->{'token-policy'}, undef, 'an absent token-policy is not invented');
> +
> +# an unusable policy has to be dropped, never half applied, and must not take the rest of the
> +# configuration down with it
> +for my $invalid (
> +    'max-lifetime=0',
> +    'max-lifetime=-1',
> +    'max-lifetime=forever',
> +    'require-expiry=maybe',
> +    'unknown-key=1',
> +) {
> +    my $cfg;
> +    {
> +        local $SIG{__WARN__} = sub { };
> +        $cfg = $parse->($invalid);
> +    }
> +    is($cfg->{'token-policy'}, undef, "'$invalid' does not yield a policy");
> +    is($cfg->{keyboard}, 'en-us', "'$invalid' does not break the rest of the config");
> +}
> +
> +# writing has to turn the parsed hash back into the property string
> +my $raw = PVE::DataCenterConfig::write_datacenter_config(
> +    'datacenter.cfg',
> +    {
> +        'token-policy' => {
> +            'require-expiry' => 1,
> +            'max-lifetime' => 86400,
> +        },
> +    },
> +);
> +like(
> +    $raw,
> +    qr/^token-policy:\s*(require-expiry=1,max-lifetime=86400|max-lifetime=86400,require-expiry=1)$/m,
> +    'the policy is written back as a property string',
> +);
> +
> +my $round_tripped = PVE::DataCenterConfig::parse_datacenter_config('datacenter.cfg', $raw);
> +is_deeply(
> +    $round_tripped->{'token-policy'},
> +    { 'require-expiry' => 1, 'max-lifetime' => 86400 },
> +    'the policy survives a write and parse round trip',
> +);
> +
> +done_testing();





^ permalink raw reply	[relevance 6%]

* Re: [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy
  2026-09-23 20:59 17% [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
                   ` (2 preceding siblings ...)
  2026-09-23 20:59 18% ` [PATCH proxmox 8/9] access-control: add API token policy type with expiry checks Thomas Lamprecht
@ 2026-11-10 15:05 12% ` Shannon Sterz
  2026-11-10 15:28  8%   ` Thomas Lamprecht
  2026-11-15 23:38  8% ` superseded: " Thomas Lamprecht
  4 siblings, 1 reply; 17+ results
From: Shannon Sterz @ 2026-11-10 15:05 UTC (permalink / raw)
  To: Thomas Lamprecht, pve-devel

On Wed Sep 23, 2026 at 10:59 PM CEST, Thomas Lamprecht wrote:
> Compliance rules like PCI DSS, SOC 2, or ISO 27001 often require
> that credentials have a limited lifetime, but there is no central way
> to enforce that for API tokens.
>
> Add an optional token-policy option to datacenter.cfg to require an
> expiration date, limit the maximum token lifetime, forbid changing
> the expiration date of existing tokens, and require privilege
> separation.
>
> The policy is only checked when a token is created or updated, and
> only for values that actually change, so existing tokens stay valid even
> if their lifetime exceeds a newly configured maximum one.
> Extending the expiration date within the limit stays possible, unless
> the opt-in 'disallow-expiry-changes' switch is set (see [0] for the
> rationale).
>
> The web UI exposes these options under Datacenter -> Options and
> adjusts the token dialogs to the policy. Changing the policy requires
> Sys.Modify on '/', like any other datacenter option; an extra
> auth-specific privilege check was skipped for now, for the current
> built-in roles it would land in the same roles as Sys.Modify, adding new
> built-in roles here is IMO scope creep and this can still be done later
> (with some more thoughts on how to handle all these datacenter options).
>
> FWIW, the first manager patch (4/9 overall) fixes a pre-existing issue
> w.r.t. only submitting the expiration date when changed, which the
> policy checks would expose more often, but it'd also make sense on its
> own and could be applied independently already.
>
> The last two patches port the backend part to the common rust stack, so
> PBS and PDM can opt in through their AccessControlConfig, and to prepare
> moving pve-access-control over to rust later. Only the expiry parts
> apply there, tokens in the rust stack always use separate ACLs, i.e. no
> sharing with the underlying users there.
>
> Dependencies: access-control needs the cluster patch, manager needs
> both, and building manager needs the pve-doc-generator with the new
> online-help anchor from the docs patch (or ALLOW_MISSING=1), which is
> why the docs patch comes before the manager ones; the proxmox patches
> are independent. d/control needs the respective versioned dependency
> bumps added on applying, and the generated datacenter option reference
> in pve-docs needs the usual make update once the cluster side is
> packaged.
>
> [0]: https://bugzilla.proxmox.com/show_bug.cgi?id=7805

Hi,

one high level question: If I didn't miss anything, adding a token
policy would break compatibility with PDM to an extend, since its wizard
doesn't currently set any expiry. This is mostly relevant when using
PDM's wizard for adding remotes and manually adding a token as a
workaround should still work, but an expiry policy makes this
cumbersome.

A nice follow up here might be adding an option that automatically set
the current max token lifetime as the expiry. PDM could also be taught
to rotate token secrets automatically somewhat analogously to my TLS
certificate rotation series. For that an option to allow expiry
extension on secret rotation only would be useful.

IMO, the security impact of allowing an extension when the secret is
regenerated is essentially 0 as creating a new token with a long expiry
as is left for the old token is always possible. It would also encourage
setting less broad permissions as they don't have to be re-added every
time the token expires.

What do you think?






^ permalink raw reply	[relevance 12%]

* [PATCH access-control 2/9] fix #7805: api: token: enforce datacenter token policy
  2026-09-23 20:59 17% [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
  2026-09-23 20:59 19% ` [PATCH cluster 1/9] datacenter config: add token-policy option Thomas Lamprecht
@ 2026-09-23 20:59 25% ` Thomas Lamprecht
  2026-09-23 20:59 18% ` [PATCH proxmox 8/9] access-control: add API token policy type with expiry checks Thomas Lamprecht
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 17+ results
From: Thomas Lamprecht @ 2026-09-23 20:59 UTC (permalink / raw)
  To: pve-devel

Check the new datacenter.cfg token-policy option on API token
creation and update, so admins can centrally require expiration
dates, bound the maximum token lifetime, forbid changing existing
expiration dates, and require privilege separation, as commonly
mandated by compliance rules like PCI DSS, SOC 2, or ISO 27001.

Existing tokens stay valid, and an update only checks settings it
actually changes, so unrelated edits or clients resubmitting
unchanged fields are not rejected for tokens that predate the policy.
The check runs before the secret is generated to avoid leaving an
orphaned entry in token.cfg on rejection. Regenerating the secret of
an existing token is deliberately not restricted, rotation does not
extend validity and blocking it would only discourage rotating old
credentials.

Changing the policy itself requires Sys.Modify on '/', like any
other datacenter option. An extra auth-specific privilege check was
skipped for now, for the current built-in roles it would land in the
same roles as Sys.Modify anyway, and anyone allowed to change
datacenter options can adapt the policy in any case.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
 src/PVE/API2/User.pm              |  32 ++++-
 src/PVE/AccessControl.pm          |  59 ++++++++
 src/test/Makefile                 |   2 +
 src/test/token-policy-api-test.pl | 102 ++++++++++++++
 src/test/token-policy-test.pl     | 217 ++++++++++++++++++++++++++++++
 5 files changed, 409 insertions(+), 3 deletions(-)
 create mode 100644 src/test/token-policy-api-test.pl
 create mode 100644 src/test/token-policy-test.pl

diff --git a/src/PVE/API2/User.pm b/src/PVE/API2/User.pm
index 579783b..0155b6b 100644
--- a/src/PVE/API2/User.pm
+++ b/src/PVE/API2/User.pm
@@ -806,14 +806,20 @@ __PACKAGE__->register_method({
             die "Token already exists.\n"
                 if defined(PVE::AccessControl::check_token_exist($usercfg, $userid, $tokenid, 1));
 
-            $full_tokenid = PVE::AccessControl::join_tokenid($userid, $tokenid);
-            $value = PVE::TokenConfig::generate_token($full_tokenid);
-
             $token = {};
             $token->{privsep} = defined($param->{privsep}) ? $param->{privsep} : 1;
             $token->{expire} = $param->{expire} if defined($param->{expire});
             $token->{comment} = $param->{comment} if $param->{comment};
 
+            # check policy before generating the secret to avoid leaving an orphan in token.cfg
+            PVE::AccessControl::assert_token_policy({
+                expire => $token->{expire} // 0,
+                'privilege-separation' => $token->{privsep},
+            });
+
+            $full_tokenid = PVE::AccessControl::join_tokenid($userid, $tokenid);
+            $value = PVE::TokenConfig::generate_token($full_tokenid);
+
             $usercfg->{users}->{$userid}->{tokens}->{$tokenid} = $token;
             cfs_write_file("user.cfg", $usercfg);
         };
@@ -899,11 +905,31 @@ __PACKAGE__->register_method({
                 $usercfg = cfs_read_file("user.cfg");
                 $token = PVE::AccessControl::check_token_exist($usercfg, $userid, $tokenid);
 
+                my $old_expire = $token->{expire} // 0;
+                my $old_privilege_separation = $token->{privsep} // 0;
+
                 $token->{privsep} = $param->{privsep} if defined($param->{privsep});
                 $token->{expire} = $param->{expire} if defined($param->{expire});
                 $token->{comment} = $param->{comment} if defined($param->{comment});
                 delete $token->{comment} if (!length $token->{comment});
 
+                my $new_expire = $token->{expire} // 0;
+                my $new_privilege_separation = $token->{privsep} // 0;
+
+                # enforce the policy only on the dimensions this update actually changes, so
+                # unrelated edits (or a client that resubmits unchanged fields) do not
+                # retroactively reject tokens that predate the policy
+                my $expire_change = $new_expire != $old_expire ? $new_expire : undef;
+                my $privilege_separation_change =
+                    $new_privilege_separation != $old_privilege_separation
+                    ? $new_privilege_separation
+                    : undef;
+                PVE::AccessControl::assert_token_policy({
+                    expire => $expire_change,
+                    'privilege-separation' => $privilege_separation_change,
+                    'is-update' => 1,
+                });
+
                 my $deletable = {
                     comment => 1,
                 };
diff --git a/src/PVE/AccessControl.pm b/src/PVE/AccessControl.pm
index 8879ab8..48e02cb 100644
--- a/src/PVE/AccessControl.pm
+++ b/src/PVE/AccessControl.pm
@@ -21,6 +21,7 @@ use PVE::OTP;
 use PVE::Ticket;
 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
+use PVE::DataCenterConfig; # ensure the 'datacenter.cfg' cfs parser is registered
 use PVE::JSONSchema qw(register_standard_option get_standard_option);
 
 use PVE::RS::TFA;
@@ -716,6 +717,64 @@ sub check_token_exist {
     return undef;
 }
 
+# Assert that a token's expiration and privilege-separation setting conform to the cluster-wide
+# token policy from datacenter.cfg. Dies with a descriptive message on violation.
+#
+# Takes a hash reference with the following keys:
+# - expire: the effective expiration date (epoch seconds, 0 == never); undef skips all
+#   expiration-related checks
+# - privilege-separation: the effective privilege separation flag; undef skips that dimension
+# - is-update: whether an existing token is updated; with 'disallow-expiry-changes' configured,
+#   any passed (i.e. actually changed) expiration date is then rejected outright
+# - ctime, policy: override the reference time to bound the expiration date against and the
+#   policy from the datacenter config, mainly for testing
+#
+# The checks are independent per dimension and only run for values that are actually passed. This
+# lets callers enforce a dimension only when the current operation sets it, so unrelated updates
+# (e.g. a comment change) do not retroactively reject tokens that predate the policy.
+sub assert_token_policy {
+    my ($param) = @_;
+
+    # integer-typed API parameters keep their submitted string spelling, and zero spellings
+    # like '00', '+0', or '-0' are true as Perl scalars, so numify to not mistake them for a
+    # set expiration date in the truthiness checks below
+    my $expire = defined($param->{expire}) ? int($param->{expire}) : undef;
+    my $privilege_separation = $param->{'privilege-separation'};
+
+    return if !defined($expire) && !defined($privilege_separation);
+
+    my $policy = $param->{policy} // cfs_read_file('datacenter.cfg')->{'token-policy'};
+    return if !$policy;
+
+    if (defined($expire)) {
+        die "the datacenter token policy does not allow changing the expiration date of an"
+            . " existing token\n"
+            if $param->{'is-update'} && $policy->{'disallow-expiry-changes'};
+
+        my $ctime = $param->{ctime} // time();
+        my $max_lifetime = $policy->{'max-lifetime'};
+        # a token that never expires trivially exceeds any finite maximum lifetime, so a set
+        # maximum lifetime also requires an expiration date
+        my $require_expiry = $policy->{'require-expiry'} || $max_lifetime;
+
+        die "the datacenter token policy requires an expiration date\n"
+            if $require_expiry && !$expire;
+
+        if ($max_lifetime && $expire && $expire > $ctime + $max_lifetime) {
+            die "the expiration date exceeds the maximum token lifetime of $max_lifetime seconds"
+                . " set by the datacenter token policy\n";
+        }
+    }
+
+    if (
+        defined($privilege_separation)
+        && $policy->{'require-privilege-separation'}
+        && !$privilege_separation
+    ) {
+        die "the datacenter token policy requires privilege separation\n";
+    }
+}
+
 # deprecated
 sub verify_one_time_pw {
     my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
diff --git a/src/test/Makefile b/src/test/Makefile
index 53f2da7..51db8cb 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -13,4 +13,6 @@ check:
 	perl -I.. perm-test7.pl
 	perl -I.. perm-test8.pl
 	perl -I.. realm_sync_test.pl
+	perl -I.. token-policy-test.pl
+	perl -I.. token-policy-api-test.pl
 	perl -I.. api-tests.pl
diff --git a/src/test/token-policy-api-test.pl b/src/test/token-policy-api-test.pl
new file mode 100644
index 0000000..dece4db
--- /dev/null
+++ b/src/test/token-policy-api-test.pl
@@ -0,0 +1,102 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More;
+use Test::MockModule;
+
+use PVE::AccessControl;
+use PVE::API2::User;
+
+# Exercise the token create and update API handlers with the real schema validation and user
+# config parser/writer, mocking out the cluster file system and secret generation. The integer
+# schema accepts zero spellings like '00', '+0', or '-0' without canonicalizing them, so the
+# policy enforcement at the API boundary must not mistake them for a set expiration date.
+
+my ($policy, $user_cfg_raw, $secret_calls);
+
+my $read = sub {
+    my ($file) = @_;
+    return PVE::AccessControl::parse_user_config($file, $user_cfg_raw) if $file eq 'user.cfg';
+    return { 'token-policy' => $policy } if $file eq 'datacenter.cfg';
+    die "unexpected cfs_read_file('$file') call\n";
+};
+
+my $access_control_module = Test::MockModule->new('PVE::AccessControl');
+$access_control_module->mock(cfs_read_file => $read);
+$access_control_module->mock(lock_user_config => sub { $_[0]->() });
+
+my $api_user_module = Test::MockModule->new('PVE::API2::User');
+$api_user_module->mock(cfs_read_file => $read);
+$api_user_module->mock(
+    cfs_write_file => sub {
+        my ($file, $cfg) = @_;
+        die "unexpected cfs_write_file('$file') call\n" if $file ne 'user.cfg';
+        $user_cfg_raw = PVE::AccessControl::write_user_config($file, $cfg);
+    },
+);
+
+my $token_config_module = Test::MockModule->new('PVE::TokenConfig');
+$token_config_module->mock(
+    generate_token => sub {
+        $secret_calls++;
+        return 'test-secret';
+    },
+);
+
+my $reset = sub {
+    my ($test_policy, $expire) = @_;
+    $policy = $test_policy;
+    $user_cfg_raw = "user:test\@pve:1:0::::::\n";
+    $user_cfg_raw .= "token:test\@pve!old:$expire:1:some comment:\n" if defined($expire);
+    $secret_calls = 0;
+};
+
+my $invoke = sub {
+    my ($method, $param) = @_;
+    my $ok = eval {
+        PVE::API2::User->$method({ userid => 'test@pve', %$param });
+        1;
+    };
+    return ($ok, $@);
+};
+
+my $now = time();
+
+for my $policy_variant ({ 'require-expiry' => 1 }, { 'max-lifetime' => 86400 }) {
+    my $desc = join(',', map { "$_=$policy_variant->{$_}" } sort keys $policy_variant->%*);
+
+    for my $zero ('0', '00', '+0', '-0') {
+        $reset->($policy_variant);
+        my ($ok, $err) = $invoke->('generate_token', { tokenid => 'new', expire => $zero });
+        ok(
+            !$ok && $err =~ /requires an expiration date/,
+            "$desc: create with expire=$zero rejected",
+        );
+        is($secret_calls, 0, "$desc: rejected create generates no secret");
+        ok($user_cfg_raw !~ /!new/, "$desc: rejected create writes no token");
+
+        $reset->($policy_variant, $now + 600);
+        my $before = $user_cfg_raw;
+        ($ok, $err) =
+            $invoke->('update_token_info', { tokenid => 'old', expire => $zero, regenerate => 1 });
+        ok(
+            !$ok && $err =~ /requires an expiration date/, "$desc: update to expire=$zero rejected",
+        );
+        is($secret_calls, 0, "$desc: rejected update rotates no secret");
+        is($user_cfg_raw, $before, "$desc: rejected update writes nothing");
+    }
+
+    $reset->($policy_variant);
+    my ($ok, $err) = $invoke->('generate_token', { tokenid => 'new', expire => $now + 600 });
+    ok($ok, "$desc: compliant create accepted") or diag($err);
+    is($secret_calls, 1, "$desc: accepted create generates a secret");
+}
+
+# unrelated updates of a token that predates the policy must keep working
+$reset->({ 'require-expiry' => 1 }, 0);
+my ($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', comment => 'changed' });
+ok($ok, 'unrelated update of a non-conforming token stays allowed') or diag($err);
+
+done_testing();
diff --git a/src/test/token-policy-test.pl b/src/test/token-policy-test.pl
new file mode 100644
index 0000000..f4c8fa5
--- /dev/null
+++ b/src/test/token-policy-test.pl
@@ -0,0 +1,217 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More;
+use Test::MockModule;
+
+use PVE::AccessControl;
+
+# tests pass the policy explicitly; keep the fallback read of datacenter.cfg from hitting a
+# real pmxcfs so the cases without a policy exercise that path against an empty config
+my $access_control_module = Test::MockModule->new('PVE::AccessControl');
+$access_control_module->mock(
+    cfs_read_file => sub {
+        my ($file) = @_;
+        die "unexpected cfs_read_file('$file') call\n" if $file ne 'datacenter.cfg';
+        return {};
+    },
+);
+
+# fixed reference time and a 90-day maximum lifetime for deterministic bounds checks
+my $now = 1_000_000_000;
+my $max = 90 * 24 * 60 * 60; # 7776000 seconds
+
+# assert_token_policy({...}) dies on a policy violation. The 'expire' and
+# 'privilege-separation' keys may be undef to skip that dimension (used for partial updates);
+# 'is-update' marks an update of an existing token (relevant for 'disallow-expiry-changes').
+sub check {
+    my ($desc, $policy, $param, $should_die) = @_;
+
+    my $err;
+    eval {
+        PVE::AccessControl::assert_token_policy({
+            ctime => $now,
+            policy => $policy,
+            $param->%*,
+        });
+        1;
+    } or $err = $@;
+
+    if ($should_die) {
+        ok($err, "$desc: rejected") or diag("expected rejection but call succeeded");
+    } else {
+        ok(!$err, "$desc: accepted") or diag("unexpected rejection: $err");
+    }
+}
+
+# no policy configured -> everything is allowed
+check(
+    'no policy, never-expiring full-priv token',
+    undef,
+    { expire => 0, 'privilege-separation' => 0 },
+    0,
+);
+check('no policy, undef dimensions', undef, {}, 0);
+check(
+    'empty policy, never-expiring full-priv token',
+    {},
+    { expire => 0, 'privilege-separation' => 0 },
+    0,
+);
+
+# require-expiry
+my $req_expire = { 'require-expiry' => 1 };
+check('require-expiry, no expiry', $req_expire, { expire => 0 }, 1);
+check('require-expiry, future expiry', $req_expire, { expire => $now + 100 }, 0);
+check('require-expiry, expiry dimension not touched', $req_expire, {}, 0);
+check(
+    'require-expiry, update removing the expiry',
+    $req_expire,
+    { expire => 0, 'is-update' => 1 },
+    1,
+);
+check(
+    'require-expiry, does not constrain privsep',
+    $req_expire,
+    { expire => $now + 100, 'privilege-separation' => 0 },
+    0,
+);
+
+# max-lifetime implies an expiry is required and bounds how far it may reach
+my $max_life = { 'max-lifetime' => $max };
+check('max-lifetime, never-expiring is rejected', $max_life, { expire => 0 }, 1);
+check('max-lifetime, within bound', $max_life, { expire => $now + 100 }, 0);
+check('max-lifetime, exactly at bound', $max_life, { expire => $now + $max }, 0);
+check('max-lifetime, one second past bound', $max_life, { expire => $now + $max + 1 }, 1);
+check('max-lifetime, expiry dimension not touched', $max_life, {}, 0);
+check(
+    'max-lifetime, update prolonging past the bound',
+    $max_life,
+    { expire => $now + $max + 1, 'is-update' => 1 },
+    1,
+);
+check('max-lifetime, expiry in the past accepted', $max_life, { expire => $now - 100 }, 0);
+check(
+    'max-lifetime with explicit require-expiry=0 still requires an expiry',
+    { 'require-expiry' => 0, 'max-lifetime' => $max },
+    { expire => 0 },
+    1,
+);
+
+# the integer schema passes zero spellings like '00' through with their submitted string
+# spelling, and those are true as Perl scalars; they must still count as "no expiration date"
+for my $zero ('0', '00', '+0', '-0') {
+    check("require-expiry, create with zero spelling '$zero'", $req_expire, { expire => $zero }, 1);
+    check(
+        "require-expiry, update removing the expiry via zero spelling '$zero'",
+        $req_expire,
+        { expire => $zero, 'is-update' => 1 },
+        1,
+    );
+    check("max-lifetime, create with zero spelling '$zero'", $max_life, { expire => $zero }, 1);
+}
+
+# disallow-expiry-changes rejects any changed expiration date on update, but neither the
+# initial expiration date on creation nor updates that leave the expiration date untouched
+my $fixed_expiry = { 'disallow-expiry-changes' => 1 };
+check(
+    'disallow-expiry-changes, update changing expiry',
+    $fixed_expiry,
+    { expire => $now + 100, 'is-update' => 1 },
+    1,
+);
+check(
+    'disallow-expiry-changes, update shortening expiry',
+    $fixed_expiry,
+    { expire => $now - 100, 'is-update' => 1 },
+    1,
+);
+check(
+    'disallow-expiry-changes, update removing expiry',
+    $fixed_expiry,
+    { expire => 0, 'is-update' => 1 },
+    1,
+);
+check('disallow-expiry-changes, update not touching expiry', $fixed_expiry, { 'is-update' => 1 },
+    0);
+check('disallow-expiry-changes, creation sets expiry', $fixed_expiry, { expire => $now + 100 }, 0);
+check('disallow-expiry-changes, creation without expiry', $fixed_expiry, { expire => 0 }, 0);
+check(
+    'disallow-expiry-changes, does not constrain privsep',
+    $fixed_expiry,
+    { 'privilege-separation' => 0, 'is-update' => 1 },
+    0,
+);
+check(
+    'disallow-expiry-changes wins over a compliant new expiry under require-expiry',
+    { 'disallow-expiry-changes' => 1, 'require-expiry' => 1 },
+    { expire => $now + 100, 'is-update' => 1 },
+    1,
+);
+
+# require-privilege-separation
+my $require_privilege_separation = { 'require-privilege-separation' => 1 };
+check(
+    'require-privilege-separation, full-priv token rejected',
+    $require_privilege_separation,
+    { 'privilege-separation' => 0 },
+    1,
+);
+check(
+    'require-privilege-separation, privsep token accepted',
+    $require_privilege_separation,
+    { 'privilege-separation' => 1 },
+    0,
+);
+check(
+    'require-privilege-separation, privsep dimension not touched',
+    $require_privilege_separation,
+    {},
+    0,
+);
+check(
+    'require-privilege-separation, does not constrain expiry',
+    $require_privilege_separation,
+    { expire => 0, 'privilege-separation' => 1 },
+    0,
+);
+
+# combined policy, as an admin would set for a compliance baseline
+my $full = { 'require-expiry' => 1, 'max-lifetime' => $max, 'require-privilege-separation' => 1 };
+check(
+    'full policy, compliant token',
+    $full,
+    { expire => $now + 100, 'privilege-separation' => 1 },
+    0,
+);
+check('full policy, missing expiry', $full, { expire => 0, 'privilege-separation' => 1 }, 1);
+check(
+    'full policy, expiry too far out',
+    $full,
+    { expire => $now + $max + 1, 'privilege-separation' => 1 },
+    1,
+);
+check(
+    'full policy, full-priv token',
+    $full,
+    { expire => $now + 100, 'privilege-separation' => 0 },
+    1,
+);
+# partial update: only the touched dimension is enforced (decision to not retroactively
+# reject tokens that predate the policy on unrelated edits)
+check(
+    'full policy, update touching only a valid expiry',
+    $full,
+    { expire => $now + 100, 'is-update' => 1 },
+    0,
+);
+check(
+    'full policy, update touching only privsep',
+    $full,
+    { 'privilege-separation' => 1, 'is-update' => 1 },
+    0,
+);
+
+done_testing();
-- 
2.47.3





^ permalink raw reply related	[relevance 25%]

* [PATCH proxmox 8/9] access-control: add API token policy type with expiry checks
  2026-09-23 20:59 17% [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
  2026-09-23 20:59 19% ` [PATCH cluster 1/9] datacenter config: add token-policy option Thomas Lamprecht
  2026-09-23 20:59 25% ` [PATCH access-control 2/9] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
@ 2026-09-23 20:59 18% ` Thomas Lamprecht
  2026-11-10 15:05  4%   ` Shannon Sterz
  2026-11-10 15:05 12% ` [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Shannon Sterz
  2026-11-15 23:38  8% ` superseded: " Thomas Lamprecht
  4 siblings, 1 reply; 17+ results
From: Thomas Lamprecht @ 2026-09-23 20:59 UTC (permalink / raw)
  To: pve-devel

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 changing 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 none is
enforced. The check is meant to be called only with an expiration
date an operation actually sets or changes, existing tokens stay
valid on purpose, so opting into a policy does not invalidate already
deployed tokens. Only the expiry-related settings are ported, tokens
in this stack always use separate ACLs, so PVE's privilege
separation setting only becomes relevant once it moves over to
this implementation.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
 proxmox-access-control/src/init.rs  |  15 ++
 proxmox-access-control/src/types.rs | 227 ++++++++++++++++++++++++++++
 2 files changed, 242 insertions(+)

diff --git a/proxmox-access-control/src/init.rs b/proxmox-access-control/src/init.rs
index 52c3393a..b8bcdafd 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,19 @@ 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.
+    ///
+    /// Existing tokens are deliberately never re-validated against a policy, so enabling one
+    /// does not invalidate already deployed tokens. 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.
+    ///
+    /// 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..7fef5adc 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,82 @@ pub struct TokenApiEntry {
     pub token: ApiToken,
 }
 
+#[api(
+    properties: {
+        "require-expiry": {
+            optional: true,
+            default: false,
+        },
+        "max-lifetime": {
+            optional: true,
+            minimum: 1,
+        },
+        "disallow-expiry-changes": {
+            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.
+///
+/// The policy is enforced when API tokens are created or updated only, existing tokens are
+/// deliberately not affected, 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<i64>,
+
+    /// Disallow changing the expiration date of existing API tokens, so that `max-lifetime`
+    /// cannot be circumvented by extending tokens repeatedly. Such tokens can still be deleted
+    /// and recreated.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub disallow_expiry_changes: Option<bool>,
+}
+
+impl TokenPolicy {
+    /// Check a new or changed token expiration date against the policy.
+    ///
+    /// Must only be called when an operation actually sets or changes the expiration date, with
+    /// an `expire` of 0 meaning no expiration date. This lets callers enforce the policy only for
+    /// the expiration date an operation sets, so unrelated updates do not retroactively reject
+    /// tokens that predate the policy. `is_update` distinguishes updating an existing token from
+    /// creating a new one, `now` is the reference time the maximum lifetime is bound against.
+    pub fn check_expiry_change(&self, expire: i64, is_update: bool, now: i64) -> Result<(), Error> {
+        if is_update && self.disallow_expiry_changes.unwrap_or(false) {
+            bail!(
+                "the token policy does not allow changing the expiration date of an existing token"
+            );
+        }
+
+        // a token that never expires trivially exceeds any finite maximum lifetime, so a set
+        // maximum lifetime also requires an expiration date
+        if expire == 0 && (self.require_expiry.unwrap_or(false) || self.max_lifetime.is_some()) {
+            bail!("the token policy requires an expiration date");
+        }
+
+        if let Some(max_lifetime) = self.max_lifetime {
+            // an extreme configured lifetime must not overflow, which panics in debug builds and
+            // wraps into a bound rejecting everything otherwise
+            if expire > 0 && expire > now.saturating_add(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 +393,153 @@ 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;
+
+    const EMPTY: TokenPolicy = TokenPolicy {
+        require_expiry: None,
+        max_lifetime: None,
+        disallow_expiry_changes: None,
+    };
+
+    const REQUIRE_EXPIRY: TokenPolicy = TokenPolicy {
+        require_expiry: Some(true),
+        ..EMPTY
+    };
+
+    const MAX_LIFETIME: TokenPolicy = TokenPolicy {
+        max_lifetime: Some(MAX),
+        ..EMPTY
+    };
+
+    const FIXED_EXPIRY: TokenPolicy = TokenPolicy {
+        disallow_expiry_changes: Some(true),
+        ..EMPTY
+    };
+
+    #[test]
+    fn empty_policy_allows_everything() {
+        assert!(EMPTY.check_expiry_change(0, false, NOW).is_ok());
+        assert!(EMPTY.check_expiry_change(NOW + 100, false, NOW).is_ok());
+        assert!(EMPTY.check_expiry_change(0, true, NOW).is_ok());
+    }
+
+    #[test]
+    fn require_expiry() {
+        assert!(REQUIRE_EXPIRY.check_expiry_change(0, false, NOW).is_err());
+        assert!(
+            REQUIRE_EXPIRY
+                .check_expiry_change(NOW + 100, false, NOW)
+                .is_ok()
+        );
+        // an update removing the expiration date is a change and gets rejected as well
+        assert!(REQUIRE_EXPIRY.check_expiry_change(0, true, NOW).is_err());
+        // while a compliant expiration date change on update stays allowed
+        assert!(
+            REQUIRE_EXPIRY
+                .check_expiry_change(NOW + 100, true, NOW)
+                .is_ok()
+        );
+    }
+
+    #[test]
+    fn max_lifetime_implies_require_expiry() {
+        assert!(MAX_LIFETIME.check_expiry_change(0, false, NOW).is_err());
+        let explicitly_not_required = TokenPolicy {
+            require_expiry: Some(false),
+            ..MAX_LIFETIME
+        };
+        assert!(
+            explicitly_not_required
+                .check_expiry_change(0, false, NOW)
+                .is_err()
+        );
+    }
+
+    #[test]
+    fn max_lifetime_bounds() {
+        assert!(
+            MAX_LIFETIME
+                .check_expiry_change(NOW + 100, false, NOW)
+                .is_ok()
+        );
+        assert!(
+            MAX_LIFETIME
+                .check_expiry_change(NOW + MAX, false, NOW)
+                .is_ok()
+        );
+        assert!(
+            MAX_LIFETIME
+                .check_expiry_change(NOW + MAX + 1, false, NOW)
+                .is_err()
+        );
+        // prolonging past the bound on update is rejected just the same
+        assert!(
+            MAX_LIFETIME
+                .check_expiry_change(NOW + MAX + 1, true, NOW)
+                .is_err()
+        );
+        // an expiration date in the past is odd, but within any bound
+        assert!(
+            MAX_LIFETIME
+                .check_expiry_change(NOW - 100, false, NOW)
+                .is_ok()
+        );
+        // prolonging within the bound on update stays allowed
+        assert!(
+            MAX_LIFETIME
+                .check_expiry_change(NOW + 100, true, NOW)
+                .is_ok()
+        );
+    }
+
+    #[test]
+    fn extreme_max_lifetime_does_not_overflow() {
+        let policy = TokenPolicy {
+            max_lifetime: Some(i64::MAX),
+            ..EMPTY
+        };
+        assert!(policy.check_expiry_change(NOW + 100, false, NOW).is_ok());
+        assert!(policy.check_expiry_change(i64::MAX, false, NOW).is_ok());
+    }
+
+    #[test]
+    fn disallow_expiry_changes() {
+        // any change on update is rejected: prolonging, shortening and removal
+        assert!(
+            FIXED_EXPIRY
+                .check_expiry_change(NOW + 100, true, NOW)
+                .is_err()
+        );
+        assert!(
+            FIXED_EXPIRY
+                .check_expiry_change(NOW - 100, true, NOW)
+                .is_err()
+        );
+        assert!(FIXED_EXPIRY.check_expiry_change(0, true, NOW).is_err());
+        // creation is unaffected, with or without an expiration date
+        assert!(
+            FIXED_EXPIRY
+                .check_expiry_change(NOW + 100, false, NOW)
+                .is_ok()
+        );
+        assert!(FIXED_EXPIRY.check_expiry_change(0, false, NOW).is_ok());
+    }
+
+    #[test]
+    fn disallow_expiry_changes_wins_over_compliant_expiry() {
+        let policy = TokenPolicy {
+            require_expiry: Some(true),
+            disallow_expiry_changes: Some(true),
+            ..EMPTY
+        };
+        assert!(policy.check_expiry_change(NOW + 100, true, NOW).is_err());
+        assert!(policy.check_expiry_change(NOW + 100, false, NOW).is_ok());
+    }
+}
-- 
2.47.3





^ permalink raw reply related	[relevance 18%]

* [PATCH cluster 1/9] datacenter config: add token-policy option
  2026-09-23 20:59 17% [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
@ 2026-09-23 20:59 19% ` Thomas Lamprecht
  2026-11-10 15:05  6%   ` Shannon Sterz
  2026-09-23 20:59 25% ` [PATCH access-control 2/9] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
                   ` (3 subsequent siblings)
  4 siblings, 1 reply; 17+ results
From: Thomas Lamprecht @ 2026-09-23 20:59 UTC (permalink / raw)
  To: pve-devel

Compliance rules like PCI DSS, SOC 2, or ISO 27001 commonly mandate
bounded credential lifetimes, but without a central policy every
token creator must remember to set an expiration date manually.

Add an optional cluster-wide policy that can require an expiration
date, bound the maximum token lifetime, forbid changing the expiration
date of existing tokens, and require privilege separation for API
tokens. It is enforced by pve-access-control on token creation and
update only; existing tokens deliberately stay untouched, so opting in
does not invalidate already deployed tokens, and (by default)
prolonging a token within the bounds stays possible as a deliberate
act (see #7805).

Note that an unparsable policy is dropped with a warning and the rest
of datacenter.cfg still loads, the same as for every other property
string here, so a typo leaves tokens unrestricted rather than locked
down.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
 src/PVE/DataCenterConfig.pm   | 51 +++++++++++++++++++++++++
 src/test/Makefile             |  6 ++-
 src/test/test_token_policy.pl | 72 +++++++++++++++++++++++++++++++++++
 3 files changed, 128 insertions(+), 1 deletion(-)
 create mode 100644 src/test/test_token_policy.pl

diff --git a/src/PVE/DataCenterConfig.pm b/src/PVE/DataCenterConfig.pm
index 004122e..a01ef47 100644
--- a/src/PVE/DataCenterConfig.pm
+++ b/src/PVE/DataCenterConfig.pm
@@ -268,6 +268,41 @@ my $webauthn_format = {
     },
 };
 
+my $token_policy_format = {
+    'require-expiry' => {
+        type => 'boolean',
+        optional => 1,
+        default => 0,
+        description => "Require an expiration date for new API tokens and when changing the"
+            . " expiration date of existing ones.",
+    },
+    'max-lifetime' => {
+        type => 'integer',
+        optional => 1,
+        minimum => 1,
+        format_description => 'seconds',
+        description => "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'.",
+    },
+    'disallow-expiry-changes' => {
+        type => 'boolean',
+        optional => 1,
+        default => 0,
+        description => "Disallow changing the expiration date of existing API tokens, so that"
+            . " 'max-lifetime' cannot be circumvented by extending tokens repeatedly. Such"
+            . " tokens can still be deleted and recreated.",
+    },
+    'require-privilege-separation' => {
+        type => 'boolean',
+        optional => 1,
+        default => 0,
+        description => "Require privilege separation for new API tokens and when changing that"
+            . " setting on existing ones, that is, disallow tokens with the full privileges of"
+            . " their user.",
+    },
+};
+
 PVE::JSONSchema::register_format('mac-prefix', \&pve_verify_mac_prefix);
 
 sub pve_verify_mac_prefix {
@@ -510,6 +545,13 @@ my $datacenter_schema = {
             format => $webauthn_format,
             description => 'webauthn configuration',
         },
+        'token-policy' => {
+            optional => 1,
+            type => 'string',
+            format => $token_policy_format,
+            description => "Cluster-wide policy for creating and updating API tokens, for"
+                . " example to enforce an expiration date or privilege separation.",
+        },
         description => {
             type => 'string',
             description =>
@@ -614,6 +656,10 @@ sub parse_datacenter_config {
         $res->{webauthn} = parse_property_string($webauthn_format, $webauthn);
     }
 
+    if (my $token_policy = $res->{'token-policy'}) {
+        $res->{'token-policy'} = parse_property_string($token_policy_format, $token_policy);
+    }
+
     if (my $tag_style = $res->{'tag-style'}) {
         $res->{'tag-style'} = parse_property_string($tag_style_format, $tag_style);
     }
@@ -707,6 +753,11 @@ sub write_datacenter_config {
         $cfg->{webauthn} = PVE::JSONSchema::print_property_string($webauthn, $webauthn_format);
     }
 
+    if (ref(my $token_policy = $cfg->{'token-policy'})) {
+        $cfg->{'token-policy'} =
+            PVE::JSONSchema::print_property_string($token_policy, $token_policy_format);
+    }
+
     if (ref(my $tag_style = $cfg->{'tag-style'})) {
         $cfg->{'tag-style'} = PVE::JSONSchema::print_property_string($tag_style, $tag_style_format);
     }
diff --git a/src/test/Makefile b/src/test/Makefile
index cdd37d0..3a47b8c 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -4,7 +4,7 @@ cpgtest: cpgtest.c
 	gcc -Wall cpgtest.c $(shell pkg-config --cflags --libs libcpg libqb) -o cpgtest
 
 .PHONY: check install clean distclean
-check: corosync-parser-test test-mac-prefix
+check: corosync-parser-test test-mac-prefix test-token-policy
 
 .PHONY: corosync-parser-test
 corosync-parser-test:
@@ -14,5 +14,9 @@ corosync-parser-test:
 test-mac-prefix:
 	perl test_mac_prefix.pl
 
+.PHONY: test-token-policy
+test-token-policy:
+	perl test_token_policy.pl
+
 distclean: clean
 clean:
diff --git a/src/test/test_token_policy.pl b/src/test/test_token_policy.pl
new file mode 100644
index 0000000..269dc14
--- /dev/null
+++ b/src/test/test_token_policy.pl
@@ -0,0 +1,72 @@
+use strict;
+use warnings;
+
+use Test::More;
+
+use lib ('.', '..');
+
+use PVE::DataCenterConfig;
+
+# the policy is a property string, so it has to survive a parse and write round trip and it must
+# not accept values that the enforcing side would not be able to interpret
+
+my $parse = sub {
+    my ($value) = @_;
+    my $raw = defined($value) ? "token-policy: $value\n" : '';
+    my $cfg = PVE::DataCenterConfig::parse_datacenter_config('datacenter.cfg',
+        $raw . "keyboard: en-us\n");
+    return $cfg;
+};
+
+my $policy = $parse->('require-expiry=1,max-lifetime=86400')->{'token-policy'};
+is($policy->{'require-expiry'}, 1, 'require-expiry is parsed');
+is($policy->{'max-lifetime'}, 86400, 'max-lifetime is parsed');
+
+$policy = $parse->('disallow-expiry-changes=1,require-privilege-separation=1')->{'token-policy'};
+is($policy->{'disallow-expiry-changes'}, 1, 'disallow-expiry-changes is parsed');
+is($policy->{'require-privilege-separation'}, 1, 'require-privilege-separation is parsed');
+
+is($parse->(undef)->{'token-policy'}, undef, 'an absent token-policy is not invented');
+
+# an unusable policy has to be dropped, never half applied, and must not take the rest of the
+# configuration down with it
+for my $invalid (
+    'max-lifetime=0',
+    'max-lifetime=-1',
+    'max-lifetime=forever',
+    'require-expiry=maybe',
+    'unknown-key=1',
+) {
+    my $cfg;
+    {
+        local $SIG{__WARN__} = sub { };
+        $cfg = $parse->($invalid);
+    }
+    is($cfg->{'token-policy'}, undef, "'$invalid' does not yield a policy");
+    is($cfg->{keyboard}, 'en-us', "'$invalid' does not break the rest of the config");
+}
+
+# writing has to turn the parsed hash back into the property string
+my $raw = PVE::DataCenterConfig::write_datacenter_config(
+    'datacenter.cfg',
+    {
+        'token-policy' => {
+            'require-expiry' => 1,
+            'max-lifetime' => 86400,
+        },
+    },
+);
+like(
+    $raw,
+    qr/^token-policy:\s*(require-expiry=1,max-lifetime=86400|max-lifetime=86400,require-expiry=1)$/m,
+    'the policy is written back as a property string',
+);
+
+my $round_tripped = PVE::DataCenterConfig::parse_datacenter_config('datacenter.cfg', $raw);
+is_deeply(
+    $round_tripped->{'token-policy'},
+    { 'require-expiry' => 1, 'max-lifetime' => 86400 },
+    'the policy survives a write and parse round trip',
+);
+
+done_testing();
-- 
2.47.3





^ permalink raw reply related	[relevance 19%]

* [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy
@ 2026-09-23 20:59 17% Thomas Lamprecht
  2026-09-23 20:59 19% ` [PATCH cluster 1/9] datacenter config: add token-policy option Thomas Lamprecht
                   ` (4 more replies)
  0 siblings, 5 replies; 17+ results
From: Thomas Lamprecht @ 2026-09-23 20:59 UTC (permalink / raw)
  To: pve-devel

Compliance rules like PCI DSS, SOC 2, or ISO 27001 often require
that credentials have a limited lifetime, but there is no central way
to enforce that for API tokens.

Add an optional token-policy option to datacenter.cfg to require an
expiration date, limit the maximum token lifetime, forbid changing
the expiration date of existing tokens, and require privilege
separation.

The policy is only checked when a token is created or updated, and
only for values that actually change, so existing tokens stay valid even
if their lifetime exceeds a newly configured maximum one.
Extending the expiration date within the limit stays possible, unless
the opt-in 'disallow-expiry-changes' switch is set (see [0] for the
rationale).

The web UI exposes these options under Datacenter -> Options and
adjusts the token dialogs to the policy. Changing the policy requires
Sys.Modify on '/', like any other datacenter option; an extra
auth-specific privilege check was skipped for now, for the current
built-in roles it would land in the same roles as Sys.Modify, adding new
built-in roles here is IMO scope creep and this can still be done later
(with some more thoughts on how to handle all these datacenter options).

FWIW, the first manager patch (4/9 overall) fixes a pre-existing issue
w.r.t. only submitting the expiration date when changed, which the
policy checks would expose more often, but it'd also make sense on its
own and could be applied independently already.

The last two patches port the backend part to the common rust stack, so
PBS and PDM can opt in through their AccessControlConfig, and to prepare
moving pve-access-control over to rust later. Only the expiry parts
apply there, tokens in the rust stack always use separate ACLs, i.e. no
sharing with the underlying users there.

Dependencies: access-control needs the cluster patch, manager needs
both, and building manager needs the pve-doc-generator with the new
online-help anchor from the docs patch (or ALLOW_MISSING=1), which is
why the docs patch comes before the manager ones; the proxmox patches
are independent. d/control needs the respective versioned dependency
bumps added on applying, and the generated datacenter option reference
in pve-docs needs the usual make update once the cluster side is
packaged.

[0]: https://bugzilla.proxmox.com/show_bug.cgi?id=7805

cluster:

Thomas Lamprecht (1):
  datacenter config: add token-policy option

 src/PVE/DataCenterConfig.pm   | 51 ++++++++++++++++++++++++++++++
 src/test/Makefile             |  6 +++-
 src/test/test_token_policy.pl | 72 +++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 128 insertions(+), 1 deletion(-)

access-control:

Thomas Lamprecht (1):
  fix #7805: api: token: enforce datacenter token policy

 src/PVE/API2/User.pm              |  32 +++++-
 src/PVE/AccessControl.pm          |  59 +++++++++++
 src/test/Makefile                 |   2 +
 src/test/token-policy-api-test.pl | 102 ++++++++++++++++++
 src/test/token-policy-test.pl     | 217 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 409 insertions(+), 3 deletions(-)

docs:

Thomas Lamprecht (1):
  user management: document the API token policy

 pveum.adoc | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)

manager:

Thomas Lamprecht (4):
  ui: token edit: only submit the expiration date when changed
  api: cluster options: return token-policy without Sys.Audit
  ui: dc options: allow editing the API token policy
  ui: token edit: adapt to the datacenter API token policy

 PVE/API2/Cluster.pm           |   2 +-
 www/manager6/UIOptions.js     |  14 ++++-
 www/manager6/dc/OptionView.js | 108 +++++++++++++++++++++++++++++++++
 www/manager6/dc/TokenEdit.js  | 136 +++++++++++++++++++++++++++++++++++++++++-
 www/manager6/dc/TokenView.js  |  36 ++++++-----
 5 files changed, 278 insertions(+), 18 deletions(-)

proxmox:

Thomas Lamprecht (2):
  access-control: add API token policy type with expiry checks
  access-control: enforce token policy on token create and update

 proxmox-access-control/src/api/tokens.rs |  17 +++
 proxmox-access-control/src/init.rs       |  15 ++
 proxmox-access-control/src/types.rs      | 227 +++++++++++++++++++++++++++++++
 3 files changed, 259 insertions(+)

-- 
2.47.3




^ permalink raw reply	[relevance 17%]

Results 1-17 of 17 | reverse | options above
-- pct% links below jump to the message on this page, permalinks otherwise --
2026-09-23 20:59 17% [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
2026-09-23 20:59 19% ` [PATCH cluster 1/9] datacenter config: add token-policy option Thomas Lamprecht
2026-11-10 15:05  6%   ` Shannon Sterz
2026-09-23 20:59 25% ` [PATCH access-control 2/9] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
2026-09-23 20:59 18% ` [PATCH proxmox 8/9] access-control: add API token policy type with expiry checks Thomas Lamprecht
2026-11-10 15:05  4%   ` Shannon Sterz
2026-11-10 15:05 12% ` [PATCH cluster/access-control/manager/docs/proxmox 0/9] fix #7805: add a datacenter-wide API token policy Shannon Sterz
2026-11-10 15:28  8%   ` Thomas Lamprecht
2026-11-15 23:38  8% ` superseded: " Thomas Lamprecht
2026-11-15 19:40 17% [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] " Thomas Lamprecht
2026-11-15 19:40 19% ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
2026-11-15 19:40 25% ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
2026-11-17 13:30  8%   ` Shannon Sterz
2026-11-15 19:40 18% ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
2026-11-17 13:29  5%   ` Shannon Sterz
2026-11-17 13:29  8% ` [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 17% ` applied: " Thomas Lamprecht

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal