From 4512eed8f53590397dd23695010ae03168ed58ee Mon Sep 17 00:00:00 2001
From: ManyTheFish <many@meilisearch.com>
Date: Wed, 1 Jun 2022 18:06:20 +0200
Subject: [PATCH] Fix PR comments

---
 meilisearch-auth/Cargo.toml                   |  2 +-
 meilisearch-auth/src/key.rs                   |  2 +-
 meilisearch-auth/src/lib.rs                   | 19 ++++++++++---------
 meilisearch-auth/src/store.rs                 | 12 +++++++++---
 .../src/extractors/authentication/mod.rs      |  2 +-
 meilisearch-http/src/routes/api_key.rs        |  9 ++++++---
 meilisearch-http/tests/auth/api_keys.rs       |  2 +-
 7 files changed, 29 insertions(+), 19 deletions(-)

diff --git a/meilisearch-auth/Cargo.toml b/meilisearch-auth/Cargo.toml
index dafeeef05..29fa78a14 100644
--- a/meilisearch-auth/Cargo.toml
+++ b/meilisearch-auth/Cargo.toml
@@ -4,6 +4,7 @@ version = "0.27.1"
 edition = "2021"
 
 [dependencies]
+base64 = "0.13.0"
 enum-iterator = "0.7.0"
 meilisearch-error = { path = "../meilisearch-error" }
 milli = { git = "https://github.com/meilisearch/milli.git", tag = "v0.28.0" }
@@ -11,7 +12,6 @@ rand = "0.8.4"
 serde = { version = "1.0.136", features = ["derive"] }
 serde_json = { version = "1.0.79", features = ["preserve_order"] }
 sha2 = "0.10.2"
-base64 = "0.13.0"
 thiserror = "1.0.30"
 time = { version = "0.3.7", features = ["serde-well-known", "formatting", "parsing", "macros"] }
 uuid = { version = "0.8.2", features = ["serde", "v4"] }
diff --git a/meilisearch-auth/src/key.rs b/meilisearch-auth/src/key.rs
index f6ff7096c..0e336a7db 100644
--- a/meilisearch-auth/src/key.rs
+++ b/meilisearch-auth/src/key.rs
@@ -133,7 +133,7 @@ impl Key {
         let uid = Uuid::new_v4();
         Self {
             name: Some("Default Admin API Key".to_string()),
-            description: Some("Use it for all other than search operations. Caution! Do not expose it on a public frontend".to_string()),
+            description: Some("Use it for anything that is not a search operation. Caution! Do not expose it on a public frontend".to_string()),
             uid,
             actions: vec![Action::All],
             indexes: vec!["*".to_string()],
diff --git a/meilisearch-auth/src/lib.rs b/meilisearch-auth/src/lib.rs
index 578093abf..e41fd92f4 100644
--- a/meilisearch-auth/src/lib.rs
+++ b/meilisearch-auth/src/lib.rs
@@ -4,20 +4,19 @@ pub mod error;
 mod key;
 mod store;
 
-use crate::store::generate_key;
 use std::collections::{HashMap, HashSet};
 use std::path::Path;
-
 use std::sync::Arc;
-use uuid::Uuid;
 
 use serde::{Deserialize, Serialize};
 use serde_json::Value;
 use time::OffsetDateTime;
+use uuid::Uuid;
 
 pub use action::{actions, Action};
 use error::{AuthControllerError, Result};
 pub use key::Key;
+use store::generate_key_as_base64;
 pub use store::open_auth_store_env;
 use store::HeedAuthStore;
 
@@ -63,16 +62,18 @@ impl AuthController {
             .ok_or_else(|| AuthControllerError::ApiKeyNotFound(uid.to_string()))
     }
 
-    pub fn get_optional_uid_from_sha(&self, sha: &[u8]) -> Result<Option<Uuid>> {
+    pub fn get_optional_uid_from_encoded_key(&self, encoded_key: &[u8]) -> Result<Option<Uuid>> {
         match &self.master_key {
-            Some(master_key) => self.store.get_uid_from_sha(sha, master_key.as_bytes()),
+            Some(master_key) => self
+                .store
+                .get_uid_from_encoded_key(encoded_key, master_key.as_bytes()),
             None => Ok(None),
         }
     }
 
-    pub fn get_uid_from_sha(&self, sha: &str) -> Result<Uuid> {
-        self.get_optional_uid_from_sha(sha.as_bytes())?
-            .ok_or_else(|| AuthControllerError::ApiKeyNotFound(sha.to_string()))
+    pub fn get_uid_from_encoded_key(&self, encoded_key: &str) -> Result<Uuid> {
+        self.get_optional_uid_from_encoded_key(encoded_key.as_bytes())?
+            .ok_or_else(|| AuthControllerError::ApiKeyNotFound(encoded_key.to_string()))
     }
 
     pub fn get_key_filters(
@@ -134,7 +135,7 @@ impl AuthController {
     pub fn generate_key(&self, uid: Uuid) -> Option<String> {
         self.master_key
             .as_ref()
-            .map(|master_key| generate_key(uid.as_bytes(), master_key.as_bytes()))
+            .map(|master_key| generate_key_as_base64(uid.as_bytes(), master_key.as_bytes()))
     }
 
     /// Check if the provided key is authorized to make a specific action
diff --git a/meilisearch-auth/src/store.rs b/meilisearch-auth/src/store.rs
index 64cf49544..69c4cbd57 100644
--- a/meilisearch-auth/src/store.rs
+++ b/meilisearch-auth/src/store.rs
@@ -118,14 +118,20 @@ impl HeedAuthStore {
         self.keys.get(&rtxn, uid.as_bytes()).map_err(|e| e.into())
     }
 
-    pub fn get_uid_from_sha(&self, key_sha: &[u8], master_key: &[u8]) -> Result<Option<Uuid>> {
+    pub fn get_uid_from_encoded_key(
+        &self,
+        encoded_key: &[u8],
+        master_key: &[u8],
+    ) -> Result<Option<Uuid>> {
         let rtxn = self.env.read_txn()?;
         let uid = self
             .keys
             .remap_data_type::<DecodeIgnore>()
             .iter(&rtxn)?
             .filter_map(|res| match res {
-                Ok((uid, _)) if generate_key(uid, master_key).as_bytes() == key_sha => {
+                Ok((uid, _))
+                    if generate_key_as_base64(uid, master_key).as_bytes() == encoded_key =>
+                {
                     let (uid, _) = try_split_array_at(uid)?;
                     Some(Uuid::from_bytes(*uid))
                 }
@@ -235,7 +241,7 @@ impl<'a> milli::heed::BytesEncode<'a> for KeyIdActionCodec {
     }
 }
 
-pub fn generate_key(uid: &[u8], master_key: &[u8]) -> String {
+pub fn generate_key_as_base64(uid: &[u8], master_key: &[u8]) -> String {
     let key = [uid, master_key].concat();
     let sha = Sha256::digest(&key);
     base64::encode_config(sha, base64::URL_SAFE_NO_PAD)
diff --git a/meilisearch-http/src/extractors/authentication/mod.rs b/meilisearch-http/src/extractors/authentication/mod.rs
index 99f972984..7732bd7fa 100644
--- a/meilisearch-http/src/extractors/authentication/mod.rs
+++ b/meilisearch-http/src/extractors/authentication/mod.rs
@@ -188,7 +188,7 @@ pub mod policies {
                 return Some(filters);
             } else if let Some(action) = Action::from_repr(A) {
                 // API key
-                if let Ok(Some(uid)) = auth.get_optional_uid_from_sha(token.as_bytes()) {
+                if let Ok(Some(uid)) = auth.get_optional_uid_from_encoded_key(token.as_bytes()) {
                     if let Ok(true) = auth.is_key_authorized(uid, action, index) {
                         return auth.get_key_filters(uid, None).ok();
                     }
diff --git a/meilisearch-http/src/routes/api_key.rs b/meilisearch-http/src/routes/api_key.rs
index cfe81b301..831a350d8 100644
--- a/meilisearch-http/src/routes/api_key.rs
+++ b/meilisearch-http/src/routes/api_key.rs
@@ -69,7 +69,8 @@ pub async fn get_api_key(
     let key = path.into_inner().key;
 
     let res = tokio::task::spawn_blocking(move || -> Result<_, AuthControllerError> {
-        let uid = Uuid::parse_str(&key).or_else(|_| auth_controller.get_uid_from_sha(&key))?;
+        let uid =
+            Uuid::parse_str(&key).or_else(|_| auth_controller.get_uid_from_encoded_key(&key))?;
         let key = auth_controller.get_key(uid)?;
 
         Ok(KeyView::from_key(key, &auth_controller))
@@ -88,7 +89,8 @@ pub async fn patch_api_key(
     let key = path.into_inner().key;
     let body = body.into_inner();
     let res = tokio::task::spawn_blocking(move || -> Result<_, AuthControllerError> {
-        let uid = Uuid::parse_str(&key).or_else(|_| auth_controller.get_uid_from_sha(&key))?;
+        let uid =
+            Uuid::parse_str(&key).or_else(|_| auth_controller.get_uid_from_encoded_key(&key))?;
         let key = auth_controller.update_key(uid, body)?;
 
         Ok(KeyView::from_key(key, &auth_controller))
@@ -105,7 +107,8 @@ pub async fn delete_api_key(
 ) -> Result<HttpResponse, ResponseError> {
     let key = path.into_inner().key;
     tokio::task::spawn_blocking(move || {
-        let uid = Uuid::parse_str(&key).or_else(|_| auth_controller.get_uid_from_sha(&key))?;
+        let uid =
+            Uuid::parse_str(&key).or_else(|_| auth_controller.get_uid_from_encoded_key(&key))?;
         auth_controller.delete_key(uid)
     })
     .await
diff --git a/meilisearch-http/tests/auth/api_keys.rs b/meilisearch-http/tests/auth/api_keys.rs
index a9f2bf91d..4eb1fdd6f 100644
--- a/meilisearch-http/tests/auth/api_keys.rs
+++ b/meilisearch-http/tests/auth/api_keys.rs
@@ -711,7 +711,7 @@ async fn list_api_keys() {
         },
         {
             "name": "Default Admin API Key",
-            "description": "Use it for all other than search operations. Caution! Do not expose it on a public frontend",
+            "description": "Use it for anything that is not a search operation. Caution! Do not expose it on a public frontend",
             "indexes": ["*"],
             "actions": ["*"],
             "expiresAt": serde_json::Value::Null,