From add2ceef67d0d36de55ae09f8d644cfc13b40c44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Renault?= Date: Tue, 28 Nov 2023 14:21:49 +0100 Subject: [PATCH] Introduce error types to avoid panics --- meilisearch-auth/src/store.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/meilisearch-auth/src/store.rs b/meilisearch-auth/src/store.rs index 742fd8d4e..276c035b0 100644 --- a/meilisearch-auth/src/store.rs +++ b/meilisearch-auth/src/store.rs @@ -17,6 +17,7 @@ use meilisearch_types::milli; use meilisearch_types::milli::heed::types::{Bytes, DecodeIgnore, SerdeJson}; use meilisearch_types::milli::heed::{Database, Env, EnvOpenOptions, RwTxn}; use sha2::Sha256; +use thiserror::Error; use time::OffsetDateTime; use uuid::fmt::Hyphenated; use uuid::Uuid; @@ -297,13 +298,14 @@ impl<'a> milli::heed::BytesDecode<'a> for KeyIdActionCodec { type DItem = (KeyId, Action, Option<&'a [u8]>); fn bytes_decode(bytes: &'a [u8]) -> StdResult { - let (key_id_bytes, action_bytes) = try_split_array_at(bytes).unwrap(); - let (action_bytes, index) = match try_split_array_at(action_bytes).unwrap() { - (action, []) => (action, None), - (action, index) => (action, Some(index)), - }; + let (key_id_bytes, action_bytes) = try_split_array_at(bytes).ok_or(SliceTooShortError)?; + let (&action_byte, index) = + match try_split_array_at(action_bytes).ok_or(SliceTooShortError)? { + ([action], []) => (action, None), + ([action], index) => (action, Some(index)), + }; let key_id = Uuid::from_bytes(*key_id_bytes); - let action = Action::from_repr(u8::from_be_bytes(*action_bytes)).unwrap(); + let action = Action::from_repr(action_byte).ok_or(InvalidActionError { action_byte })?; Ok((key_id, action, index)) } @@ -326,6 +328,16 @@ impl<'a> milli::heed::BytesEncode<'a> for KeyIdActionCodec { } } +#[derive(Error, Debug)] +#[error("the slice is too short")] +pub struct SliceTooShortError; + +#[derive(Error, Debug)] +#[error("cannot construct a valid Action from {action_byte}")] +pub struct InvalidActionError { + pub action_byte: u8, +} + pub fn generate_key_as_hexa(uid: Uuid, master_key: &[u8]) -> String { // format uid as hyphenated allowing user to generate their own keys. let mut uid_buffer = [0; Hyphenated::LENGTH];