all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH v2 manager 13/19] ui: token edit: adapt to the datacenter API token policy
Date: Sun, 15 Nov 2026 20:40:34 +0100	[thread overview]
Message-ID: <20261115194043.3947825-14-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261115194043.3947825-1-t.lamprecht@proxmox.com>

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





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

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

Reply instructions:

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

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

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

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

  git send-email \
    --in-reply-to=20261115194043.3947825-14-t.lamprecht@proxmox.com \
    --to=t.lamprecht@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

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

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