Skip to content
Open
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
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ crate-type = ["cdylib"]
name = "preload"
crate-type = ["cdylib"]

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

[[example]]
name = "subcmd"
crate-type = ["cdylib"]
Expand Down
34 changes: 34 additions & 0 deletions examples/post_auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use std::sync::{LazyLock, Mutex};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add integration test for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added examples, not sure how I can do an integ test for this.

use valkey_module::alloc::ValkeyAlloc;

use valkey_module::{valkey_module, Context, ValkeyResult, ValkeyString, ValkeyValue};

static LAST_AUTH_USER: LazyLock<Mutex<(String, String)>> = LazyLock::new(|| Mutex::new((String::new(), String::new())));

// This callback will be scheduled to run after the auth handler completes.
// It receives retained `ValkeyString` previous and new usernames.
fn post_auth_callback(ctx: &Context, prev_user: ValkeyString, new_user: ValkeyString) {
ctx.log_notice(&format!("post_auth: prev_user='{}', new_user='{}'", prev_user, new_user));
let mut lock = LAST_AUTH_USER.lock().unwrap();
*lock = (prev_user.to_string_lossy(), new_user.to_string_lossy());
}

fn whoami(_ctx: &Context, _args: Vec<ValkeyString>) -> ValkeyResult {
let (prev, new) = LAST_AUTH_USER.lock().unwrap().clone();
if new.is_empty() {
Ok(ValkeyValue::Null)
} else {
Ok(ValkeyValue::Array(vec![ValkeyValue::BulkString(prev), ValkeyValue::BulkString(new)]))
}
}

valkey_module! {
name: "post_auth_example",
version: 1,
allocator: (ValkeyAlloc, ValkeyAlloc),
data_types: [],
post_auth: [ post_auth_callback ],
commands: [
["whoami_postauth", whoami, "readonly", 0, 0, 0],
]
}
66 changes: 66 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ macro_rules! valkey_module {
$(auth: [
$($auth_callback:expr),* $(,)*
],)?
$(post_auth: [
$($post_auth_callback:expr),* $(,)*
],)?
$(acl_categories: [
$($acl_category:expr),* $(,)*
])?
Expand Down Expand Up @@ -461,6 +464,10 @@ macro_rules! valkey_module {

raw::register_info_function(ctx, Some(__info_func));

$(
$crate::valkey_module_post_auth!($module_name, ctx, $($post_auth_callback),*);
)?

$(
$crate::valkey_module_auth!($module_name, ctx, $($auth_callback),*);
)?
Expand Down Expand Up @@ -576,3 +583,62 @@ macro_rules! valkey_module_auth {
)*
};
}

/// Registers post-authentication callbacks with the Valkey module
///
/// These callbacks are invoked after the authentication chain finishes. The macro
/// registers lightweight auth callbacks that schedule a post-notification job so
/// the provided Rust callback runs outside the auth context. The user callback
/// signature should be `fn(&Context, ValkeyString, ValkeyString)` (prev_user, new_user).
#[macro_export]
macro_rules! valkey_module_post_auth {
($module_name:expr, $ctx:expr, $($post_auth_callback:expr),* $(,)*) => {
$(
{
paste::paste! {
extern "C" fn [<__do_post_auth_ $module_name _ $post_auth_callback>] (
ctx: *mut $crate::raw::RedisModuleCtx,
username: *mut $crate::raw::RedisModuleString,
_password: *mut $crate::raw::RedisModuleString,
_err: *mut *mut $crate::raw::RedisModuleString,
) -> std::os::raw::c_int {
let context = $crate::Context::new(ctx);
let ctx_ptr = unsafe { std::ptr::NonNull::new_unchecked(ctx) };
let username_rs = $crate::ValkeyString::new(Some(ctx_ptr), username);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does username_rs stand for?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

username_"rust" since Im converting from the unsafe C pointer

let username_owned = username_rs.to_string_lossy();
// Get previous username before auth
let prev_username = match context.get_client_username() {
Ok(u) => u.to_string_lossy(),
Err(_) => "default".to_string(),
};

// schedule a post-notification job so the callback runs outside
// the auth handler (deferred), and can perform safe operations.
let _ = context.add_post_notification_job(move |ctx| {
let prev = $crate::ValkeyString::create_and_retain(&prev_username);
let new_user = $crate::ValkeyString::create_and_retain(&username_owned);
$post_auth_callback(ctx, prev, new_user);
});

// Do not interfere with the authentication chain.
$crate::AUTH_NOT_HANDLED
}

#[cfg(not(any(
feature = "min-redis-compatibility-version-7-2",
feature = "min-valkey-compatibility-version-8-0"
)))]
compile_error!("Post-auth callbacks require Redis 7.2 or Valkey 8.0 and above");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wouldn't this work on Valkey 7.2 as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would, i'll update it


#[cfg(any(
feature = "min-redis-compatibility-version-7-2",
feature = "min-valkey-compatibility-version-8-0"
))]
unsafe {
$crate::raw::RedisModule_RegisterAuthCallback.expect("RedisModule_RegisterAuthCallback should exist on Redis/Valkey 7.0 and above")($ctx, Some([<__do_post_auth_ $module_name _ $post_auth_callback>]))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this be Redis/Valkey 7.2?

}
}
}
)*
};
}