* [PATCH v2 cluster 1/19] datacenter config: add token-policy option
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 2/19] datacenter config: token policy: add default-to-max-lifetime setting Thomas Lamprecht
` (19 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
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 [flat|nested] 26+ messages in thread* [PATCH v2 cluster 2/19] datacenter config: token policy: add default-to-max-lifetime setting
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 3/19] datacenter config: token policy: allow extension on regeneration Thomas Lamprecht
` (18 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
With 'max-lifetime' set, a token created without an expiration date
is rejected. That breaks tools unaware of the policy, like the remote
wizard of Proxmox Datacenter Manager, and makes onboarding them
cumbersome, as a compliant token must be created by hand first.
Add a setting that gives such tokens the maximum lifetime instead, so
a missing expiration date no longer gets them rejected. It is opt-in,
as a token expiring without the client asking for it can break that
client later instead. The enforcement side applies it on token
creation only.
Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
src/PVE/DataCenterConfig.pm | 9 +++++++++
src/test/test_token_policy.pl | 3 +++
2 files changed, 12 insertions(+)
diff --git a/src/PVE/DataCenterConfig.pm b/src/PVE/DataCenterConfig.pm
index 13d388f..330126b 100644
--- a/src/PVE/DataCenterConfig.pm
+++ b/src/PVE/DataCenterConfig.pm
@@ -294,6 +294,15 @@ my $token_policy_format = {
. " repeatedly. Shortening it, or setting one for a token without, stays possible,"
. " and tokens can still be deleted and recreated.",
},
+ 'default-to-max-lifetime' => {
+ type => 'boolean',
+ optional => 1,
+ default => 0,
+ description =>
+ "Set the expiration date of API tokens created without one to the maximum"
+ . " lifetime instead of rejecting them, for example for tools unaware of the policy."
+ . " Has no effect without 'max-lifetime'.",
+ },
'require-privilege-separation' => {
type => 'boolean',
optional => 1,
diff --git a/src/test/test_token_policy.pl b/src/test/test_token_policy.pl
index 0128aad..bcafec1 100644
--- a/src/test/test_token_policy.pl
+++ b/src/test/test_token_policy.pl
@@ -23,6 +23,9 @@ $policy = $parse->('disallow-expiry-extension=1,require-privilege-separation=1')
is($policy->{'disallow-expiry-extension'}, 1, 'disallow-expiry-extension is parsed');
is($policy->{'require-privilege-separation'}, 1, 'require-privilege-separation is parsed');
+$policy = $parse->('max-lifetime=86400,default-to-max-lifetime=1')->{'token-policy'};
+is($policy->{'default-to-max-lifetime'}, 1, 'default-to-max-lifetime 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
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 cluster 3/19] datacenter config: token policy: allow extension on regeneration
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 1/19] datacenter config: add token-policy option Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 cluster 2/19] datacenter config: token policy: add default-to-max-lifetime setting Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-17 13:30 ` Shannon Sterz
2026-11-15 19:40 ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
` (17 subsequent siblings)
20 siblings, 1 reply; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
With 'disallow-expiry-extension' set, keeping an integration running
past the maximum lifetime needs a new token with all its permissions
set up again. As creating that token is always possible, the
restriction mostly adds work and discourages narrowly scoped tokens.
Extending a token together with regenerating its secret has the same
effect as recreating it, as the old credential stops working. Add a
setting that allows exactly that, so tools can rotate their tokens in
place, within the maximum lifetime.
Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
src/PVE/DataCenterConfig.pm | 8 ++++++++
src/test/test_token_policy.pl | 3 +++
2 files changed, 11 insertions(+)
diff --git a/src/PVE/DataCenterConfig.pm b/src/PVE/DataCenterConfig.pm
index 330126b..49d1bb6 100644
--- a/src/PVE/DataCenterConfig.pm
+++ b/src/PVE/DataCenterConfig.pm
@@ -303,6 +303,14 @@ my $token_policy_format = {
. " lifetime instead of rejecting them, for example for tools unaware of the policy."
. " Has no effect without 'max-lifetime'.",
},
+ 'allow-extension-on-regenerate' => {
+ type => 'boolean',
+ optional => 1,
+ default => 0,
+ description => "Allow extending the expiration date of an existing API token when its"
+ . " secret is regenerated in the same request, despite 'disallow-expiry-extension'."
+ . " The maximum lifetime still applies.",
+ },
'require-privilege-separation' => {
type => 'boolean',
optional => 1,
diff --git a/src/test/test_token_policy.pl b/src/test/test_token_policy.pl
index bcafec1..adcb93a 100644
--- a/src/test/test_token_policy.pl
+++ b/src/test/test_token_policy.pl
@@ -26,6 +26,9 @@ is($policy->{'require-privilege-separation'}, 1, 'require-privilege-separation i
$policy = $parse->('max-lifetime=86400,default-to-max-lifetime=1')->{'token-policy'};
is($policy->{'default-to-max-lifetime'}, 1, 'default-to-max-lifetime is parsed');
+$policy = $parse->('disallow-expiry-extension=1,allow-extension-on-regenerate=1')->{'token-policy'};
+is($policy->{'allow-extension-on-regenerate'}, 1, 'allow-extension-on-regenerate 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
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* Re: [PATCH v2 cluster 3/19] datacenter config: token policy: allow extension on regeneration
2026-11-15 19:40 ` [PATCH v2 cluster 3/19] datacenter config: token policy: allow extension on regeneration Thomas Lamprecht
@ 2026-11-17 13:30 ` Shannon Sterz
0 siblings, 0 replies; 26+ messages in thread
From: Shannon Sterz @ 2026-11-17 13:30 UTC (permalink / raw)
To: Thomas Lamprecht, pve-devel
On Sun Nov 15, 2026 at 8:40 PM CET, Thomas Lamprecht wrote:
> With 'disallow-expiry-extension' set, keeping an integration running
> past the maximum lifetime needs a new token with all its permissions
> set up again. As creating that token is always possible, the
> restriction mostly adds work and discourages narrowly scoped tokens.
>
> Extending a token together with regenerating its secret has the same
> effect as recreating it, as the old credential stops working. Add a
> setting that allows exactly that, so tools can rotate their tokens in
> place, within the maximum lifetime.
>
> Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
> Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
> ---
>
> new in v2
>
> src/PVE/DataCenterConfig.pm | 8 ++++++++
> src/test/test_token_policy.pl | 3 +++
> 2 files changed, 11 insertions(+)
>
> diff --git a/src/PVE/DataCenterConfig.pm b/src/PVE/DataCenterConfig.pm
> index 330126b..49d1bb6 100644
> --- a/src/PVE/DataCenterConfig.pm
> +++ b/src/PVE/DataCenterConfig.pm
> @@ -303,6 +303,14 @@ my $token_policy_format = {
> . " lifetime instead of rejecting them, for example for tools unaware of the policy."
> . " Has no effect without 'max-lifetime'.",
> },
> + 'allow-extension-on-regenerate' => {
> + type => 'boolean',
> + optional => 1,
> + default => 0,
nit: `0` being the more cumbersome setting with little upside since
recreating tokens is still possible makes it sound like a bad default.
maybe add a sentence why it should be the default or change the default
to one `1`. for example:
Nonetheless, 0 is chosen as the default as allowing the expiry to be
extended even by regeneration may not match an admins expectations.
-->8 snip 8<--
^ permalink raw reply [flat|nested] 26+ messages in thread
* [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (2 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 cluster 3/19] datacenter config: token policy: allow extension on regeneration Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-17 13:30 ` Shannon Sterz
2026-11-15 19:40 ` [PATCH v2 access-control 5/19] api: token: apply the default lifetime from the " Thomas Lamprecht
` (16 subsequent siblings)
20 siblings, 1 reply; 26+ messages in thread
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 [flat|nested] 26+ messages in thread* Re: [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy
2026-11-15 19:40 ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
@ 2026-11-17 13:30 ` Shannon Sterz
0 siblings, 0 replies; 26+ messages in thread
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 [flat|nested] 26+ messages in thread
* [PATCH v2 access-control 5/19] api: token: apply the default lifetime from the token policy
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (3 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 access-control 4/19] fix #7805: api: token: enforce datacenter token policy Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 access-control 6/19] api: token: allow extending tokens on secret regeneration Thomas Lamprecht
` (15 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Give tokens created without an expiration date the maximum lifetime
when the policy opts into that with 'default-to-max-lifetime', instead
of rejecting them. Tools unaware of the policy, like the remote wizard
of Proxmox Datacenter Manager, then no longer fail just for omitting
the expiration date, and the effective expiration date is part of the
creation response as before. Updates are not affected, removing an
expiration date there is an explicit request and stays rejected.
Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
src/PVE/API2/User.pm | 5 +++++
src/PVE/AccessControl.pm | 12 ++++++++++++
src/test/token-policy-api-test.pl | 22 ++++++++++++++++++++++
src/test/token-policy-test.pl | 17 +++++++++++++++++
4 files changed, 56 insertions(+)
diff --git a/src/PVE/API2/User.pm b/src/PVE/API2/User.pm
index 78e5fc9..6490060 100644
--- a/src/PVE/API2/User.pm
+++ b/src/PVE/API2/User.pm
@@ -811,6 +811,11 @@ __PACKAGE__->register_method({
$token->{expire} = $param->{expire} if defined($param->{expire});
$token->{comment} = $param->{comment} if $param->{comment};
+ if (!int($token->{expire} // 0)) {
+ my $default_expire = PVE::AccessControl::token_policy_default_expire();
+ $token->{expire} = $default_expire if $default_expire;
+ }
+
# check policy before generating the secret to avoid leaving an orphan in token.cfg
PVE::AccessControl::assert_token_policy({
expire => $token->{expire} // 0,
diff --git a/src/PVE/AccessControl.pm b/src/PVE/AccessControl.pm
index e2027cf..930cb5a 100644
--- a/src/PVE/AccessControl.pm
+++ b/src/PVE/AccessControl.pm
@@ -753,6 +753,18 @@ sub assert_token_policy {
}
}
+# Returns the expiration date the datacenter token policy assigns to a new token created without
+# one, or undef if the policy does not default it. 'ctime' and 'policy' can be overridden like
+# for assert_token_policy.
+sub token_policy_default_expire {
+ my ($param) = @_;
+
+ my $policy = $param->{policy} // cfs_read_file('datacenter.cfg')->{'token-policy'};
+ return undef if !$policy || !$policy->{'default-to-max-lifetime'} || !$policy->{'max-lifetime'};
+
+ return ($param->{ctime} // time()) + $policy->{'max-lifetime'};
+}
+
sub check_token_exist {
my ($usercfg, $username, $tokenid, $noerr) = @_;
diff --git a/src/test/token-policy-api-test.pl b/src/test/token-policy-api-test.pl
index 5af4e58..ebaece7 100644
--- a/src/test/token-policy-api-test.pl
+++ b/src/test/token-policy-api-test.pl
@@ -112,4 +112,26 @@ $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);
+# default-to-max-lifetime gives tokens created without an expiration date the maximum lifetime
+my $defaulting = { 'max-lifetime' => 86400, 'default-to-max-lifetime' => 1 };
+for my $case (['absent', {}], ['zero', { expire => 0 }], ['zero spelling', { expire => '00' }]) {
+ my ($desc, $param) = $case->@*;
+ $reset->($defaulting);
+ my $before = time();
+ ($ok, $err) = $invoke->('generate_token', { tokenid => 'new', %$param });
+ ok($ok, "create with $desc expiry is accepted under default-to-max-lifetime") or diag($err);
+ my ($expire) = $user_cfg_raw =~ /^token:test\@pve!new:(\d+):/m;
+ ok(
+ defined($expire) && $expire >= $before + 86400 && $expire <= time() + 86400,
+ "create with $desc expiry stores the maximum lifetime as expiration date",
+ ) or diag("stored expire: " . ($expire // 'none'));
+}
+$reset->($defaulting);
+($ok, $err) = $invoke->('generate_token', { tokenid => 'new', expire => $now + 600 });
+ok($ok, 'an explicit expiry is kept under default-to-max-lifetime') or diag($err);
+like($user_cfg_raw, qr/^token:test\@pve!new:${\($now + 600)}:/m, 'the explicit expiry is stored');
+$reset->({ 'default-to-max-lifetime' => 1, 'require-expiry' => 1 });
+($ok, $err) = $invoke->('generate_token', { tokenid => 'new' });
+ok(!$ok && $err =~ /requires an expiration date/, 'no default without a maximum lifetime');
+
done_testing();
diff --git a/src/test/token-policy-test.pl b/src/test/token-policy-test.pl
index d29c781..f43fc8c 100644
--- a/src/test/token-policy-test.pl
+++ b/src/test/token-policy-test.pl
@@ -239,4 +239,21 @@ check(
0,
);
+# default-to-max-lifetime only yields a default with a maximum lifetime to derive it from
+my $default_expire = sub {
+ my ($policy) = @_;
+ return PVE::AccessControl::token_policy_default_expire({
+ ctime => $now,
+ policy => $policy,
+ });
+};
+is(
+ $default_expire->({ 'max-lifetime' => $max, 'default-to-max-lifetime' => 1 }),
+ $now + $max,
+ 'default-to-max-lifetime yields now plus the maximum lifetime',
+);
+is($default_expire->({ 'max-lifetime' => $max }), undef, 'no default without opting in');
+is($default_expire->({ 'default-to-max-lifetime' => 1 }), undef, 'no default without a maximum');
+is($default_expire->(undef), undef, 'no default without a policy');
+
done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 access-control 6/19] api: token: allow extending tokens on secret regeneration
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (4 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 access-control 5/19] api: token: apply the default lifetime from the " Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 docs 7/19] user management: document the API token policy Thomas Lamprecht
` (14 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Honor the new 'allow-extension-on-regenerate' policy setting: with it,
an update that regenerates the secret may also extend the expiration
date despite 'disallow-expiry-extension', as the old credential stops
working just like it would on recreating the token. The maximum
lifetime still bounds the new date, and the check still runs before
the secret is regenerated, so a rejected extension does not rotate it.
Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
src/PVE/API2/User.pm | 1 +
src/PVE/AccessControl.pm | 8 +++++-
src/test/token-policy-api-test.pl | 11 ++++++++
src/test/token-policy-test.pl | 45 +++++++++++++++++++++++++++++++
4 files changed, 64 insertions(+), 1 deletion(-)
diff --git a/src/PVE/API2/User.pm b/src/PVE/API2/User.pm
index 6490060..453d317 100644
--- a/src/PVE/API2/User.pm
+++ b/src/PVE/API2/User.pm
@@ -932,6 +932,7 @@ __PACKAGE__->register_method({
expire => $expire_change,
'privilege-separation' => $privilege_separation_change,
'current-expire' => $old_expire,
+ regenerate => $regenerate,
});
my $deletable = {
diff --git a/src/PVE/AccessControl.pm b/src/PVE/AccessControl.pm
index 930cb5a..3192fed 100644
--- a/src/PVE/AccessControl.pm
+++ b/src/PVE/AccessControl.pm
@@ -700,6 +700,8 @@ sub check_user_enabled {
# 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
+# - regenerate: whether the update also regenerates the secret, see
+# 'allow-extension-on-regenerate'
# - ctime, policy: override the reference time for the maximum lifetime and the policy from the
# datacenter config, for testing
#
@@ -719,10 +721,14 @@ sub assert_token_policy {
return if !$policy;
if (defined($expire)) {
- # removing the expiration date or moving it later extends the token
+ # removing the expiration date or moving it later extends the token; regenerating the
+ # secret along with it is like recreating the token, which the policy may allow
my $current_expire = $param->{'current-expire'};
+ my $regenerate_allows_extension =
+ $param->{regenerate} && $policy->{'allow-extension-on-regenerate'};
if (
$policy->{'disallow-expiry-extension'}
+ && !$regenerate_allows_extension
&& $current_expire
&& (!$expire || $expire > $current_expire)
) {
diff --git a/src/test/token-policy-api-test.pl b/src/test/token-policy-api-test.pl
index ebaece7..090d576 100644
--- a/src/test/token-policy-api-test.pl
+++ b/src/test/token-policy-api-test.pl
@@ -134,4 +134,15 @@ $reset->({ 'default-to-max-lifetime' => 1, 'require-expiry' => 1 });
($ok, $err) = $invoke->('generate_token', { tokenid => 'new' });
ok(!$ok && $err =~ /requires an expiration date/, 'no default without a maximum lifetime');
+# allow-extension-on-regenerate: extending needs the secret regenerated in the same request
+$reset->({ 'disallow-expiry-extension' => 1, 'allow-extension-on-regenerate' => 1 }, $now + 600);
+($ok, $err) = $invoke->('update_token_info', { tokenid => 'old', expire => $now + 1200 });
+ok(!$ok && $err =~ /does not allow extending/, 'extending without regeneration is rejected');
+is($secret_calls, 0, 'the rejected update does not touch the secret');
+($ok, $err) =
+ $invoke->('update_token_info', { tokenid => 'old', expire => $now + 1200, regenerate => 1 });
+ok($ok, 'extending together with regeneration is accepted') or diag($err);
+is($secret_calls, 1, 'the accepted update regenerates the secret');
+like($user_cfg_raw, qr/^token:test\@pve!old:${\($now + 1200)}:/m, 'the extended expiry is stored');
+
done_testing();
diff --git a/src/test/token-policy-test.pl b/src/test/token-policy-test.pl
index f43fc8c..2310fdc 100644
--- a/src/test/token-policy-test.pl
+++ b/src/test/token-policy-test.pl
@@ -177,6 +177,51 @@ check(
0,
);
+# allow-extension-on-regenerate lifts the extension ban only together with a secret regeneration
+my $rotation = { 'disallow-expiry-extension' => 1, 'allow-extension-on-regenerate' => 1 };
+check(
+ 'allow-extension-on-regenerate, extension with regeneration',
+ $rotation,
+ { expire => $now + 200, 'current-expire' => $now + 100, regenerate => 1 },
+ 0,
+);
+check(
+ 'allow-extension-on-regenerate, removal with regeneration',
+ $rotation,
+ { expire => 0, 'current-expire' => $now + 100, regenerate => 1 },
+ 0,
+);
+check(
+ 'allow-extension-on-regenerate, extension without regeneration',
+ $rotation,
+ { expire => $now + 200, 'current-expire' => $now + 100 },
+ 1,
+);
+check(
+ 'allow-extension-on-regenerate, extension with regenerate=0',
+ $rotation,
+ { expire => $now + 200, 'current-expire' => $now + 100, regenerate => 0 },
+ 1,
+);
+check(
+ 'disallow-expiry-extension alone ignores regeneration',
+ $no_extension,
+ { expire => $now + 200, 'current-expire' => $now + 100, regenerate => 1 },
+ 1,
+);
+check(
+ 'allow-extension-on-regenerate, max-lifetime still bounds the extension',
+ { $rotation->%*, 'max-lifetime' => $max },
+ { expire => $now + $max + 1, 'current-expire' => $now + 100, regenerate => 1 },
+ 1,
+);
+check(
+ 'allow-extension-on-regenerate, extension within max-lifetime with regeneration',
+ { $rotation->%*, 'max-lifetime' => $max },
+ { expire => $now + $max, 'current-expire' => $now + 100, regenerate => 1 },
+ 0,
+);
+
# require-privilege-separation
my $require_privilege_separation = { 'require-privilege-separation' => 1 };
check(
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 docs 7/19] user management: document the API token policy
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (5 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 access-control 6/19] api: token: allow extending tokens on secret regeneration Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 docs 8/19] user management: document the default-to-max-lifetime setting Thomas Lamprecht
` (13 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Describe the new datacenter token-policy option next to the general
API token section, so admins who need to fulfill compliance
requirements find the enforcement options in one place. The option
reference itself is generated from the datacenter.cfg schema.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
changes since v1:
- adapt to 'disallow-expiry-extension'
- warn to only configure the policy once all nodes are upgraded
- note that it applies to tokens created by other tools too, like PDM
pveum.adoc | 44 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/pveum.adoc b/pveum.adoc
index 1413faf..9370664 100644
--- a/pveum.adoc
+++ b/pveum.adoc
@@ -115,6 +115,50 @@ To use an API token, set the HTTP header 'Authorization' to the displayed value
of the form `PVEAPIToken=USER@REALM!TOKENID=UUID` when making API requests, or
refer to your API client's documentation.
+[[pveum_token_policy]]
+Token Policy
+~~~~~~~~~~~~
+
+The optional `token-policy` datacenter option sets cluster-wide rules for
+creating and updating API tokens, as compliance standards like PCI DSS,
+SOC 2, or ISO 27001 often require, most notably a limited credential
+lifetime. The policy can require an expiration date for new tokens, limit
+how far in the future the expiration date can be set, forbid extending the
+expiration date of existing tokens, and require privilege separation.
+
+WARNING: The policy is enforced by the nodes that handle a token request,
+so in a cluster, only configure it once all nodes run a version supporting
+it. Nodes running an older version ignore the policy, and changing
+datacenter options on such a node removes it from the configuration.
+
+Changing the policy requires `Sys.Modify` on `/`, like any other datacenter
+option. Configure it in the web interface under *Datacenter -> Options ->
+API Token Policy*, or on the command line:
+
+[source,bash]
+----
+pvesh set /cluster/options --token-policy max-lifetime=7776000
+----
+
+`max-lifetime` is set in seconds (7776000 above is 90 days), while the web
+interface takes days. It counts from when the expiration date is set, that
+is on token creation or when an update changes it, and implies
+`require-expiry`, as a token without an expiration date would exceed any
+maximum lifetime.
+
+The policy only applies when a token is created or updated, and only to
+values that actually change. Existing tokens stay valid even if they do not
+conform to a policy configured later, and unrelated updates of such tokens
+keep working. A new expiration date must be within the limit. With
+`disallow-expiry-extension`, the expiration date of an existing token can
+only be shortened, or set if it has none. Tokens can always be deleted and
+recreated.
+
+NOTE: The policy also applies to tokens that other tools create through the
+API, for example when adding the cluster as a remote to Proxmox Datacenter
+Manager. If such a tool cannot create a compliant token, create one manually
+and use that in the tool instead.
+
[[pveum_resource_pools]]
Resource Pools
--------------
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 docs 8/19] user management: document the default-to-max-lifetime setting
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (6 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 docs 7/19] user management: document the API token policy Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 docs 9/19] user management: document extending tokens on secret regeneration Thomas Lamprecht
` (12 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Point admins at the new setting as the alternative to creating tokens
by hand for tools that do not set an expiration date themselves.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
pveum.adoc | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/pveum.adoc b/pveum.adoc
index 9370664..7e043d9 100644
--- a/pveum.adoc
+++ b/pveum.adoc
@@ -156,8 +156,11 @@ recreated.
NOTE: The policy also applies to tokens that other tools create through the
API, for example when adding the cluster as a remote to Proxmox Datacenter
-Manager. If such a tool cannot create a compliant token, create one manually
-and use that in the tool instead.
+Manager. For tools that do not set an expiration date, set
+`default-to-max-lifetime` together with `max-lifetime`, so that their tokens
+get the maximum lifetime instead of being rejected. If a tool still cannot
+create a compliant token, for example because it disables privilege
+separation, create one manually and use that in the tool instead.
[[pveum_resource_pools]]
Resource Pools
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 docs 9/19] user management: document extending tokens on secret regeneration
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (7 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 docs 8/19] user management: document the default-to-max-lifetime setting Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 10/19] ui: token edit: only submit the expiration date when changed Thomas Lamprecht
` (11 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Describe the new allow-extension-on-regenerate policy setting and how
to rotate a token in place with it, in the web interface and on the
command line.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
pveum.adoc | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/pveum.adoc b/pveum.adoc
index 7e043d9..a5887d4 100644
--- a/pveum.adoc
+++ b/pveum.adoc
@@ -154,6 +154,22 @@ keep working. A new expiration date must be within the limit. With
only be shortened, or set if it has none. Tokens can always be deleted and
recreated.
+With `allow-extension-on-regenerate`, an existing token can still be
+extended within the limit when its secret is regenerated in the same
+request. The old secret stops working, like it would when recreating the
+token, so tools can rotate their tokens in place without setting up the
+permissions again. In the web interface, enable *Regenerate Secret* in the
+token edit dialog and set the new expiration date. On the command line, pass
+the new expiration date in Unix epoch seconds:
+
+[source,bash]
+----
+pveum user token modify <userid> <tokenid> --expire <timestamp> --regenerate 1
+----
+
+Like on creation, the new secret is only displayed once, so update the tool
+to use it right away.
+
NOTE: The policy also applies to tokens that other tools create through the
API, for example when adding the cluster as a remote to Proxmox Datacenter
Manager. For tools that do not set an expiration date, set
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 manager 10/19] ui: token edit: only submit the expiration date when changed
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (8 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 docs 9/19] user management: document extending tokens on secret regeneration Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 11/19] api: cluster options: return token-policy without Sys.Audit Thomas Lamprecht
` (10 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
The day-granular date field resubmits the stored expiration date
truncated to the start of its day, so any unrelated edit, for example
of the comment, silently shortened the stored date by up to a day.
Drop the value from the submission if the selected day was not
actually changed.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
changes since v1:
- compute the unchanged day with Ext.Date.clearTime, like the date field
www/manager6/dc/TokenEdit.js | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/www/manager6/dc/TokenEdit.js b/www/manager6/dc/TokenEdit.js
index fc9f0cc2c..cf4e2ae2e 100644
--- a/www/manager6/dc/TokenEdit.js
+++ b/www/manager6/dc/TokenEdit.js
@@ -25,6 +25,20 @@ Ext.define('PVE.dc.TokenEdit', {
delete values.userid;
delete values.tokenid;
+ // the date field only holds the day, so drop an unchanged day to keep the exact stored
+ // expiration date
+ if (!win.isCreate && win.originalExpire !== undefined) {
+ let originalDayStart = 0;
+ if (win.originalExpire) {
+ let day = new Date(win.originalExpire * 1000);
+ Ext.Date.clearTime(day);
+ originalDayStart = Math.floor(day.getTime() / 1000);
+ }
+ if (Number(values.expire) === originalDayStart) {
+ delete values.expire;
+ }
+ }
+
win.url += `${uid}/token/${tid}`;
return values;
},
@@ -91,6 +105,20 @@ Ext.define('PVE.dc.TokenEdit', {
});
}
},
+
+ setValues: function (values) {
+ let me = this;
+ // remember the stored expiration date to detect a real change on submission; the
+ // token grid's record carries it as a Date object, the API as epoch seconds
+ if (!me.isCreate && values.expire !== undefined) {
+ me.originalExpire =
+ values.expire instanceof Date
+ ? Math.floor(values.expire.getTime() / 1000)
+ : Number(values.expire);
+ }
+ me.callParent([values]);
+ },
+
apiCallDone: function (success, response, options) {
let res = response.result.data;
if (!success || !res.value) {
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 manager 11/19] api: cluster options: return token-policy without Sys.Audit
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (9 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 manager 10/19] ui: token edit: only submit the expiration date when changed Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 12/19] ui: dc options: allow editing the API token policy Thomas Lamprecht
` (9 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Any user can create API tokens for themselves, so the token dialogs
need the new datacenter token policy to adapt up front, but reading
the full datacenter config requires Sys.Audit. Return the policy like
the console and tag-style options; it only contains restrictions that
are enforced on the token create and update calls anyway.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
PVE/API2/Cluster.pm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/PVE/API2/Cluster.pm b/PVE/API2/Cluster.pm
index 4e5efbfd9..fe7cb7766 100644
--- a/PVE/API2/Cluster.pm
+++ b/PVE/API2/Cluster.pm
@@ -813,7 +813,7 @@ __PACKAGE__->register_method({
if ($rpcenv->check($authuser, '/', ['Sys.Audit'], 1)) {
$res = $datacenter_config;
} else {
- for my $k (qw(console tag-style)) {
+ for my $k (qw(console tag-style token-policy)) {
$res->{$k} = $datacenter_config->{$k} if exists $datacenter_config->{$k};
}
}
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 manager 12/19] ui: dc options: allow editing the API token policy
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (10 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 manager 11/19] api: cluster options: return token-policy without Sys.Audit Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 13/19] ui: token edit: adapt to the datacenter " Thomas Lamprecht
` (8 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Render and edit the new datacenter token-policy option. The maximum
lifetime is entered in days, fractional values are allowed for
sub-day lifetimes, and the exact stored value is kept when the field
is left untouched, so a finer grained value set via the API survives
unrelated edits.
A set maximum lifetime implies requiring an expiration date, so the
dialog locks that checkbox on while a lifetime is entered to make the
implication visible, and restores the previous choice once the
lifetime is cleared again.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
changes since v1:
- adapt to 'disallow-expiry-extension'
- lock the require-expiry checkbox on while a maximum lifetime is set
www/manager6/dc/OptionView.js | 136 ++++++++++++++++++++++++++++++++++
1 file changed, 136 insertions(+)
diff --git a/www/manager6/dc/OptionView.js b/www/manager6/dc/OptionView.js
index dc12aa7e1..d5bc1a538 100644
--- a/www/manager6/dc/OptionView.js
+++ b/www/manager6/dc/OptionView.js
@@ -384,6 +384,142 @@ Ext.define('PVE.dc.OptionView', {
},
],
});
+ me.rows['token-policy'] = {
+ required: true,
+ header: gettext('API Token Policy'),
+ renderer: function (policy) {
+ if (!policy) {
+ return Proxmox.Utils.NoneText;
+ }
+ let parts = [];
+ if (Number(policy['require-expiry'])) {
+ parts.push(gettext('Require Expiration Date'));
+ }
+ if (policy['max-lifetime'] !== undefined) {
+ let lifetime = Proxmox.Utils.format_duration_human(
+ Number(policy['max-lifetime']),
+ );
+ parts.push(Ext.String.format(gettext('Max. Lifetime: {0}'), lifetime));
+ }
+ if (Number(policy['disallow-expiry-extension'])) {
+ parts.push(gettext('Disallow Extending Expiration'));
+ }
+ if (Number(policy['require-privilege-separation'])) {
+ parts.push(gettext('Require Privilege Separation'));
+ }
+ return parts.length ? parts.join(', ') : Proxmox.Utils.NoneText;
+ },
+ editor: {
+ xtype: 'proxmoxWindowEdit',
+ subject: gettext('API Token Policy'),
+ onlineHelp: 'pveum_token_policy',
+ url: '/api2/extjs/cluster/options',
+ width: 450,
+ fieldDefaults: {
+ labelWidth: 200,
+ },
+ setValues: function (values) {
+ let me = this;
+ // max-lifetime is stored in seconds but edited in days; keep the exact stored
+ // value for saving an untouched field
+ let policy = Ext.apply({}, values['token-policy'] || {});
+ me.storedMaxLifetime = policy['max-lifetime'];
+ // the maximum lifetime may lock the checkbox before it gets set below
+ me.down('field[name=require-expiry]').explicitValue = !!Number(
+ policy['require-expiry'],
+ );
+ if (policy['max-lifetime'] !== undefined) {
+ policy['max-lifetime'] =
+ Math.ceil((Number(policy['max-lifetime']) / 86400) * 100) / 100;
+ }
+ Ext.Array.each(me.query('inputpanel'), (panel) => panel.setValues(policy));
+ },
+ items: [
+ {
+ xtype: 'inputpanel',
+ onGetValues: function (values) {
+ let me = this;
+ let win = me.up('proxmoxWindowEdit');
+ let policy = {};
+ // read the field directly, it is disabled and thus not part of the
+ // values while a maximum lifetime implies it
+ if (me.down('field[name=require-expiry]').getValue()) {
+ policy['require-expiry'] = 1;
+ }
+ if (values['disallow-expiry-extension']) {
+ policy['disallow-expiry-extension'] = 1;
+ }
+ if (values['require-privilege-separation']) {
+ policy['require-privilege-separation'] = 1;
+ }
+ let days = values['max-lifetime'];
+ if (days !== undefined && days !== null && days !== '') {
+ let untouched = !me.down('field[name=max-lifetime]').isDirty();
+ policy['max-lifetime'] =
+ untouched && win.storedMaxLifetime !== undefined
+ ? win.storedMaxLifetime
+ : Math.round(Number(days) * 86400);
+ }
+ if (Object.keys(policy).length === 0) {
+ return { delete: 'token-policy' };
+ }
+ return { 'token-policy': PVE.Parser.printPropertyString(policy) };
+ },
+ items: [
+ {
+ xtype: 'proxmoxcheckbox',
+ name: 'require-expiry',
+ uncheckedValue: 0,
+ fieldLabel: gettext('Require Expiration Date'),
+ listeners: {
+ // remember an explicit choice to restore it once a maximum
+ // lifetime no longer implies it
+ change: function (field, value) {
+ if (!field.isDisabled()) {
+ field.explicitValue = value;
+ }
+ },
+ },
+ },
+ {
+ xtype: 'numberfield',
+ name: 'max-lifetime',
+ minValue: 0.01,
+ emptyText: gettext('No limit'),
+ fieldLabel: gettext('Maximum Lifetime (days)'),
+ listeners: {
+ // a maximum lifetime implies requiring an expiration date,
+ // show that by locking the checkbox on
+ change: function (field, value) {
+ let requireExpiry = field
+ .up('inputpanel')
+ .down('field[name=require-expiry]');
+ let implied = value !== null && value !== undefined;
+ // lock before setting, to keep the remembered choice
+ requireExpiry.setDisabled(implied);
+ requireExpiry.setValue(
+ implied || !!requireExpiry.explicitValue,
+ );
+ },
+ },
+ },
+ {
+ xtype: 'proxmoxcheckbox',
+ name: 'disallow-expiry-extension',
+ uncheckedValue: 0,
+ fieldLabel: gettext('Disallow Extending Expiration'),
+ },
+ {
+ xtype: 'proxmoxcheckbox',
+ name: 'require-privilege-separation',
+ uncheckedValue: 0,
+ fieldLabel: gettext('Require Privilege Separation'),
+ },
+ ],
+ },
+ ],
+ },
+ };
me.rows['tag-style'] = {
required: true,
renderer: (value) => {
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 manager 13/19] ui: token edit: adapt to the datacenter API token policy
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (11 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 manager 12/19] ui: dc options: allow editing the API token policy Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 14/19] ui: token policy: expose the default-to-max-lifetime setting Thomas Lamprecht
` (7 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Adapt the token dialogs up front when a datacenter token policy is
set: require and pre-fill a compliant expiration date, bound the date
picker, also by the current expiration date when the policy forbids
extending it, and lock privilege separation on. The policy is fetched
anew right before a token dialog opens, so a policy changed elsewhere
in the meantime is applied without needing a session reload; if that
fetch fails the last known policy is used, the backend enforces it on
the actual calls.
As the date field is day-granular, it is no use for a sub-day maximum
lifetime: at best a single future midnight fits the bound, covering
only an arbitrary fraction of it, and on the 25 hour day of a DST
transition even a one day maximum can lack one. In both cases the
dialog switches to a seconds-granular lifetime field, resolved to an
absolute expiration date only on submission to not lose validity
time; on edit it stays empty to keep the current expiration date.
Where the policy forbids extending, the resolved date is capped at the
current one, as the time left until then shrinks while the dialog is
open.
Both the date picker bound and the resolved lifetime follow the server
clock, estimated from the Date header of the policy fetch, as the
backend checks against its own clock. A browser clock running a few
seconds ahead would otherwise get the full maximum lifetime rejected,
and one running behind would shorten the validity, or for short
lifetimes submit an already expired date.
On edit the date picker is only bounded if the current expiration date
conforms, as tokens predating the policy would otherwise render the
form permanently invalid and block edits the backend explicitly
allows, since it only enforces settings that actually change.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
changes since v1:
- with 'disallow-expiry-extension', bound the date by the current one
instead of locking the field, and cap an entered lifetime at it
- follow the server clock, estimated from the policy fetch's Date header
- move the policy handling into methods
www/manager6/UIOptions.js | 23 +++++-
www/manager6/dc/OptionView.js | 1 +
www/manager6/dc/TokenEdit.js | 136 +++++++++++++++++++++++++++++++++-
www/manager6/dc/TokenView.js | 36 +++++----
4 files changed, 179 insertions(+), 17 deletions(-)
diff --git a/www/manager6/UIOptions.js b/www/manager6/UIOptions.js
index 8c4674af1..412fb32fa 100644
--- a/www/manager6/UIOptions.js
+++ b/www/manager6/UIOptions.js
@@ -10,7 +10,7 @@ Ext.define('PVE.UIOptions', {
url: '/cluster/options',
method: 'GET',
success: function (response) {
- for (const option of ['allowed-tags', 'console', 'tag-style']) {
+ for (const option of ['allowed-tags', 'console', 'tag-style', 'token-policy']) {
PVE.UIOptions.options[option] = response?.result?.data?.[option];
}
@@ -21,6 +21,27 @@ Ext.define('PVE.UIOptions', {
});
},
+ // milliseconds the server clock is ahead of the local one, estimated from the Date header of
+ // the last policy fetch, as the backend checks token lifetimes against its own clock; the
+ // header's second precision and the response delay bias it toward earlier dates
+ serverTimeOffset: 0,
+
+ serverNow: () => Date.now() + PVE.UIOptions.serverTimeOffset,
+
+ // the token policy can change independently of the tag settings, so refresh only that
+ // without triggering the resource store refresh a full update does; await this to act on
+ // a current policy
+ updateTokenPolicy: async function () {
+ try {
+ let response = await Proxmox.Async.api2({ url: '/cluster/options', method: 'GET' });
+ PVE.UIOptions.options['token-policy'] = response.result?.data?.['token-policy'];
+ let serverTime = Date.parse(response.getResponseHeader('Date'));
+ PVE.UIOptions.serverTimeOffset = isNaN(serverTime) ? 0 : serverTime - Date.now();
+ } catch {
+ // best effort, keep the last known policy, the backend enforces it in any case
+ }
+ },
+
tagList: [],
updateTagList: function (tags) {
diff --git a/www/manager6/dc/OptionView.js b/www/manager6/dc/OptionView.js
index d5bc1a538..666be8a52 100644
--- a/www/manager6/dc/OptionView.js
+++ b/www/manager6/dc/OptionView.js
@@ -753,6 +753,7 @@ Ext.define('PVE.dc.OptionView', {
}
PVE.UIOptions.options['tag-style'] = store.getById('tag-style')?.data?.value;
+ PVE.UIOptions.options['token-policy'] = store.getById('token-policy')?.data?.value;
PVE.UIOptions.updateTagSettings(PVE.UIOptions.options['tag-style']);
PVE.UIOptions.fireUIConfigChanged();
});
diff --git a/www/manager6/dc/TokenEdit.js b/www/manager6/dc/TokenEdit.js
index cf4e2ae2e..ad31db929 100644
--- a/www/manager6/dc/TokenEdit.js
+++ b/www/manager6/dc/TokenEdit.js
@@ -39,6 +39,18 @@ Ext.define('PVE.dc.TokenEdit', {
}
}
+ // resolve the lifetime only now, to not lose validity time while the dialog is open
+ let lifetimeField = me.down('field[name=token-lifetime]');
+ if (!lifetimeField.isDisabled() && lifetimeField.getValue()) {
+ values.expire =
+ Math.floor(PVE.UIOptions.serverNow() / 1000) + lifetimeField.getValue();
+ // the time left until the current expiration date shrinks while the dialog is
+ // open, so cap at that date where the policy forbids extending it
+ if (win.expireCap) {
+ values.expire = Math.min(values.expire, win.expireCap);
+ }
+ }
+
win.url += `${uid}/token/${tid}`;
return values;
},
@@ -82,6 +94,17 @@ Ext.define('PVE.dc.TokenEdit', {
xtype: 'pmxExpireDate',
name: 'expire',
},
+ {
+ // used instead of the date field for sub-day maximum lifetimes
+ xtype: 'numberfield',
+ name: 'token-lifetime',
+ submitValue: false,
+ hidden: true,
+ disabled: true,
+ allowDecimals: false,
+ minValue: 1,
+ fieldLabel: gettext('Lifetime (seconds)'),
+ },
],
columnB: [
{
@@ -97,15 +120,126 @@ Ext.define('PVE.dc.TokenEdit', {
me.callParent();
- if (!me.isCreate) {
+ // the backend enforces the policy in any case, applying it here guides the user
+ me.policy = PVE.UIOptions.options['token-policy'] || {};
+ if (me.policy['max-lifetime'] !== undefined) {
+ me.maxLifetime = Number(me.policy['max-lifetime']);
+ // computed once, so that the pre-filled default cannot drift past the bound
+ let now = PVE.UIOptions.serverNow();
+ me.maxDate = new Date(now + me.maxLifetime * 1000);
+ // the date field only offers midnights, at best covering an arbitrary part of a sub-day
+ // maximum, and on a 25 hour DST day a one day maximum may contain no midnight at all
+ let nextMidnight = new Date(now);
+ nextMidnight.setHours(24, 0, 0, 0);
+ me.useLifetimeField = me.maxLifetime < 86400 || nextMidnight > me.maxDate;
+ }
+ me.expiryRequired = !!Number(me.policy['require-expiry']) || me.maxDate !== undefined;
+
+ if (me.isCreate) {
+ me.applyPolicyOnCreate();
+ } else {
me.load({
success: function (response, options) {
me.setValues(response.result.data);
+ me.applyPolicyOnEdit();
},
});
}
},
+ applyPolicyOnCreate: function () {
+ let me = this;
+
+ let expireField = me.down('field[name=expire]');
+ if (me.useLifetimeField) {
+ expireField.setVisible(false);
+ expireField.setDisabled(true);
+ let lifetimeField = me.down('field[name=token-lifetime]');
+ lifetimeField.setVisible(true);
+ lifetimeField.setDisabled(false);
+ lifetimeField.setMaxValue(me.maxLifetime);
+ lifetimeField.allowBlank = false;
+ } else {
+ if (me.maxDate) {
+ expireField.setMaxValue(me.maxDate);
+ expireField.setValue(me.maxDate);
+ }
+ if (me.expiryRequired) {
+ expireField.allowBlank = false;
+ }
+ }
+
+ if (Number(me.policy['require-privilege-separation'])) {
+ let privilegeSeparationField = me.down('field[name=privsep]');
+ privilegeSeparationField.setValue(true);
+ privilegeSeparationField.setDisabled(true);
+ }
+ },
+
+ applyPolicyOnEdit: function () {
+ let me = this;
+
+ // privilege separation cannot be disabled again, while enabling it for a token that
+ // predates the policy stays possible
+ let privilegeSeparationField = me.down('field[name=privsep]');
+ if (
+ Number(me.policy['require-privilege-separation']) &&
+ privilegeSeparationField.getValue()
+ ) {
+ privilegeSeparationField.setDisabled(true);
+ }
+
+ // the policy may forbid moving the expiration date later or removing it
+ let noExtension = !!Number(me.policy['disallow-expiry-extension']) && !!me.originalExpire;
+ me.applyExpiryBounds(noExtension);
+ },
+
+ // bound a new expiration date by the maximum lifetime and, if extending is forbidden, by the
+ // current one
+ applyExpiryBounds: function (noExtension) {
+ let me = this;
+
+ let expireField = me.down('field[name=expire]');
+ if (me.useLifetimeField) {
+ // keep the current date visible but read-only, an empty lifetime keeps it
+ expireField.setDisabled(true);
+ let maxValue = me.maxLifetime;
+ me.expireCap = noExtension ? me.originalExpire : undefined;
+ if (noExtension) {
+ let remaining = me.originalExpire - Math.floor(PVE.UIOptions.serverNow() / 1000);
+ maxValue = Math.min(maxValue, remaining);
+ }
+ // an already expired token has nothing left to shorten
+ let usable = maxValue >= 1;
+ let lifetimeField = me.down('field[name=token-lifetime]');
+ lifetimeField.setVisible(usable);
+ lifetimeField.setDisabled(!usable);
+ if (usable) {
+ lifetimeField.setMaxValue(maxValue);
+ lifetimeField.setEmptyText(gettext('unchanged'));
+ }
+ return;
+ }
+
+ // removing an existing expiration date is a change the policy rejects; for a token without
+ // one, the field may stay blank, as the unchanged value is not submitted
+ expireField.allowBlank = !(me.originalExpire && (me.expiryRequired || noExtension));
+
+ // bound by the maximum lifetime only if the current date conforms, else the form would be
+ // stuck invalid for tokens that predate the policy, blocking edits the backend allows
+ let current = me.originalExpire ? new Date(me.originalExpire * 1000) : undefined;
+ let bound;
+ if (me.maxDate && (!current || current <= me.maxDate)) {
+ bound = me.maxDate;
+ }
+ if (noExtension && (!bound || current < bound)) {
+ // the date field compares whole days, so the current day stays selectable and is
+ // then dropped from submission as unchanged
+ bound = current;
+ }
+ expireField.setMaxValue(bound);
+ },
+
setValues: function (values) {
let me = this;
// remember the stored expiration date to detect a real change on submission; the
diff --git a/www/manager6/dc/TokenView.js b/www/manager6/dc/TokenView.js
index 8272729af..854eb4aad 100644
--- a/www/manager6/dc/TokenView.js
+++ b/www/manager6/dc/TokenView.js
@@ -61,20 +61,32 @@ Ext.define('PVE.dc.TokenView', {
return userid === Proxmox.UserName || !!caps.access['User.Modify'];
};
- let run_editor = function (rec) {
- if (!hasTokenCRUDPermissions(rec.data.userid)) {
- return;
+ let openPending = false;
+ let openTokenEditor = async function (editorConfig, values) {
+ if (openPending) {
+ return; // a slow policy refresh must not spawn duplicate windows
+ }
+ openPending = true;
+ // fetch the current policy first, the dialog adapts its fields to it
+ await PVE.UIOptions.updateTokenPolicy();
+ openPending = false;
+ if (me.destroyed || !me.isVisible(true)) {
+ return; // the user navigated away while the policy was being fetched
}
- let win = Ext.create('PVE.dc.TokenEdit', {
- method: 'PUT',
- url: urlFromRecord(rec),
- });
- win.setValues(rec.data);
+ let win = Ext.create('PVE.dc.TokenEdit', editorConfig);
+ win.setValues(values);
win.on('destroy', reload);
win.show();
};
+ let run_editor = function (rec) {
+ if (!hasTokenCRUDPermissions(rec.data.userid)) {
+ return;
+ }
+ openTokenEditor({ method: 'PUT', url: urlFromRecord(rec) }, rec.data);
+ };
+
let regenerate_token = function (_btn, _event, rec) {
if (!hasTokenCRUDPermissions(rec.data.userid)) {
return;
@@ -99,13 +111,7 @@ Ext.define('PVE.dc.TokenView', {
{
text: gettext('Add'),
handler: function (btn, e) {
- let data = {};
- let win = Ext.create('PVE.dc.TokenEdit', {
- isCreate: true,
- });
- win.setValues(data);
- win.on('destroy', reload);
- win.show();
+ openTokenEditor({ isCreate: true }, {});
},
},
{
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 manager 14/19] ui: token policy: expose the default-to-max-lifetime setting
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (12 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 manager 13/19] ui: token edit: adapt to the datacenter " Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 manager 15/19] ui: token policy: allow extension on secret regeneration Thomas Lamprecht
` (6 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Render and edit the new setting. It has no effect without a maximum
lifetime, so the checkbox is only enabled while one is entered and
gets cleared along with it.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
www/manager6/dc/OptionView.js | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/www/manager6/dc/OptionView.js b/www/manager6/dc/OptionView.js
index 666be8a52..38b4e8d6e 100644
--- a/www/manager6/dc/OptionView.js
+++ b/www/manager6/dc/OptionView.js
@@ -401,6 +401,9 @@ Ext.define('PVE.dc.OptionView', {
);
parts.push(Ext.String.format(gettext('Max. Lifetime: {0}'), lifetime));
}
+ if (Number(policy['default-to-max-lifetime'])) {
+ parts.push(gettext('Default to Max. Lifetime'));
+ }
if (Number(policy['disallow-expiry-extension'])) {
parts.push(gettext('Disallow Extending Expiration'));
}
@@ -446,6 +449,9 @@ Ext.define('PVE.dc.OptionView', {
if (me.down('field[name=require-expiry]').getValue()) {
policy['require-expiry'] = 1;
}
+ if (values['default-to-max-lifetime']) {
+ policy['default-to-max-lifetime'] = 1;
+ }
if (values['disallow-expiry-extension']) {
policy['disallow-expiry-extension'] = 1;
}
@@ -500,9 +506,29 @@ Ext.define('PVE.dc.OptionView', {
requireExpiry.setValue(
implied || !!requireExpiry.explicitValue,
);
+ let defaultToMax = field
+ .up('inputpanel')
+ .down('field[name=default-to-max-lifetime]');
+ defaultToMax.setDisabled(!implied);
+ if (!implied) {
+ defaultToMax.setValue(false);
+ }
},
},
},
+ {
+ xtype: 'proxmoxcheckbox',
+ name: 'default-to-max-lifetime',
+ uncheckedValue: 0,
+ disabled: true,
+ fieldLabel: gettext('Default to Max. Lifetime'),
+ autoEl: {
+ tag: 'div',
+ 'data-qtip': gettext(
+ 'Give tokens created without an expiration date the maximum lifetime instead of rejecting them.',
+ ),
+ },
+ },
{
xtype: 'proxmoxcheckbox',
name: 'disallow-expiry-extension',
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 manager 15/19] ui: token policy: allow extension on secret regeneration
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (13 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 manager 14/19] ui: token policy: expose the default-to-max-lifetime setting Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
` (5 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Expose the new allow-extension-on-regenerate setting in the datacenter
options, enabled only while extending is disallowed in general as it
has no effect otherwise, and offer a 'Regenerate Secret' checkbox in
the token edit dialog when the policy allows extending that way.
Ticking it lifts the bound by the current expiration date, the maximum
lifetime still applies, and the new secret is shown after saving like
for the separate regenerate action. As that action asks for
confirmation, a hint below the checkbox states that the current secret
stops working.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
www/manager6/dc/OptionView.js | 32 ++++++++++++++++++++++++++++++++
www/manager6/dc/TokenEdit.js | 29 +++++++++++++++++++++++++++++
2 files changed, 61 insertions(+)
diff --git a/www/manager6/dc/OptionView.js b/www/manager6/dc/OptionView.js
index 38b4e8d6e..b9db5a729 100644
--- a/www/manager6/dc/OptionView.js
+++ b/www/manager6/dc/OptionView.js
@@ -407,6 +407,9 @@ Ext.define('PVE.dc.OptionView', {
if (Number(policy['disallow-expiry-extension'])) {
parts.push(gettext('Disallow Extending Expiration'));
}
+ if (Number(policy['allow-extension-on-regenerate'])) {
+ parts.push(gettext('Allow Extension on Regeneration'));
+ }
if (Number(policy['require-privilege-separation'])) {
parts.push(gettext('Require Privilege Separation'));
}
@@ -455,6 +458,9 @@ Ext.define('PVE.dc.OptionView', {
if (values['disallow-expiry-extension']) {
policy['disallow-expiry-extension'] = 1;
}
+ if (values['allow-extension-on-regenerate']) {
+ policy['allow-extension-on-regenerate'] = 1;
+ }
if (values['require-privilege-separation']) {
policy['require-privilege-separation'] = 1;
}
@@ -534,6 +540,32 @@ Ext.define('PVE.dc.OptionView', {
name: 'disallow-expiry-extension',
uncheckedValue: 0,
fieldLabel: gettext('Disallow Extending Expiration'),
+ listeners: {
+ // allowing an extension on regeneration only makes sense
+ // while extending is disallowed in general
+ change: function (field, value) {
+ let allowOnRegenerate = field
+ .up('inputpanel')
+ .down('field[name=allow-extension-on-regenerate]');
+ allowOnRegenerate.setDisabled(!value);
+ if (!value) {
+ allowOnRegenerate.setValue(false);
+ }
+ },
+ },
+ },
+ {
+ xtype: 'proxmoxcheckbox',
+ name: 'allow-extension-on-regenerate',
+ uncheckedValue: 0,
+ disabled: true,
+ fieldLabel: gettext('Allow Extension on Regeneration'),
+ autoEl: {
+ tag: 'div',
+ 'data-qtip': gettext(
+ 'Allow extending the expiration date of a token when its secret is regenerated at the same time.',
+ ),
+ },
},
{
xtype: 'proxmoxcheckbox',
diff --git a/www/manager6/dc/TokenEdit.js b/www/manager6/dc/TokenEdit.js
index ad31db929..e0dd0d0fd 100644
--- a/www/manager6/dc/TokenEdit.js
+++ b/www/manager6/dc/TokenEdit.js
@@ -105,6 +105,24 @@ Ext.define('PVE.dc.TokenEdit', {
minValue: 1,
fieldLabel: gettext('Lifetime (seconds)'),
},
+ {
+ // offered when the policy allows extending the expiration date along with it
+ xtype: 'proxmoxcheckbox',
+ name: 'regenerate',
+ hidden: true,
+ disabled: true,
+ fieldLabel: gettext('Regenerate Secret'),
+ boxLabel: gettext('allows extending the expiration date'),
+ },
+ {
+ xtype: 'displayfield',
+ itemId: 'regenerateHint',
+ userCls: 'pmx-hint',
+ hidden: true,
+ value: gettext(
+ 'After saving, the current secret stops working and the new one is shown.',
+ ),
+ },
],
columnB: [
{
@@ -191,6 +209,16 @@ Ext.define('PVE.dc.TokenEdit', {
// the policy may forbid moving the expiration date later or removing it
let noExtension = !!Number(me.policy['disallow-expiry-extension']) && !!me.originalExpire;
+ if (noExtension && Number(me.policy['allow-extension-on-regenerate'])) {
+ let regenerateField = me.down('field[name=regenerate]');
+ let regenerateHint = me.down('#regenerateHint');
+ regenerateField.setVisible(true);
+ regenerateField.setDisabled(false);
+ regenerateField.on('change', (_field, regenerate) => {
+ regenerateHint.setVisible(regenerate);
+ me.applyExpiryBounds(!regenerate);
+ });
+ }
me.applyExpiryBounds(noExtension);
},
@@ -238,6 +266,7 @@ Ext.define('PVE.dc.TokenEdit', {
bound = current;
}
expireField.setMaxValue(bound);
+ expireField.validate();
},
setValues: function (values) {
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (14 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 manager 15/19] ui: token policy: allow extension on secret regeneration Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-17 13:29 ` Shannon Sterz
2026-11-15 19:40 ` [PATCH v2 proxmox 17/19] access-control: enforce token policy on token create and update Thomas Lamprecht
` (4 subsequent siblings)
20 siblings, 1 reply; 26+ messages in thread
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 [flat|nested] 26+ messages in thread* Re: [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks
2026-11-15 19:40 ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
@ 2026-11-17 13:29 ` Shannon Sterz
0 siblings, 0 replies; 26+ messages in thread
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 [flat|nested] 26+ messages in thread
* [PATCH v2 proxmox 17/19] access-control: enforce token policy on token create and update
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (15 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 proxmox 16/19] access-control: add API token policy type with expiry checks Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 proxmox 18/19] access-control: apply a default token lifetime from the policy Thomas Lamprecht
` (3 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
An update only checks the expiration date if its value 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, or rotated on update, to avoid
leaving an orphaned entry in the token shadow file, or losing the
old secret, for a rejected request.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
changes since v1:
- use separate expiry checks for new tokens and updates; fetch the
policy when an expiration date is submitted and let the update check
accept an unchanged date
proxmox-access-control/src/api/tokens.rs | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/proxmox-access-control/src/api/tokens.rs b/proxmox-access-control/src/api/tokens.rs
index f7417934..e2d144eb 100644
--- a/proxmox-access-control/src/api/tokens.rs
+++ b/proxmox-access-control/src/api/tokens.rs
@@ -97,6 +97,12 @@ pub fn generate_token(
);
}
+ // check the policy before generating the secret to avoid leaving an orphaned entry in the
+ // token shadow file on rejection
+ if let Some(policy) = crate::init::access_conf().token_policy()? {
+ policy.check_new_expiry(expire.unwrap_or(0), proxmox_time::epoch_i64())?;
+ }
+
let secret = token_shadow::generate_and_set_secret(&tokenid)?;
let token = ApiToken {
@@ -203,6 +209,10 @@ pub fn update_token(
}
if let Some(expire) = expire {
+ if let Some(policy) = crate::init::access_conf().token_policy()? {
+ let current = data.expire.unwrap_or(0);
+ policy.check_expiry_update(expire, current, proxmox_time::epoch_i64())?;
+ }
data.expire = if expire > 0 { Some(expire) } else { None };
}
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 proxmox 18/19] access-control: apply a default token lifetime from the policy
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (16 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 proxmox 17/19] access-control: enforce token policy on token create and update Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-15 19:40 ` [PATCH v2 proxmox 19/19] access-control: allow extending tokens on secret regeneration Thomas Lamprecht
` (2 subsequent siblings)
20 siblings, 0 replies; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Counterpart of the new 'default-to-max-lifetime' token policy setting
in PVE: tokens created without an expiration date get the maximum
lifetime when the policy opts into that, instead of being rejected, so
tools unaware of the policy still get a conforming token. Updates are
not affected, removing an expiration date there stays rejected.
Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
proxmox-access-control/src/api/tokens.rs | 14 ++++++--
proxmox-access-control/src/types.rs | 44 ++++++++++++++++++++++++
2 files changed, 56 insertions(+), 2 deletions(-)
diff --git a/proxmox-access-control/src/api/tokens.rs b/proxmox-access-control/src/api/tokens.rs
index e2d144eb..0ddcfdd3 100644
--- a/proxmox-access-control/src/api/tokens.rs
+++ b/proxmox-access-control/src/api/tokens.rs
@@ -97,10 +97,20 @@ pub fn generate_token(
);
}
+ let policy = crate::init::access_conf().token_policy()?;
+ let now = proxmox_time::epoch_i64();
+
+ let expire = match expire {
+ Some(expire) if expire > 0 => Some(expire),
+ _ => policy
+ .and_then(|policy| policy.default_expire(now))
+ .or(expire),
+ };
+
// check the policy before generating the secret to avoid leaving an orphaned entry in the
// token shadow file on rejection
- if let Some(policy) = crate::init::access_conf().token_policy()? {
- policy.check_new_expiry(expire.unwrap_or(0), proxmox_time::epoch_i64())?;
+ if let Some(policy) = policy {
+ policy.check_new_expiry(expire.unwrap_or(0), now)?;
}
let secret = token_shadow::generate_and_set_secret(&tokenid)?;
diff --git a/proxmox-access-control/src/types.rs b/proxmox-access-control/src/types.rs
index ce117376..1377bc50 100644
--- a/proxmox-access-control/src/types.rs
+++ b/proxmox-access-control/src/types.rs
@@ -189,6 +189,10 @@ pub struct TokenApiEntry {
optional: true,
default: false,
},
+ "default-to-max-lifetime": {
+ optional: true,
+ default: false,
+ },
},
)]
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize, Updater)]
@@ -214,9 +218,27 @@ pub struct TokenPolicy {
/// recreated.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub disallow_expiry_extension: Option<bool>,
+
+ /// Set the expiration date of API tokens created without one to the maximum lifetime instead
+ /// of rejecting them, for example for tools unaware of the policy. Has no effect without
+ /// `max-lifetime`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub default_to_max_lifetime: Option<bool>,
}
impl TokenPolicy {
+ /// The expiration date for a token created without one: `now` plus the maximum lifetime if the
+ /// policy opts into defaulting, `None` otherwise.
+ pub fn default_expire(&self, now: i64) -> Option<i64> {
+ if self.default_to_max_lifetime.unwrap_or_default()
+ && let Some(max_lifetime) = self.max_lifetime
+ {
+ Some(now.saturating_add_unsigned(max_lifetime))
+ } else {
+ None
+ }
+ }
+
/// 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)
@@ -422,6 +444,7 @@ mod tests {
require_expiry: None,
max_lifetime: None,
disallow_expiry_extension: None,
+ default_to_max_lifetime: None,
};
const REQUIRE_EXPIRY: TokenPolicy = TokenPolicy {
@@ -499,6 +522,27 @@ mod tests {
assert!(update_ok(&MAX_LIFETIME, NOW + MAX + 1, NOW + MAX + 1));
}
+ #[test]
+ fn default_to_max_lifetime() {
+ let policy = TokenPolicy {
+ default_to_max_lifetime: Some(true),
+ ..MAX_LIFETIME
+ };
+ assert_eq!(policy.default_expire(NOW), Some(NOW + MAX));
+ // only with a maximum lifetime to derive the default from, and only when opted into
+ assert_eq!(MAX_LIFETIME.default_expire(NOW), None);
+ let without_maximum = TokenPolicy {
+ default_to_max_lifetime: Some(true),
+ ..EMPTY
+ };
+ assert_eq!(without_maximum.default_expire(NOW), None);
+ let extreme = TokenPolicy {
+ max_lifetime: Some(u64::MAX),
+ ..policy
+ };
+ assert_eq!(extreme.default_expire(NOW), Some(i64::MAX));
+ }
+
#[test]
fn disallow_expiry_extension() {
// moving the expiration date later or removing it is rejected
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* [PATCH v2 proxmox 19/19] access-control: allow extending tokens on secret regeneration
2026-11-15 19:40 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (17 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 proxmox 18/19] access-control: apply a default token lifetime from the policy Thomas Lamprecht
@ 2026-11-15 19:40 ` Thomas Lamprecht
2026-11-17 13:29 ` Shannon Sterz
2026-11-17 13:29 ` [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Shannon Sterz
2026-11-18 2:17 ` applied: " Thomas Lamprecht
20 siblings, 1 reply; 26+ messages in thread
From: Thomas Lamprecht @ 2026-11-15 19:40 UTC (permalink / raw)
To: pve-devel
Counterpart of the new 'allow-extension-on-regenerate' token policy
setting in PVE: with it, an update that regenerates the secret may
also extend the expiration date despite 'disallow-expiry-extension',
as the old credential stops working just like it would on recreating
the token. The maximum lifetime still bounds the new date, and the
check still runs before the secret is regenerated.
Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
new in v2
proxmox-access-control/src/api/tokens.rs | 8 +++-
proxmox-access-control/src/types.rs | 56 ++++++++++++++++++++++--
2 files changed, 59 insertions(+), 5 deletions(-)
diff --git a/proxmox-access-control/src/api/tokens.rs b/proxmox-access-control/src/api/tokens.rs
index 0ddcfdd3..0c4d408f 100644
--- a/proxmox-access-control/src/api/tokens.rs
+++ b/proxmox-access-control/src/api/tokens.rs
@@ -220,8 +220,12 @@ pub fn update_token(
if let Some(expire) = expire {
if let Some(policy) = crate::init::access_conf().token_policy()? {
- let current = data.expire.unwrap_or(0);
- policy.check_expiry_update(expire, current, proxmox_time::epoch_i64())?;
+ policy.check_expiry_update(
+ expire,
+ data.expire.unwrap_or(0),
+ regenerate == Some(true),
+ proxmox_time::epoch_i64(),
+ )?;
}
data.expire = if expire > 0 { Some(expire) } else { None };
}
diff --git a/proxmox-access-control/src/types.rs b/proxmox-access-control/src/types.rs
index 1377bc50..7b8bb5ca 100644
--- a/proxmox-access-control/src/types.rs
+++ b/proxmox-access-control/src/types.rs
@@ -193,6 +193,10 @@ pub struct TokenApiEntry {
optional: true,
default: false,
},
+ "allow-extension-on-regenerate": {
+ optional: true,
+ default: false,
+ },
},
)]
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize, Updater)]
@@ -224,6 +228,12 @@ pub struct TokenPolicy {
/// `max-lifetime`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_to_max_lifetime: Option<bool>,
+
+ /// Allow extending the expiration date of an existing API token when its secret is
+ /// regenerated in the same request, despite `disallow-expiry-extension`. The maximum lifetime
+ /// still applies.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub allow_extension_on_regenerate: Option<bool>,
}
impl TokenPolicy {
@@ -248,13 +258,22 @@ impl TokenPolicy {
///
/// `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> {
+ /// `regenerate` tells whether the update also regenerates the secret.
+ pub fn check_expiry_update(
+ &self,
+ expire: i64,
+ current: i64,
+ regenerate: bool,
+ now: i64,
+ ) -> Result<(), Error> {
if expire == current {
return Ok(());
}
- // removing the expiration date or moving it later extends the token
+ // removing the expiration date or moving it later extends the token; regenerating the
+ // secret along with it is like recreating the token, which the policy may allow
if self.disallow_expiry_extension.unwrap_or_default()
+ && !(regenerate && self.allow_extension_on_regenerate.unwrap_or_default())
&& current != 0
&& (expire == 0 || expire > current)
{
@@ -445,6 +464,7 @@ mod tests {
max_lifetime: None,
disallow_expiry_extension: None,
default_to_max_lifetime: None,
+ allow_extension_on_regenerate: None,
};
const REQUIRE_EXPIRY: TokenPolicy = TokenPolicy {
@@ -467,7 +487,16 @@ mod tests {
}
fn update_ok(policy: &TokenPolicy, expire: i64, current: i64) -> bool {
- policy.check_expiry_update(expire, current, NOW).is_ok()
+ policy
+ .check_expiry_update(expire, current, false, NOW)
+ .is_ok()
+ }
+
+ // an update that also regenerates the secret
+ fn rotate_ok(policy: &TokenPolicy, expire: i64, current: i64) -> bool {
+ policy
+ .check_expiry_update(expire, current, true, NOW)
+ .is_ok()
}
#[test]
@@ -558,6 +587,27 @@ mod tests {
assert!(create_ok(&NO_EXTENSION, 0));
}
+ #[test]
+ fn allow_extension_on_regenerate() {
+ let policy = TokenPolicy {
+ allow_extension_on_regenerate: Some(true),
+ ..NO_EXTENSION
+ };
+ // extending or removing the date passes only together with a secret regeneration
+ assert!(rotate_ok(&policy, NOW + 200, CURRENT));
+ assert!(rotate_ok(&policy, 0, CURRENT));
+ assert!(!update_ok(&policy, NOW + 200, CURRENT));
+ // a policy without the setting ignores the regeneration
+ assert!(!rotate_ok(&NO_EXTENSION, NOW + 200, CURRENT));
+ // the maximum lifetime still bounds the extension
+ let bounded = TokenPolicy {
+ max_lifetime: Some(MAX as u64),
+ ..policy
+ };
+ assert!(rotate_ok(&bounded, NOW + MAX, CURRENT));
+ assert!(!rotate_ok(&bounded, NOW + MAX + 1, CURRENT));
+ }
+
#[test]
fn disallow_expiry_extension_combined() {
let policy = TokenPolicy {
--
2.47.3
^ permalink raw reply related [flat|nested] 26+ messages in thread* Re: [PATCH v2 proxmox 19/19] access-control: allow extending tokens on secret regeneration
2026-11-15 19:40 ` [PATCH v2 proxmox 19/19] access-control: allow extending tokens on secret regeneration Thomas Lamprecht
@ 2026-11-17 13:29 ` Shannon Sterz
0 siblings, 0 replies; 26+ messages in thread
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 new 'allow-extension-on-regenerate' token policy
> setting in PVE: with it, an update that regenerates the secret may
> also extend the expiration date despite 'disallow-expiry-extension',
> as the old credential stops working just like it would on recreating
> the token. The maximum lifetime still bounds the new date, and the
> check still runs before the secret is regenerated.
>
> Suggested-by: Shannon Sterz <s.sterz@proxmox.com>
> Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
> ---
>
> new in v2
>
> proxmox-access-control/src/api/tokens.rs | 8 +++-
> proxmox-access-control/src/types.rs | 56 ++++++++++++++++++++++--
> 2 files changed, 59 insertions(+), 5 deletions(-)
>
> diff --git a/proxmox-access-control/src/api/tokens.rs b/proxmox-access-control/src/api/tokens.rs
> index 0ddcfdd3..0c4d408f 100644
> --- a/proxmox-access-control/src/api/tokens.rs
> +++ b/proxmox-access-control/src/api/tokens.rs
> @@ -220,8 +220,12 @@ pub fn update_token(
>
> if let Some(expire) = expire {
> if let Some(policy) = crate::init::access_conf().token_policy()? {
> - let current = data.expire.unwrap_or(0);
> - policy.check_expiry_update(expire, current, proxmox_time::epoch_i64())?;
> + policy.check_expiry_update(
> + expire,
> + data.expire.unwrap_or(0),
> + regenerate == Some(true),
nit: an `unwrap_or_default()` would have the same effect and may be
considered more idiomatic
-->8 snip 8<--
^ permalink raw reply [flat|nested] 26+ messages in thread
* 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 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (18 preceding siblings ...)
2026-11-15 19:40 ` [PATCH v2 proxmox 19/19] access-control: allow extending tokens on secret regeneration Thomas Lamprecht
@ 2026-11-17 13:29 ` Shannon Sterz
2026-11-18 2:17 ` applied: " Thomas Lamprecht
20 siblings, 0 replies; 26+ messages in thread
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 [flat|nested] 26+ messages in thread* 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 [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Thomas Lamprecht
` (19 preceding siblings ...)
2026-11-17 13:29 ` [PATCH v2 cluster/access-control/docs/manager/proxmox 0/19] fix #7805: add a datacenter-wide API token policy Shannon Sterz
@ 2026-11-18 2:17 ` Thomas Lamprecht
20 siblings, 0 replies; 26+ messages in thread
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 [flat|nested] 26+ messages in thread