From 66e18eae79d3ce20f2a50bbf17995b1838e6050f Mon Sep 17 00:00:00 2001 From: Louis Dureuil Date: Thu, 22 Dec 2022 11:55:27 +0100 Subject: [PATCH] auth: add generate_master_key function --- Cargo.lock | 1 + meilisearch-auth/Cargo.toml | 1 + meilisearch-auth/src/lib.rs | 16 ++++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index fb3c0daa2..db954797d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2352,6 +2352,7 @@ dependencies = [ name = "meilisearch-auth" version = "1.0.0" dependencies = [ + "base64", "enum-iterator", "hmac", "meilisearch-types", diff --git a/meilisearch-auth/Cargo.toml b/meilisearch-auth/Cargo.toml index fbddc14d0..383be69cf 100644 --- a/meilisearch-auth/Cargo.toml +++ b/meilisearch-auth/Cargo.toml @@ -4,6 +4,7 @@ version = "1.0.0" edition = "2021" [dependencies] +base64 = "0.13.1" enum-iterator = "1.1.3" hmac = "0.12.1" meilisearch-types = { path = "../meilisearch-types" } diff --git a/meilisearch-auth/src/lib.rs b/meilisearch-auth/src/lib.rs index 020a2821c..ea6bf34a0 100644 --- a/meilisearch-auth/src/lib.rs +++ b/meilisearch-auth/src/lib.rs @@ -268,3 +268,19 @@ fn generate_default_keys(store: &HeedAuthStore) -> Result<()> { Ok(()) } + +pub const MASTER_KEY_MIN_SIZE: usize = 16; +const MASTER_KEY_GEN_SIZE: usize = 32; + +pub fn generate_master_key() -> String { + use rand::rngs::OsRng; + use rand::RngCore; + + let mut csprng = OsRng; + let mut buf = vec![0; MASTER_KEY_GEN_SIZE]; + csprng.fill_bytes(&mut buf); + + // let's encode the random bytes to base64 to make them human-readable and not too long. + // We're using the URL_SAFE alphabet that will produce keys without =, / or other unusual characters. + base64::encode_config(buf, base64::URL_SAFE_NO_PAD) +}