public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Wolfgang Bumiller <w.bumiller@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [pbs-devel] [PATCH backup 1/2] tfa: remember recovery indices
Date: Mon, 18 Jan 2021 12:46:46 +0100	[thread overview]
Message-ID: <20210118114647.632-1-w.bumiller@proxmox.com> (raw)

and tell the client which keys are still available rather
than just yes/no/low

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
---
 src/config/tfa.rs | 76 ++++++++++++++++++++++-------------------------
 1 file changed, 35 insertions(+), 41 deletions(-)

diff --git a/src/config/tfa.rs b/src/config/tfa.rs
index e0f2fcfe..5d01ea82 100644
--- a/src/config/tfa.rs
+++ b/src/config/tfa.rs
@@ -1088,7 +1088,7 @@ impl TfaUserData {
 #[derive(Deserialize, Serialize)]
 pub struct Recovery {
     secret: String,
-    entries: Vec<String>,
+    entries: Vec<Option<String>>,
 }
 
 impl Recovery {
@@ -1116,7 +1116,7 @@ impl Recovery {
                 AsHex(&b[6..8]),
             );
 
-            this.entries.push(this.hash(entry.as_bytes())?);
+            this.entries.push(Some(this.hash(entry.as_bytes())?));
             original.push(entry);
         }
 
@@ -1138,31 +1138,32 @@ impl Recovery {
         Ok(AsHex(&hmac).to_string())
     }
 
-    /// Shortcut to get the count.
-    fn len(&self) -> usize {
-        self.entries.len()
+    /// Iterator over available keys.
+    fn available(&self) -> impl Iterator<Item = &str> {
+        self.entries.iter().filter_map(Option::as_deref)
     }
 
-    /// Check if this entry is empty.
-    fn is_empty(&self) -> bool {
-        self.entries.is_empty()
+    /// Count the available keys.
+    fn count_available(&self) -> usize {
+        self.available().count()
     }
 
     /// Convenience serde method to check if either the option is `None` or the content `is_empty`.
     fn option_is_empty(this: &Option<Self>) -> bool {
-        this.as_ref().map_or(true, Self::is_empty)
+        this.as_ref()
+            .map_or(true, |this| this.count_available() == 0)
     }
 
     /// Verify a key and remove it. Returns whether the key was valid. Errors on openssl errors.
     fn verify(&mut self, key: &str) -> Result<bool, Error> {
         let hash = self.hash(key.as_bytes())?;
-        Ok(match self.entries.iter().position(|entry| *entry == hash) {
-            Some(index) => {
-                self.entries.remove(index);
-                true
+        for entry in &mut self.entries {
+            if entry.as_ref() == Some(&hash) {
+                *entry = None;
+                return Ok(true);
             }
-            None => false,
-        })
+        }
+        Ok(false)
     }
 }
 
@@ -1283,45 +1284,38 @@ pub fn verify_challenge(
 }
 
 /// Used to inform the user about the recovery code status.
-#[derive(Clone, Copy, Eq, PartialEq, Deserialize, Serialize)]
-#[serde(rename_all = "kebab-case")]
-pub enum RecoveryState {
-    Unavailable,
-    Low,
-    Available,
-}
+///
+/// This contains the available key indices.
+#[derive(Clone, Default, Eq, PartialEq, Deserialize, Serialize)]
+pub struct RecoveryState(Vec<usize>);
 
 impl RecoveryState {
-    fn from_count(count: usize) -> Self {
-        match count {
-            0 => RecoveryState::Unavailable,
-            1..=3 => RecoveryState::Low,
-            _ => RecoveryState::Available,
-        }
-    }
-
-    // serde needs `&self` but this is a tiny Copy type, so we mark this as inline
-    #[inline]
     fn is_unavailable(&self) -> bool {
-        *self == RecoveryState::Unavailable
-    }
-}
-
-impl Default for RecoveryState {
-    fn default() -> Self {
-        RecoveryState::Unavailable
+        self.0.is_empty()
     }
 }
 
 impl From<&Option<Recovery>> for RecoveryState {
     fn from(r: &Option<Recovery>) -> Self {
         match r {
-            Some(r) => Self::from_count(r.len()),
-            None => RecoveryState::Unavailable,
+            Some(r) => Self::from(r),
+            None => Self::default(),
         }
     }
 }
 
+impl From<&Recovery> for RecoveryState {
+    fn from(r: &Recovery) -> Self {
+        Self(
+            r.entries
+                .iter()
+                .enumerate()
+                .filter_map(|(idx, key)| if key.is_some() { Some(idx) } else { None })
+                .collect(),
+        )
+    }
+}
+
 /// When sending a TFA challenge to the user, we include information about what kind of challenge
 /// the user may perform. If webauthn credentials are available, a webauthn challenge will be
 /// included.
-- 
2.20.1





             reply	other threads:[~2021-01-18 11:46 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2021-01-18 11:46 Wolfgang Bumiller [this message]
2021-01-18 11:46 ` [pbs-devel] [PATCH backup 2/2] gui: enumerate recovery keys and list in 2nd factor window Wolfgang Bumiller
2021-01-18 12:52   ` [pbs-devel] applied: " Thomas Lamprecht
2021-01-18 12:52 ` [pbs-devel] applied: [PATCH backup 1/2] tfa: remember recovery indices 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=20210118114647.632-1-w.bumiller@proxmox.com \
    --to=w.bumiller@proxmox.com \
    --cc=pbs-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 a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal