From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68]) by lore.proxmox.com (Postfix) with ESMTPS id D001C1FF15C for ; Fri, 3 Oct 2025 16:21:50 +0200 (CEST) Received: from firstgate.proxmox.com (localhost [127.0.0.1]) by firstgate.proxmox.com (Proxmox) with ESMTP id 6C9FA54FD; Fri, 3 Oct 2025 16:21:50 +0200 (CEST) From: Shannon Sterz To: pdm-devel@lists.proxmox.com Date: Fri, 3 Oct 2025 16:21:03 +0200 Message-ID: <20251003142108.352525-4-s.sterz@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20251003142108.352525-1-s.sterz@proxmox.com> References: <20251003142108.352525-1-s.sterz@proxmox.com> MIME-Version: 1.0 X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1759501248741 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.057 Adjusted score from AWL reputation of From: address BAYES_00 -1.9 Bayes spam probability is 0 to 1% DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Subject: [pdm-devel] [PATCH proxmox 3/3] access-control: add api endpoints for handling tokens X-BeenThere: pdm-devel@lists.proxmox.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Proxmox Datacenter Manager development discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: Proxmox Datacenter Manager development discussion Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Errors-To: pdm-devel-bounces@lists.proxmox.com Sender: "pdm-devel" 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 --- 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 { + 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, + enable: Option, + expire: Option, + digest: Option, +) -> Result { + 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, + enable: Option, + expire: Option, + regenerate: Option, + delete: Option>, + digest: Option, +) -> Result, 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, +) -> 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, Error> { + let (config, digest) = crate::user::config()?; + + let list: Vec = 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 { + 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, } + +#[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