Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adde API for ACL validation #294

Merged
merged 5 commits into from
Mar 21, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 2 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ commands:
parameters:
redis_version:
type: string
default: "6"
default: "7"
getredis_params:
type: string
default: ""
Expand Down Expand Up @@ -97,7 +97,7 @@ commands:
default: ""
redis_version:
type: string
default: "6"
default: "7"
getredis_params:
type: string
default: ""
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ crate-type = ["cdylib"]
name = "string"
crate-type = ["cdylib"]

[[example]]
name = "acl"
crate-type = ["cdylib"]

[[example]]
name = "call"
crate-type = ["cdylib"]
Expand Down
33 changes: 33 additions & 0 deletions examples/acl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#[macro_use]
extern crate redis_module;

use redis_module::{
AclPermissions, Context, NextArg, RedisError, RedisResult, RedisString, RedisValue,
};

fn verify_key_access_for_user(ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
iddm marked this conversation as resolved.
Show resolved Hide resolved
let user = args.next_arg()?;
let key = args.next_arg()?;
let res = ctx.acl_check_key_permission(&user, &key, &AclPermissions::all());
if let Err(err) = res {
return Err(RedisError::String(format!("Err {err}")));
}
Ok(RedisValue::SimpleStringStatic("OK"))
}

fn get_current_user(ctx: &Context, _args: Vec<RedisString>) -> RedisResult {
Ok(RedisValue::BulkRedisString(ctx.get_current_user()))
}

//////////////////////////////////////////////////////

redis_module! {
name: "acl",
version: 1,
data_types: [],
commands: [
["verify_key_access_for_user", verify_key_access_for_user, "", 0, 0, 0],
["get_current_user", get_current_user, "", 0, 0, 0],
],
}
76 changes: 76 additions & 0 deletions src/context/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use bitflags::bitflags;
use std::borrow::Borrow;
use std::ffi::CString;
use std::os::raw::{c_char, c_int, c_long, c_longlong};
use std::ptr;
Expand Down Expand Up @@ -421,6 +422,81 @@ impl Context {
raw::RedisModule_GetContextFlags.unwrap()(self.ctx)
})
}

/// Return the current user name attached to the context
pub fn get_current_user(&self) -> RedisString {
let user = unsafe { raw::RedisModule_GetCurrentUserName.unwrap()(self.ctx) };
RedisString::from_redis_module_string(ptr::null_mut(), user)
}

/// Attach the given user to the current context so each operation performed from
/// now on using this context will be validated againts this new user.
/// Return Status::Ok on success and Status::Err or failure.
pub fn autenticate_user<T: Borrow<[u8]>>(&self, user_name: T) -> raw::Status {
let user_name_blob: &[u8] = user_name.borrow();
if unsafe {
iddm marked this conversation as resolved.
Show resolved Hide resolved
raw::RedisModule_AuthenticateClientWithACLUser.unwrap()(
self.ctx,
user_name_blob.as_ptr() as *const c_char,
user_name_blob.len(),
None,
ptr::null_mut(),
ptr::null_mut(),
)
} == raw::REDISMODULE_OK as i32
{
raw::Status::Ok
} else {
raw::Status::Err
}
}

/// Verify the the given user has the give ACL permission on the given key.
/// Return Ok(()) if the user has the permissions or error (with relevant error message)
/// if the validation failed.
pub fn acl_check_key_permission(
&self,
user_name: &RedisString,
key_name: &RedisString,
permissions: &AclPermissions,
) -> Result<(), RedisError> {
let user = unsafe { raw::RedisModule_GetModuleUserFromUserName.unwrap()(user_name.inner) };
if user.is_null() {
return Err(RedisError::Str("User does not exists or disabled"));
}
if unsafe {
iddm marked this conversation as resolved.
Show resolved Hide resolved
raw::RedisModule_ACLCheckKeyPermissions.unwrap()(
user,
key_name.inner,
permissions.bits(),
)
} == raw::REDISMODULE_OK as i32
{
unsafe { raw::RedisModule_FreeModuleUser.unwrap()(user) };
Ok(())
} else {
unsafe { raw::RedisModule_FreeModuleUser.unwrap()(user) };
Err(RedisError::Str("User does not have permissions on key"))
}
}
}

bitflags! {
/// An object represent ACL permissions.
/// Used to check ACL permission using `acl_check_key_permission`.
pub struct AclPermissions : c_int {
/// User can look at the content of the value, either return it or copy it.
const ACCESS = raw::REDISMODULE_CMD_KEY_ACCESS as c_int;

/// User can insert more data to the key, without deleting or modify existing data.
const INSERT = raw::REDISMODULE_CMD_KEY_INSERT as c_int;

/// User can delete content from the key.
const DELETE = raw::REDISMODULE_CMD_KEY_DELETE as c_int;

/// User can update existing data inside the key.
const UPDATE = raw::REDISMODULE_CMD_KEY_UPDATE as c_int;
}
}

pub struct InfoContext {
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub use crate::context::thread_safe::{DetachedFromClient, ThreadSafeContext};
pub use crate::raw::NotifyEvent;

pub use crate::context::keys_cursor::KeysCursor;
pub use crate::context::AclPermissions;
pub use crate::context::Context;
pub use crate::context::ContextFlags;
pub use crate::raw::*;
Expand Down
57 changes: 57 additions & 0 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::utils::{get_redis_connection, start_redis_server_with_module};
use anyhow::Context;
use anyhow::Result;
use redis::RedisError;
use redis::RedisResult;

mod utils;

Expand Down Expand Up @@ -266,3 +267,59 @@ fn test_ctx_flags() -> Result<()> {

Ok(())
}

#[test]
fn test_get_current_user() -> Result<()> {
let port: u16 = 6490;
let _guards = vec![start_redis_server_with_module("acl", port)
.with_context(|| "failed to start redis server")?];
let mut con =
get_redis_connection(port).with_context(|| "failed to connect to redis server")?;

let res: String = redis::cmd("get_current_user").query(&mut con)?;

assert_eq!(&res, "default");

Ok(())
}

#[test]
fn test_verify_acl_on_user() -> Result<()> {
let port: u16 = 6491;
let _guards = vec![start_redis_server_with_module("acl", port)
.with_context(|| "failed to start redis server")?];
let mut con =
get_redis_connection(port).with_context(|| "failed to connect to redis server")?;

let res: String = redis::cmd("verify_key_access_for_user")
.arg(&["default", "x"])
.query(&mut con)?;

assert_eq!(&res, "OK");

let res: String = redis::cmd("ACL")
.arg(&["SETUSER", "alice", "on", ">pass", "~cached:*", "+get"])
.query(&mut con)?;

assert_eq!(&res, "OK");

let res: String = redis::cmd("verify_key_access_for_user")
.arg(&["alice", "cached:1"])
.query(&mut con)?;

assert_eq!(&res, "OK");

let res: RedisResult<String> = redis::cmd("verify_key_access_for_user")
.arg(&["alice", "not_allow"])
.query(&mut con);

assert!(res.is_err());
if let Err(res) = res {
assert_eq!(
res.to_string(),
"Err: User does not have permissions on key"
);
}

Ok(())
}