Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ log = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
time = { version = "0.3.7", features = ["serde-well-known", "formatting", "parsing"] }
jsonwebtoken = { version = "8", default-features = false }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
futures = "0.3"
Expand Down
18 changes: 18 additions & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,24 @@ impl Client {

Ok(tasks.results)
}

/// Generates a new tenant token.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::*;
/// # futures::executor::block_on(async move {
/// # let client = client::Client::new("http://localhost:7700", "masterKey");
/// let token = client.generate_tenant_token(serde_json::json!(["*"]), None, None).unwrap();
/// let client = client::Client::new("http://localhost:7700", token);
/// # });
/// ```
pub fn generate_tenant_token(&self, search_rules: serde_json::Value, api_key: Option<&str>, expires_at: Option<OffsetDateTime>) -> Result<String, Error> {
let api_key = api_key.unwrap_or(&self.api_key);

crate::tenant_tokens::generate_tenant_token(search_rules, api_key, expires_at)
}
}

#[derive(Deserialize)]
Expand Down
18 changes: 18 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ pub enum Error {
/// It probably comes from an invalid API key resulting in an invalid HTTP header.
InvalidRequest,

/// It is not possible to generate a tenant token with a invalid api key.
/// Empty strings or with less than 8 characters are considered invalid.
TenantTokensInvalidApiKey,
/// It is not possible to generate an already expired tenant token.
TenantTokensExpiredSignature,

/// When jsonwebtoken cannot generate the token successfully.
InvalidTenantToken(jsonwebtoken::errors::Error),

/// The http client encountered an error.
#[cfg(not(target_arch = "wasm32"))]
HttpError(isahc::Error),
Expand Down Expand Up @@ -52,6 +61,12 @@ impl From<MeilisearchError> for Error {
}
}

impl From<jsonwebtoken::errors::Error> for Error {
fn from(error: jsonwebtoken::errors::Error) -> Error {
Error::InvalidTenantToken(error)
}
}

/// The type of error that was encountered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -168,6 +183,9 @@ impl std::fmt::Display for Error {
Error::ParseError(e) => write!(fmt, "Error parsing response JSON: {}", e),
Error::HttpError(e) => write!(fmt, "HTTP request failed: {}", e),
Error::Timeout => write!(fmt, "A task did not succeed in time."),
Error::TenantTokensInvalidApiKey => write!(fmt, "The provided api_key is invalid."),
Error::TenantTokensExpiredSignature => write!(fmt, "The provided expires_at is already expired."),
Error::InvalidTenantToken(e) => write!(fmt, "Impossible to generate the token, jsonwebtoken encountered an error: {}", e)
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ pub mod search;
pub mod settings;
/// Module representing the [tasks::Task]s.
pub mod tasks;
/// Module that generates tenant tokens.
mod tenant_tokens;

#[cfg(feature = "sync")]
pub(crate) type Rc<T> = std::sync::Arc<T>;
Expand Down
37 changes: 36 additions & 1 deletion src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ mod tests {
use crate::{client::*, search::*};
use meilisearch_test_macro::meilisearch_test;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use serde_json::{Map, Value, json};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Document {
Expand Down Expand Up @@ -571,4 +571,39 @@ mod tests {
assert_eq!(results.hits.len(), 1);
Ok(())
}

#[meilisearch_test]
async fn test_generate_tenant_token_from_client(client: Client, index: Index) -> Result<(), Error> {
use crate::key::{KeyBuilder, Action};

setup_test_index(&client, &index).await?;

let key = KeyBuilder::new("key for generate_tenant_token test")
.with_action(Action::All)
.with_index("*")
.create(&client).await.unwrap();
let allowed_client = Client::new("http://localhost:7700", key.key);

let search_rules = vec![
json!({ "*": {}}),
json!({ "*": Value::Null }),
json!(["*"]),
json!({ "*": { "filter": "kind = text" } }),
json!([index.uid.to_string()]),
];

for rules in search_rules {
let token = allowed_client.generate_tenant_token(rules, None, None).expect("Cannot generate tenant token.");
let new_client = Client::new("http://localhost:7700", token);

let result: SearchResults<Document> = new_client.index(index.uid.to_string())
.search()
.execute()
.await?;

assert!(!result.hits.is_empty());
}

Ok(())
}
}
127 changes: 127 additions & 0 deletions src/tenant_tokens.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use crate::{
errors::*
};
use serde::{Serialize, Deserialize};
use jsonwebtoken::{encode, Header, EncodingKey};
use time::{OffsetDateTime};
use serde_json::Value;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TenantTokenClaim {
api_key_prefix: String,
search_rules: Value,
#[serde(with = "time::serde::timestamp::option")]
exp: Option<OffsetDateTime>,
}

pub fn generate_tenant_token(search_rules: Value, api_key: impl AsRef<str>, expires_at: Option<OffsetDateTime>) -> Result<String, Error> {
if api_key.as_ref().chars().count() < 8 {
return Err(Error::TenantTokensInvalidApiKey)
}

if expires_at.map_or(false, |expires_at| OffsetDateTime::now_utc() > expires_at) {
return Err(Error::TenantTokensExpiredSignature)
}

let key_prefix = api_key.as_ref().chars().take(8).collect();
let claims = TenantTokenClaim {
api_key_prefix: key_prefix,
exp: expires_at,
search_rules
};

let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(api_key.as_ref().as_bytes()),
);

Ok(token?)
}

#[cfg(test)]
mod tests {
use serde_json::json;
use crate::tenant_tokens::*;
use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
use std::collections::HashSet;

const SEARCH_RULES: [&str; 1] = ["*"];
const VALID_KEY: &str = "a19b6ec84ee31324efa560cd1f7e6939";

fn build_validation() -> Validation {
let mut validation = Validation::new(Algorithm::HS256);
validation.validate_exp = false;
validation.required_spec_claims = HashSet::new();

validation
}

#[test]
fn test_generate_token_with_given_key() {
let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, None).unwrap();

let valid_key = decode::<TenantTokenClaim>(
&token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &build_validation()
);
let invalid_key = decode::<TenantTokenClaim>(
&token, &DecodingKey::from_secret("not-the-same-key".as_ref()), &build_validation()
);

assert!(valid_key.is_ok());
assert!(invalid_key.is_err());
}

#[test]
fn test_generate_token_without_key() {
let key = String::from("");
let token = generate_tenant_token(json!(SEARCH_RULES), &key, None);

assert!(token.is_err());
}

#[test]
fn test_generate_token_with_expiration() {
let exp = OffsetDateTime::now_utc() + time::Duration::HOUR;
let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, Some(exp)).unwrap();

let decoded = decode::<TenantTokenClaim>(
&token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &Validation::new(Algorithm::HS256)
);

assert!(decoded.is_ok());
}

#[test]
fn test_generate_token_with_expires_at_in_the_past() {
let exp = OffsetDateTime::now_utc() - time::Duration::HOUR;
let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, Some(exp));

assert!(token.is_err());
}

#[test]
fn test_generate_token_contains_claims() {
let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, None).unwrap();

let decoded = decode::<TenantTokenClaim>(
&token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &build_validation()
).expect("Cannot decode the token");

assert_eq!(decoded.claims.api_key_prefix, &VALID_KEY[..8]);
assert_eq!(decoded.claims.search_rules, json!(SEARCH_RULES));
}

#[test]
fn test_generate_token_with_multi_byte_chars() {
let key = "Ëa1ทt9bVcL-vãUทtP3OpXW5qPc%bWH5ทvw09";
let token = generate_tenant_token(json!(SEARCH_RULES), key, None).unwrap();

let decoded = decode::<TenantTokenClaim>(
&token, &DecodingKey::from_secret(key.as_ref()), &build_validation()
).expect("Cannot decode the token");

assert_eq!(decoded.claims.api_key_prefix, "Ëa1ทt9bV");
}
}