From mboxrd@z Thu Jan  1 00:00:00 1970
Return-Path: <d.csapak@proxmox.com>
Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68])
 (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)
 key-exchange X25519 server-signature RSA-PSS (2048 bits))
 (No client certificate requested)
 by lists.proxmox.com (Postfix) with ESMTPS id 5564D6AB4C
 for <pbs-devel@lists.proxmox.com>; Fri, 17 Sep 2021 13:56:49 +0200 (CEST)
Received: from firstgate.proxmox.com (localhost [127.0.0.1])
 by firstgate.proxmox.com (Proxmox) with ESMTP id A5AD92F2EC
 for <pbs-devel@lists.proxmox.com>; Fri, 17 Sep 2021 13:56:18 +0200 (CEST)
Received: from proxmox-new.maurer-it.com (proxmox-new.maurer-it.com
 [94.136.29.106])
 (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)
 key-exchange X25519 server-signature RSA-PSS (2048 bits))
 (No client certificate requested)
 by firstgate.proxmox.com (Proxmox) with ESMTPS id 332972F28D
 for <pbs-devel@lists.proxmox.com>; Fri, 17 Sep 2021 13:56:15 +0200 (CEST)
Received: from proxmox-new.maurer-it.com (localhost.localdomain [127.0.0.1])
 by proxmox-new.maurer-it.com (Proxmox) with ESMTP id 6433844934
 for <pbs-devel@lists.proxmox.com>; Fri, 17 Sep 2021 13:56:09 +0200 (CEST)
From: Dominik Csapak <d.csapak@proxmox.com>
To: pbs-devel@lists.proxmox.com
Date: Fri, 17 Sep 2021 13:56:04 +0200
Message-Id: <20210917115607.135162-5-d.csapak@proxmox.com>
X-Mailer: git-send-email 2.30.2
In-Reply-To: <20210917115607.135162-1-d.csapak@proxmox.com>
References: <20210917115607.135162-1-d.csapak@proxmox.com>
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
X-SPAM-LEVEL: Spam detection results:  0
 AWL 0.379 Adjusted score from AWL reputation of From: address
 BAYES_00                 -1.9 Bayes spam probability is 0 to 1%
 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
 URIBL_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to URIBL was blocked. See
 http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block for more
 information. [user.rs]
Subject: [pbs-devel] [PATCH proxmox-backup v3 4/7] api2: add missing token
 list match_all property
X-BeenThere: pbs-devel@lists.proxmox.com
X-Mailman-Version: 2.1.29
Precedence: list
List-Id: Proxmox Backup Server development discussion
 <pbs-devel.lists.proxmox.com>
List-Unsubscribe: <https://lists.proxmox.com/cgi-bin/mailman/options/pbs-devel>, 
 <mailto:pbs-devel-request@lists.proxmox.com?subject=unsubscribe>
List-Archive: <http://lists.proxmox.com/pipermail/pbs-devel/>
List-Post: <mailto:pbs-devel@lists.proxmox.com>
List-Help: <mailto:pbs-devel-request@lists.proxmox.com?subject=help>
List-Subscribe: <https://lists.proxmox.com/cgi-bin/mailman/listinfo/pbs-devel>, 
 <mailto:pbs-devel-request@lists.proxmox.com?subject=subscribe>
X-List-Received-Date: Fri, 17 Sep 2021 11:56:49 -0000

to have the proper link between the token list and the sub routes
in the api, include the 'tokenname' property in the token listing

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
 src/api2/access/user.rs                | 66 +++++++++++++++++---------
 src/bin/proxmox_backup_manager/user.rs |  6 +--
 2 files changed, 47 insertions(+), 25 deletions(-)

diff --git a/src/api2/access/user.rs b/src/api2/access/user.rs
index 75071cf1..1d866214 100644
--- a/src/api2/access/user.rs
+++ b/src/api2/access/user.rs
@@ -395,7 +395,7 @@ pub fn delete_user(userid: Userid, digest: Option<String>) -> Result<(), Error>
             userid: {
                 type: Userid,
             },
-            tokenname: {
+            "token-name": {
                 type: Tokenname,
             },
         },
@@ -411,14 +411,14 @@ pub fn delete_user(userid: Userid, digest: Option<String>) -> Result<(), Error>
 /// Read user's API token metadata
 pub fn read_token(
     userid: Userid,
-    tokenname: Tokenname,
+    token_name: Tokenname,
     _info: &ApiMethod,
     mut rpcenv: &mut dyn RpcEnvironment,
 ) -> Result<ApiToken, Error> {
 
     let (config, digest) = pbs_config::user::config()?;
 
-    let tokenid = Authid::from((userid, Some(tokenname)));
+    let tokenid = Authid::from((userid, Some(token_name)));
 
     rpcenv["digest"] = proxmox::tools::digest_to_hex(&digest).into();
     config.lookup("token", &tokenid.to_string())
@@ -431,7 +431,7 @@ pub fn read_token(
             userid: {
                 type: Userid,
             },
-            tokenname: {
+            "token-name": {
                 type: Tokenname,
             },
             comment: {
@@ -475,7 +475,7 @@ pub fn read_token(
 /// Generate a new API token with given metadata
 pub fn generate_token(
     userid: Userid,
-    tokenname: Tokenname,
+    token_name: Tokenname,
     comment: Option<String>,
     enable: Option<bool>,
     expire: Option<i64>,
@@ -491,11 +491,11 @@ pub fn generate_token(
         crate::tools::detect_modified_configuration_file(&digest, &expected_digest)?;
     }
 
-    let tokenid = Authid::from((userid.clone(), Some(tokenname.clone())));
+    let tokenid = Authid::from((userid.clone(), Some(token_name.clone())));
     let tokenid_string = tokenid.to_string();
 
     if config.sections.get(&tokenid_string).is_some() {
-        bail!("token '{}' for user '{}' already exists.", tokenname.as_str(), userid);
+        bail!("token '{}' for user '{}' already exists.", token_name.as_str(), userid);
     }
 
     let secret = format!("{:x}", proxmox::tools::uuid::Uuid::generate());
@@ -525,7 +525,7 @@ pub fn generate_token(
             userid: {
                 type: Userid,
             },
-            tokenname: {
+            "token-name": {
                 type: Tokenname,
             },
             comment: {
@@ -556,7 +556,7 @@ pub fn generate_token(
 /// Update user's API token metadata
 pub fn update_token(
     userid: Userid,
-    tokenname: Tokenname,
+    token_name: Tokenname,
     comment: Option<String>,
     enable: Option<bool>,
     expire: Option<i64>,
@@ -572,7 +572,7 @@ pub fn update_token(
         crate::tools::detect_modified_configuration_file(&digest, &expected_digest)?;
     }
 
-    let tokenid = Authid::from((userid, Some(tokenname)));
+    let tokenid = Authid::from((userid, Some(token_name)));
     let tokenid_string = tokenid.to_string();
 
     let mut data: ApiToken = config.lookup("token", &tokenid_string)?;
@@ -608,7 +608,7 @@ pub fn update_token(
             userid: {
                 type: Userid,
             },
-            tokenname: {
+            "token-name": {
                 type: Tokenname,
             },
             digest: {
@@ -627,7 +627,7 @@ pub fn update_token(
 /// Delete a user's API token
 pub fn delete_token(
     userid: Userid,
-    tokenname: Tokenname,
+    token_name: Tokenname,
     digest: Option<String>,
 ) -> Result<(), Error> {
 
@@ -640,12 +640,12 @@ pub fn delete_token(
         crate::tools::detect_modified_configuration_file(&digest, &expected_digest)?;
     }
 
-    let tokenid = Authid::from((userid.clone(), Some(tokenname.clone())));
+    let tokenid = Authid::from((userid.clone(), Some(token_name.clone())));
     let tokenid_string = tokenid.to_string();
 
     match config.sections.get(&tokenid_string) {
         Some(_) => { config.sections.remove(&tokenid_string); },
-        None => bail!("token '{}' of user '{}' does not exist.", tokenname.as_str(), userid),
+        None => bail!("token '{}' of user '{}' does not exist.", token_name.as_str(), userid),
     }
 
     token_shadow::delete_secret(&tokenid)?;
@@ -655,6 +655,22 @@ pub fn delete_token(
     Ok(())
 }
 
+#[api(
+    properties: {
+        "token-name": { type: Tokenname },
+        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(
     input: {
         properties: {
@@ -666,7 +682,7 @@ pub fn delete_token(
     returns: {
         description: "List user's API tokens (with config digest).",
         type: Array,
-        items: { type: ApiToken },
+        items: { type: TokenApiEntry },
     },
     access: {
         permission: &Permission::Or(&[
@@ -680,7 +696,7 @@ pub fn list_tokens(
     userid: Userid,
     _info: &ApiMethod,
     mut rpcenv: &mut dyn RpcEnvironment,
-) -> Result<Vec<ApiToken>, Error> {
+) -> Result<Vec<TokenApiEntry>, Error> {
 
     let (config, digest) = pbs_config::user::config()?;
 
@@ -688,15 +704,21 @@ pub fn list_tokens(
 
     rpcenv["digest"] = proxmox::tools::digest_to_hex(&digest).into();
 
-    let filter_by_owner = |token: &ApiToken| {
-        if token.tokenid.is_token() {
-           token.tokenid.user() == &userid
+    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 {
-            false
+            None
         }
     };
 
-    Ok(list.into_iter().filter(filter_by_owner).collect())
+    let res = list.into_iter().filter_map(filter_by_owner).collect();
+
+    Ok(res)
 }
 
 const TOKEN_ITEM_ROUTER: Router = Router::new()
@@ -707,7 +729,7 @@ const TOKEN_ITEM_ROUTER: Router = Router::new()
 
 const TOKEN_ROUTER: Router = Router::new()
     .get(&API_METHOD_LIST_TOKENS)
-    .match_all("tokenname", &TOKEN_ITEM_ROUTER);
+    .match_all("token-name", &TOKEN_ITEM_ROUTER);
 
 const USER_SUBDIRS: SubdirMap = &[
     ("token", &TOKEN_ROUTER),
diff --git a/src/bin/proxmox_backup_manager/user.rs b/src/bin/proxmox_backup_manager/user.rs
index 9681ba79..cff66ce7 100644
--- a/src/bin/proxmox_backup_manager/user.rs
+++ b/src/bin/proxmox_backup_manager/user.rs
@@ -198,15 +198,15 @@ pub fn user_commands() -> CommandLineInterface {
         .insert(
             "generate-token",
             CliCommand::new(&api2::access::user::API_METHOD_GENERATE_TOKEN)
-                .arg_param(&["userid", "tokenname"])
+                .arg_param(&["userid", "token-name"])
                 .completion_cb("userid", pbs_config::user::complete_userid)
         )
         .insert(
             "delete-token",
             CliCommand::new(&api2::access::user::API_METHOD_DELETE_TOKEN)
-                .arg_param(&["userid", "tokenname"])
+                .arg_param(&["userid", "token-name"])
                 .completion_cb("userid", pbs_config::user::complete_userid)
-                .completion_cb("tokenname", pbs_config::user::complete_token_name)
+                .completion_cb("token-name", pbs_config::user::complete_token_name)
         )
         .insert(
             "permissions",
-- 
2.30.2