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
10 changes: 10 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,16 @@ pub struct Options {
)]
pub scope: String,

// replace OIDC users' roles with the roles their provider groups grant, on every login
#[arg(
long = "oidc-sync-roles",
env = "P_OIDC_SYNC_ROLES",
default_value = "false",
required = false,
help = "Make the OIDC provider's groups authoritative for OIDC users' roles: on each login the user's roles are replaced by the roles their groups name (or the default role), so removing a user from a group revokes the role. When off (default), group roles are added and roles assigned in Parseable are kept."
)]
pub oidc_sync_roles: bool,

// additional query params for oidc auth url
#[arg(
long,
Expand Down
228 changes: 202 additions & 26 deletions src/handlers/http/oidc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*
*/

use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};

use actix_web::http::StatusCode;
Expand Down Expand Up @@ -51,9 +51,10 @@ use crate::{
rbac::{
self, EXPIRY_DURATION, Users,
map::{DEFAULT_ROLE, SessionKey},
role::model::Role,
user::{self, GroupUser, User, UserType},
},
storage::{ObjectStorageError, StorageMetadata},
storage::ObjectStorageError,
utils::{
actix::extract_session_key_from_req, get_tenant_id_from_key, get_tenant_id_from_request,
},
Expand Down Expand Up @@ -236,12 +237,20 @@ pub async fn reply_login(
let (username, user_id, user_info) = extract_identity(&session)?;
let metadata = get_metadata(&tenant_id).await?;
let existing_user = find_existing_user(&user_info, tenant_id.clone());
let default_role = DEFAULT_ROLE
.read()
.get(tenant_id.as_deref().unwrap_or(DEFAULT_TENANT))
.and_then(|r| r.clone())
.map(|r| HashSet::from([r]))
.unwrap_or_default();
let final_roles = resolve_roles(
&session.claims.groups,
&metadata,
&metadata.roles,
&metadata.users,
&user_info,
&tenant_id,
existing_user.as_ref(),
default_role,
PARSEABLE.options.oidc_sync_roles,
);

let expires_in = bearer_expiry(&session.bearer);
Expand Down Expand Up @@ -317,45 +326,43 @@ fn extract_identity(session: &OAuthSession) -> Result<(String, String, user::Use
}

/// Determine the final set of roles for the user.
///
/// With `sync_with_provider` (`P_OIDC_SYNC_ROLES`) the provider's groups are the only source of roles besides the
/// default role, so the native-account fallback below is skipped: otherwise removing a user's last group would
/// hand the removed role straight back through a native account with the same email.
///
/// It reads no global state (the caller passes the defined roles, the users and the tenant's default role), so it
/// can be unit-tested.
fn resolve_roles(
groups: &HashSet<String>,
metadata: &StorageMetadata,
defined_roles: &HashMap<String, Role>,
users: &[User],
user_info: &user::UserInfo,
tenant_id: &Option<String>,
existing_user: Option<&User>,
default_role: HashSet<String>,
sync_with_provider: bool,
) -> HashSet<String> {
let valid_oidc_roles: HashSet<String> = metadata
.roles
let valid_oidc_roles: HashSet<String> = defined_roles
.keys()
.filter(|role_name| groups.contains(*role_name))
.cloned()
.collect();

let default_role = DEFAULT_ROLE
.read()
.get(tenant_id.as_deref().unwrap_or(DEFAULT_TENANT))
.and_then(|r| r.clone())
.map(|r| HashSet::from([r]))
.unwrap_or_default();

let mut roles = match existing_user {
Some(user) => {
let mut roles = user.roles.clone();
roles.extend(valid_oidc_roles);
roles
}
None if !valid_oidc_roles.is_empty() => valid_oidc_roles,
None => default_role.clone(),
};
let mut roles = merge_oidc_roles(
existing_user.map(|user| &user.roles),
valid_oidc_roles,
sync_with_provider,
);
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

if roles.is_empty() {
roles.clone_from(&default_role);
roles = default_role;
}

// Inherit roles from a native user with the same email (e.g. tenant owner via OAuth)
if roles.is_empty()
&& !sync_with_provider
&& let Some(email) = &user_info.email
&& let Some(native) = metadata.users.iter().find(|u| {
&& let Some(native) = users.iter().find(|u| {
matches!(u.ty, UserType::Native(_))
&& u.userid() == email.as_str()
&& !u.roles.is_empty()
Expand All @@ -367,6 +374,27 @@ fn resolve_roles(
roles
}

/// Combines the roles a returning user already has with the roles their provider groups grant.
///
/// By default roles accumulate: group roles are added and roles assigned inside Parseable are kept, which also
/// means removing a user from a group in the provider does not take the role away. With `P_OIDC_SYNC_ROLES` the
/// provider is authoritative and the user's roles become exactly the group roles at every login. An empty result
/// falls back to the default role in the caller.
fn merge_oidc_roles(
existing: Option<&HashSet<String>>,
group_roles: HashSet<String>,
sync_with_provider: bool,
) -> HashSet<String> {
match existing {
Some(current) if !sync_with_provider => {
let mut roles = current.clone();
roles.extend(group_roles);
roles
}
_ => group_roles,
}
}

/// Compute session expiry from the bearer token.
fn bearer_expiry(bearer: &Bearer) -> TimeDelta {
match bearer.expires_in.as_ref() {
Expand Down Expand Up @@ -665,3 +693,151 @@ fn is_valid_redirect_url(base_url: &str, redirect_url: &str) -> bool {
.map(|url| url.origin() == redirect_origin)
.unwrap_or(false)
}

#[cfg(test)]
mod merge_oidc_roles_tests {
use std::collections::{HashMap, HashSet};

use super::{merge_oidc_roles, resolve_roles};
use crate::rbac::{
role::model::{DefaultPrivilege, Role},
user::{self, User},
};

/// Roles `group-role` and `native-role`, and a native user `alice@example.com` holding `native-role`.
fn roles_and_native_alice() -> (HashMap<String, Role>, Vec<User>) {
let roles = ["group-role", "native-role"]
.into_iter()
.map(|role| {
(
role.to_string(),
Role::create_user_role(vec![DefaultPrivilege::Reader { resource: None }]),
)
})
.collect();
let (mut native, _password) = User::new_basic("alice@example.com".to_string(), None, false);
native.roles = set(&["native-role"]);
(roles, vec![native])
}

fn alice() -> user::UserInfo {
user::UserInfo {
email: Some("alice@example.com".to_string()),
..Default::default()
}
}

#[test]
fn with_sync_removing_the_last_group_does_not_restore_roles_from_a_native_account() {
let (defined_roles, users) = roles_and_native_alice();
let (mut returning, _password) = User::new_basic("alice-oauth".to_string(), None, false);
returning.roles = set(&["group-role"]);

let roles = resolve_roles(
&HashSet::new(),
&defined_roles,
&users,
&alice(),
Some(&returning),
HashSet::new(),
true,
);

assert!(roles.is_empty(), "got {roles:?}");
}

#[test]
fn without_sync_a_user_with_no_roles_still_inherits_from_the_native_account() {
let (defined_roles, users) = roles_and_native_alice();

let roles = resolve_roles(
&HashSet::new(),
&defined_roles,
&users,
&alice(),
None,
HashSet::new(),
false,
);

assert_eq!(roles, set(&["native-role"]));
}

#[test]
fn with_sync_group_roles_replace_existing_roles_end_to_end() {
let (defined_roles, users) = roles_and_native_alice();
let (mut returning, _password) = User::new_basic("alice-oauth".to_string(), None, false);
returning.roles = set(&["native-role", "group-role"]);

let roles = resolve_roles(
&set(&["group-role", "unknown-group"]),
&defined_roles,
&users,
&alice(),
Some(&returning),
HashSet::new(),
true,
);

assert_eq!(roles, set(&["group-role"]));
}

#[test]
fn with_sync_and_no_groups_the_default_role_still_applies() {
let (defined_roles, users) = roles_and_native_alice();
let (mut returning, _password) = User::new_basic("alice-oauth".to_string(), None, false);
returning.roles = set(&["group-role"]);

let roles = resolve_roles(
&HashSet::new(),
&defined_roles,
&users,
&alice(),
Some(&returning),
set(&["default-role"]),
true,
);

assert_eq!(roles, set(&["default-role"]));
}

fn set(roles: &[&str]) -> HashSet<String> {
roles.iter().map(|r| r.to_string()).collect()
}

#[test]
fn new_user_gets_exactly_the_group_roles() {
assert_eq!(
merge_oidc_roles(None, set(&["reader"]), false),
set(&["reader"])
);
assert_eq!(
merge_oidc_roles(None, set(&["reader"]), true),
set(&["reader"])
);
}

#[test]
fn by_default_existing_roles_are_kept_and_group_roles_added() {
let current = set(&["admin-assigned", "old-group"]);
assert_eq!(
merge_oidc_roles(Some(&current), set(&["new-group"]), false),
set(&["admin-assigned", "old-group", "new-group"])
);
}

#[test]
fn with_sync_a_role_from_a_removed_group_is_revoked() {
let current = set(&["old-group", "kept-group"]);
assert_eq!(
merge_oidc_roles(Some(&current), set(&["kept-group"]), true),
set(&["kept-group"])
);
}

#[test]
fn with_sync_no_matching_groups_leaves_no_roles_for_the_default_fallback() {
let current = set(&["old-group"]);
assert!(merge_oidc_roles(Some(&current), HashSet::new(), true).is_empty());
}
}
Loading