From: Shannon Sterz <s.sterz@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [pdm-devel] [PATCH proxmox 3/3] access-control: add api endpoints for handling tokens
Date: Fri, 3 Oct 2025 16:21:03 +0200 [thread overview]
Message-ID: <20251003142108.352525-4-s.sterz@proxmox.com> (raw)
In-Reply-To: <20251003142108.352525-1-s.sterz@proxmox.com>
by adding most of the logic of token creation, updating and deleting
here, users can more easily add api tokens to their api. this requires
the api feature.
users of these api endpoints are expected to set the `access`
parameters according to their needs. by default only super users can
access any of them.
Signed-off-by: Shannon Sterz <s.sterz@proxmox.com>
---
proxmox-access-control/Cargo.toml | 1 +
proxmox-access-control/src/api/mod.rs | 6 +
proxmox-access-control/src/api/tokens.rs | 310 +++++++++++++++++++++
proxmox-access-control/src/token_shadow.rs | 8 +
proxmox-access-control/src/types.rs | 33 ++-
5 files changed, 357 insertions(+), 1 deletion(-)
create mode 100644 proxmox-access-control/src/api/tokens.rs
diff --git a/proxmox-access-control/Cargo.toml b/proxmox-access-control/Cargo.toml
index dbcbeced..2c4e0628 100644
--- a/proxmox-access-control/Cargo.toml
+++ b/proxmox-access-control/Cargo.toml
@@ -31,6 +31,7 @@ proxmox-section-config = { workspace = true, optional = true }
proxmox-shared-memory = { workspace = true, optional = true }
proxmox-sys = { workspace = true, features = [ "crypt" ], optional = true }
proxmox-time = { workspace = true }
+proxmox-uuid = { workspace = true }
[features]
default = []
diff --git a/proxmox-access-control/src/api/mod.rs b/proxmox-access-control/src/api/mod.rs
index 5e17dc76..59dc32e2 100644
--- a/proxmox-access-control/src/api/mod.rs
+++ b/proxmox-access-control/src/api/mod.rs
@@ -1,2 +1,8 @@
+mod tokens;
+pub use tokens::{
+ API_METHOD_DELETE_TOKEN, API_METHOD_GENERATE_TOKEN, API_METHOD_LIST_TOKENS,
+ API_METHOD_READ_TOKEN, API_METHOD_UPDATE_TOKEN,
+};
+
mod acl;
pub use acl::{ACL_ROUTER, API_METHOD_READ_ACL, API_METHOD_UPDATE_ACL, ROLE_ROUTER};
diff --git a/proxmox-access-control/src/api/tokens.rs b/proxmox-access-control/src/api/tokens.rs
new file mode 100644
index 00000000..e86b26b7
--- /dev/null
+++ b/proxmox-access-control/src/api/tokens.rs
@@ -0,0 +1,310 @@
+//! User Management
+
+use anyhow::{bail, Error};
+use proxmox_config_digest::ConfigDigest;
+use proxmox_schema::api_types::COMMENT_SCHEMA;
+
+use proxmox_auth_api::types::{Authid, Tokenname, Userid};
+use proxmox_router::{ApiMethod, RpcEnvironment};
+use proxmox_schema::api;
+
+use crate::acl;
+use crate::token_shadow::{self};
+use crate::types::{
+ ApiToken, ApiTokenSecret, DeletableTokenProperty, TokenApiEntry, ENABLE_USER_SCHEMA,
+ EXPIRE_USER_SCHEMA, REGENERATE_TOKEN_SCHEMA,
+};
+
+#[api(
+ input: {
+ properties: {
+ userid: {
+ type: Userid,
+ },
+ "token-name": {
+ type: Tokenname,
+ },
+ },
+ },
+ returns: { type: ApiToken },
+)]
+/// Read user's API token metadata
+pub fn read_token(
+ userid: Userid,
+ token_name: Tokenname,
+ _info: &ApiMethod,
+ rpcenv: &mut dyn RpcEnvironment,
+) -> Result<ApiToken, Error> {
+ let (config, digest) = crate::user::config()?;
+
+ let tokenid = Authid::from((userid, Some(token_name)));
+
+ rpcenv["digest"] = hex::encode(digest).into();
+ config.lookup("token", &tokenid.to_string())
+}
+
+#[api(
+ protected: true,
+ input: {
+ properties: {
+ userid: {
+ type: Userid,
+ },
+ "token-name": {
+ type: Tokenname,
+ },
+ comment: {
+ optional: true,
+ schema: COMMENT_SCHEMA,
+ },
+ enable: {
+ schema: ENABLE_USER_SCHEMA,
+ optional: true,
+ },
+ expire: {
+ schema: EXPIRE_USER_SCHEMA,
+ optional: true,
+ },
+ digest: {
+ optional: true,
+ type: ConfigDigest,
+ },
+ },
+ },
+ returns: { type: ApiTokenSecret },
+)]
+/// Generate a new API token with given metadata
+pub fn generate_token(
+ userid: Userid,
+ token_name: Tokenname,
+ comment: Option<String>,
+ enable: Option<bool>,
+ expire: Option<i64>,
+ digest: Option<ConfigDigest>,
+) -> Result<ApiTokenSecret, Error> {
+ let _lock = crate::user::lock_config()?;
+ let (mut config, config_digest) = crate::user::config()?;
+
+ config_digest.detect_modification(digest.as_ref())?;
+
+ let tokenid = Authid::from((userid.clone(), Some(token_name.clone())));
+ let tokenid_string = tokenid.to_string();
+
+ if config.sections.contains_key(&tokenid_string) {
+ bail!(
+ "token '{}' for user '{userid}' already exists.",
+ token_name.as_str(),
+ );
+ }
+
+ let secret = token_shadow::generate_and_set_secret(&tokenid)?;
+
+ let token = ApiToken {
+ tokenid: tokenid.clone(),
+ comment,
+ enable,
+ expire,
+ };
+
+ config.set_data(&tokenid_string, "token", &token)?;
+
+ crate::user::save_config(&config)?;
+
+ Ok(ApiTokenSecret { tokenid, secret })
+}
+
+#[api(
+ protected: true,
+ input: {
+ properties: {
+ userid: {
+ type: Userid,
+ },
+ "token-name": {
+ type: Tokenname,
+ },
+ comment: {
+ optional: true,
+ schema: COMMENT_SCHEMA,
+ },
+ enable: {
+ schema: ENABLE_USER_SCHEMA,
+ optional: true,
+ },
+ expire: {
+ schema: EXPIRE_USER_SCHEMA,
+ optional: true,
+ },
+ regenerate: {
+ schema: REGENERATE_TOKEN_SCHEMA,
+ optional: true,
+ },
+ delete: {
+ description: "List of properties to delete.",
+ type: Array,
+ optional: true,
+ items: {
+ type: DeletableTokenProperty,
+ }
+ },
+ digest: {
+ optional: true,
+ type: ConfigDigest,
+ },
+ },
+ },
+ returns: {
+ type: ApiTokenSecret,
+ optional: true
+ }
+)]
+/// Update user's API token metadata. If regenerate is set to true, the token and it's new secret
+/// will be returned.
+#[allow(clippy::too_many_arguments)]
+
+pub fn update_token(
+ userid: Userid,
+ token_name: Tokenname,
+ comment: Option<String>,
+ enable: Option<bool>,
+ expire: Option<i64>,
+ regenerate: Option<bool>,
+ delete: Option<Vec<DeletableTokenProperty>>,
+ digest: Option<ConfigDigest>,
+) -> Result<Option<ApiTokenSecret>, Error> {
+ let _lock = crate::user::lock_config()?;
+
+ let (mut config, config_digest) = crate::user::config()?;
+ config_digest.detect_modification(digest.as_ref())?;
+
+ let tokenid = Authid::from((userid, Some(token_name)));
+ let tokenid_string = tokenid.to_string();
+
+ let mut data: ApiToken = config.lookup("token", &tokenid_string)?;
+
+ if let Some(delete) = delete {
+ for delete_prop in delete {
+ match delete_prop {
+ DeletableTokenProperty::Comment => data.comment = None,
+ }
+ }
+ }
+
+ if let Some(comment) = comment {
+ let comment = comment.trim().to_string();
+ if comment.is_empty() {
+ data.comment = None;
+ } else {
+ data.comment = Some(comment);
+ }
+ }
+
+ if let Some(enable) = enable {
+ data.enable = if enable { None } else { Some(false) };
+ }
+
+ if let Some(expire) = expire {
+ data.expire = if expire > 0 { Some(expire) } else { None };
+ }
+
+ let new_secret = if regenerate == Some(true) {
+ let secret = token_shadow::generate_and_set_secret(&tokenid)?;
+ Some(ApiTokenSecret { tokenid, secret })
+ } else {
+ None
+ };
+
+ config.set_data(&tokenid_string, "token", &data)?;
+
+ crate::user::save_config(&config)?;
+
+ Ok(new_secret)
+}
+
+#[api(
+ protected: true,
+ input: {
+ properties: {
+ userid: {
+ type: Userid,
+ },
+ "token-name": {
+ type: Tokenname,
+ },
+ digest: {
+ optional: true,
+ type: ConfigDigest,
+ },
+ },
+ },
+)]
+/// Delete a user's API token
+pub fn delete_token(
+ userid: Userid,
+ token_name: Tokenname,
+ digest: Option<ConfigDigest>,
+) -> Result<(), Error> {
+ let _acl_lock = acl::lock_config()?;
+ let _user_lock = crate::user::lock_config()?;
+
+ let (mut user_config, config_digest) = crate::user::config()?;
+ config_digest.detect_modification(digest.as_ref())?;
+ let (mut acl_config, _digest) = crate::acl::config()?;
+
+ let tokenid = Authid::from((userid.clone(), Some(token_name.clone())));
+ let tokenid_string = tokenid.to_string();
+
+ if user_config.sections.remove(&tokenid_string).is_none() {
+ bail!(
+ "token '{}' of user '{userid}' does not exist.",
+ token_name.as_str(),
+ );
+ }
+
+ token_shadow::delete_secret(&tokenid)?;
+ acl_config.delete_authid(&tokenid);
+ crate::user::save_config(&user_config)?;
+ crate::acl::save_config(&acl_config)?;
+
+ Ok(())
+}
+
+#[api(
+ input: {
+ properties: {
+ userid: {
+ type: Userid,
+ },
+ },
+ },
+ returns: {
+ description: "List user's API tokens (with config digest).",
+ type: Array,
+ items: { type: TokenApiEntry },
+ },
+)]
+/// List user's API tokens
+pub fn list_tokens(
+ userid: Userid,
+ _info: &ApiMethod,
+ rpcenv: &mut dyn RpcEnvironment,
+) -> Result<Vec<TokenApiEntry>, Error> {
+ let (config, digest) = crate::user::config()?;
+
+ let list: Vec<ApiToken> = config.convert_to_typed_array("token")?;
+
+ rpcenv["digest"] = hex::encode(digest).into();
+
+ let filter_by_owner = |token: ApiToken| {
+ if token.tokenid.is_token() && token.tokenid.user() == &userid {
+ let token_name = token.tokenid.tokenname().unwrap().to_owned();
+ Some(TokenApiEntry { token_name, token })
+ } else {
+ None
+ }
+ };
+
+ let res = list.into_iter().filter_map(filter_by_owner).collect();
+
+ Ok(res)
+}
diff --git a/proxmox-access-control/src/token_shadow.rs b/proxmox-access-control/src/token_shadow.rs
index 46397edb..373910f3 100644
--- a/proxmox-access-control/src/token_shadow.rs
+++ b/proxmox-access-control/src/token_shadow.rs
@@ -73,3 +73,11 @@ pub fn delete_secret(tokenid: &Authid) -> Result<(), Error> {
Ok(())
}
+
+/// Generates a new secret for the given tokenid / API token, sets it then returns it.
+/// The secret is stored as salted hash.
+pub fn generate_and_set_secret(tokenid: &Authid) -> Result<String, Error> {
+ let secret = format!("{:x}", proxmox_uuid::Uuid::generate());
+ set_secret(tokenid, &secret)?;
+ Ok(secret)
+}
diff --git a/proxmox-access-control/src/types.rs b/proxmox-access-control/src/types.rs
index 9c539f7b..85b1f106 100644
--- a/proxmox-access-control/src/types.rs
+++ b/proxmox-access-control/src/types.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use const_format::concatcp;
-use proxmox_auth_api::types::{Authid, Userid, PROXMOX_TOKEN_ID_SCHEMA};
+use proxmox_auth_api::types::{Authid, Tokenname, Userid, PROXMOX_TOKEN_ID_SCHEMA};
use proxmox_schema::{
api,
api_types::{COMMENT_SCHEMA, SAFE_ID_REGEX_STR, SINGLE_LINE_COMMENT_FORMAT},
@@ -154,9 +154,26 @@ impl ApiToken {
pub struct ApiTokenSecret {
pub tokenid: Authid,
/// The secret associated with the token.
+ // rename to `value` as that is what it is called in the api
+ #[serde(rename = "value")]
pub secret: String,
}
+#[api(
+ properties: {
+ token: { type: ApiToken },
+ }
+)]
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+/// A Token Entry that contains the token-name
+pub struct TokenApiEntry {
+ /// The Token name
+ pub token_name: Tokenname,
+ #[serde(flatten)]
+ pub token: ApiToken,
+}
+
#[api(
properties: {
userid: {
@@ -285,3 +302,17 @@ pub struct RoleInfo {
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
}
+
+#[api()]
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+/// The set of properties that can be deleted from a token.
+pub enum DeletableTokenProperty {
+ /// Delete the comment property.
+ Comment,
+}
+
+pub const REGENERATE_TOKEN_SCHEMA: Schema =
+ BooleanSchema::new("Regenerate token secret while keeping permissions.")
+ .default(false)
+ .schema();
--
2.47.3
_______________________________________________
pdm-devel mailing list
pdm-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel
next prev parent reply other threads:[~2025-10-03 14:21 UTC|newest]
Thread overview: 12+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-10-03 14:21 [pdm-devel] [PATCH datacenter-manager/proxmox/yew-comp 0/8] add better token support for pdm Shannon Sterz
2025-10-03 14:21 ` [pdm-devel] [PATCH proxmox 1/3] access-control: refactor api module to be more hirachical Shannon Sterz
2025-10-03 14:21 ` [pdm-devel] [PATCH proxmox 2/3] access-control: move `ApiTokenSecret` to types module Shannon Sterz
2025-10-03 14:21 ` Shannon Sterz [this message]
2025-10-03 14:21 ` [pdm-devel] [PATCH yew-comp 1/2] utils/tfa add recover/token panel: add copy_text_to_clipboard function Shannon Sterz
2025-10-03 14:21 ` [pdm-devel] [PATCH yew-comp 2/2] token panel: improve token secret dialog layout and hide password Shannon Sterz
2025-10-03 14:21 ` [pdm-devel] [PATCH datacenter-manager 1/3] ui: add a token panel and a token acl edit menu in the permissions panel Shannon Sterz
2025-10-03 14:21 ` [pdm-devel] [PATCH datacenter-manager 2/3] server: access: use token endpoints from proxmox-access-control Shannon Sterz
2025-10-03 14:21 ` [pdm-devel] [PATCH datacenter-manager 3/3] server: clean up acl tree entries and api tokens when deleting users Shannon Sterz
-- strict thread matches above, loose matches on Subject: below --
2025-09-24 14:51 [pdm-devel] [RFC datacenter-manager/proxmox/yew-comp 0/8] token support for pdm Shannon Sterz
2025-09-24 14:51 ` [pdm-devel] [PATCH proxmox 3/3] access-control: add api endpoints for handling tokens Shannon Sterz
2025-09-26 9:14 ` Fabian Grünbichler
2025-10-01 15:29 ` Shannon Sterz
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=20251003142108.352525-4-s.sterz@proxmox.com \
--to=s.sterz@proxmox.com \
--cc=pdm-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.