From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 714311FF09D for ; Sun, 15 Nov 2026 20:43:32 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 5113621910; Sun, 15 Nov 2026 20:41:11 +0100 (CET) From: Thomas Lamprecht 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 Message-ID: <20261115194043.3947825-14-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261115194043.3947825-1-t.lamprecht@proxmox.com> References: <20261115194043.3947825-1-t.lamprecht@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1794771649838 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.225 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: VNTJUQ6XPIZ34SVDJ4DRMCQ7Y36C6OXV X-Message-ID-Hash: VNTJUQ6XPIZ34SVDJ4DRMCQ7Y36C6OXV X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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