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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ nor authentication, so it is the cheapest way to check a mapping.
An import converges: re-running it skips what the realm already has rather than
failing or duplicating.

### Keycloak

Reads a realm through the Admin REST API: realm settings, clients, realm and
client roles, and users.

Each user's role mappings are read from `/users/{id}/role-mappings` and assigned
in FerrisKey, realm roles and client roles alike. Only the roles a user holds
directly are read: composite roles are not expanded and roles inherited from a
group are not copied onto the user.

A mapping to a role the import does not create is skipped and reported on stderr
with the user and the role. That covers a realm role whose name contains `:` and
a client whose id contains `:` (for example a URN): a blueprint reserves `:` as
the separator in `client_id:role_name`, so those mappings cannot be written down.

A re-run adds the mappings a user is missing and removes none, so a role granted
in FerrisKey since the first import stays. `--dry-run` lists each mapping as
`user -> role` (`-o json` / `-o yaml` print them in each user's `roles`).

Passwords are not exported by Keycloak, so users arrive without credentials.

### Supabase

Reads a project through its Auth (GoTrue) Admin API, authenticating with the
Expand Down
227 changes: 217 additions & 10 deletions libs/ferriskey-cli-core/src/import/sources/keycloak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
//! `--source-token`. Entities are then read from `/admin/realms/{realm}/...`.
//!
//! User password hashes are never exported by Keycloak, so users are recreated
//! without credentials. User role mappings are not imported in this iteration
//! (roles themselves are created).
//! without credentials. Each user's direct realm and client role mappings are
//! read from `/users/{id}/role-mappings`; composite and group-inherited roles
//! are not expanded.

use std::collections::{HashMap, HashSet};

use reqwest::blocking::Client;
use serde::Deserialize;
Expand Down Expand Up @@ -109,26 +112,43 @@ impl RealmSource for KeycloakSource {
let kc_clients: Vec<KcClient> = self.get(&token, "/clients")?;
let kc_roles: Vec<KcRole> = self.get(&token, "/roles")?;

let mut catalogue = RoleCatalogue {
realm: kc_roles.iter().map(|role| role.name.clone()).collect(),
clients: HashSet::new(),
};

let clients = kc_clients
.into_iter()
.map(|client| {
let client_roles = self
.get::<Vec<KcRole>>(&token, &format!("/clients/{}/roles", client.id))
.unwrap_or_default()
let client_roles: Vec<RoleBlueprint> = self
.get::<Vec<KcRole>>(&token, &format!("/clients/{}/roles", client.id))?
.into_iter()
.map(map_role)
.collect();
map_client(client, client_roles)
for role in &client_roles {
catalogue
.clients
.insert((client.client_id.clone(), role.name.clone()));
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Ok(map_client(client, client_roles))
})
.collect();
.collect::<Result<Vec<_>, ImportError>>()?;

let mut users = Vec::new();
let mut first = 0;
loop {
let page: Vec<KcUser> =
self.get(&token, &format!("/users?first={first}&max={USER_PAGE_SIZE}"))?;
let count = page.len();
users.extend(page.into_iter().map(map_user));
for user in page {
let mappings: KcRoleMappings =
self.get(&token, &format!("/users/{}/role-mappings", user.id))?;
let (roles, skipped) = map_role_mappings(&mappings, &catalogue);
for reason in skipped {
eprintln!("note: user '{}': {reason}", user.username);
}
users.push(map_user(user, roles));
}
if count < USER_PAGE_SIZE {
break;
}
Expand Down Expand Up @@ -211,15 +231,80 @@ fn map_client(client: KcClient, roles: Vec<RoleBlueprint>) -> ClientBlueprint {
}
}

fn map_user(user: KcUser) -> crate::import::UserBlueprint {
/// What the import creates, so a mapping can be checked against it: a user
/// can only be given a role the target realm will actually hold.
struct RoleCatalogue {
realm: HashSet<String>,
clients: HashSet<(String, String)>,
}

/// Turns a user's direct Keycloak mappings into blueprint role references
/// (`name` for a realm role, `client_id:name` for a client role).
///
/// A blueprint separates the client from the role at the first `:`, so a realm
/// role or a client id containing one cannot be written down; those, and any
/// role the import does not create, come back as skip reasons instead.
fn map_role_mappings(
mappings: &KcRoleMappings,
catalogue: &RoleCatalogue,
) -> (Vec<String>, Vec<String>) {
let mut roles = Vec::new();
let mut skipped = Vec::new();

for role in mappings.realm_mappings.iter().flatten() {
if role.name.contains(':') {
skipped.push(format!(
"realm role '{}' skipped: a ':' in the name is reserved for client roles",
role.name
));
} else if !catalogue.realm.contains(&role.name) {
skipped.push(format!(
"realm role '{}' skipped: it is not part of the import",
role.name
));
} else {
roles.push(role.name.clone());
}
}

let mut clients: Vec<(&String, &KcClientMapping)> =
mappings.client_mappings.iter().flatten().collect();
clients.sort_by_key(|(key, _)| key.as_str());
for (key, entry) in clients {
let client_id = entry.client.as_deref().unwrap_or(key);
for role in &entry.mappings {
if client_id.contains(':') {
skipped.push(format!(
"client role '{client_id}:{}' skipped: a ':' in the client id is reserved \
as the client/role separator",
role.name
));
} else if !catalogue
.clients
.contains(&(client_id.to_owned(), role.name.clone()))
{
skipped.push(format!(
"client role '{client_id}:{}' skipped: it is not part of the import",
role.name
));
} else {
roles.push(format!("{client_id}:{}", role.name));
}
}
}

(roles, skipped)
}

fn map_user(user: KcUser, roles: Vec<String>) -> crate::import::UserBlueprint {
crate::import::UserBlueprint {
username: user.username,
id: None,
email: user.email,
firstname: user.first_name,
lastname: user.last_name,
email_verified: user.email_verified,
roles: Vec::new(),
roles,
credential: None,
}
}
Expand Down Expand Up @@ -268,8 +353,24 @@ struct KcRole {
description: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct KcRoleMappings {
#[serde(rename = "realmMappings")]
realm_mappings: Option<Vec<KcRole>>,
#[serde(rename = "clientMappings")]
client_mappings: Option<HashMap<String, KcClientMapping>>,
}

#[derive(Debug, Deserialize)]
struct KcClientMapping {
client: Option<String>,
#[serde(default)]
mappings: Vec<KcRole>,
}

#[derive(Debug, Deserialize)]
struct KcUser {
id: String,
username: String,
email: Option<String>,
#[serde(rename = "firstName")]
Expand Down Expand Up @@ -321,4 +422,110 @@ mod tests {
assert_eq!(settings.email_verification_enabled, Some(true));
assert!(settings.remember_me_enabled.is_none());
}

fn catalogue() -> RoleCatalogue {
RoleCatalogue {
realm: ["admin", "default-roles-acme", "ops:oncall"]
.into_iter()
.map(str::to_owned)
.collect(),
clients: [("web", "viewer"), ("urn:app", "editor")]
.into_iter()
.map(|(client, role)| (client.to_owned(), role.to_owned()))
.collect(),
}
}

fn mappings(json: &str) -> KcRoleMappings {
serde_json::from_str(json).expect("role mappings")
}

#[test]
fn reads_a_keycloak_role_mappings_payload() {
let parsed = mappings(
r#"{
"realmMappings": [{"id": "r1", "name": "admin", "composite": false}],
"clientMappings": {
"web": {"id": "c1", "client": "web", "mappings": [{"id": "r2", "name": "viewer"}]}
}
}"#,
);
let (roles, skipped) = map_role_mappings(&parsed, &catalogue());
assert_eq!(roles, vec!["admin".to_owned(), "web:viewer".to_owned()]);
assert!(skipped.is_empty());
}

#[test]
fn a_user_without_mappings_gets_no_roles() {
let (roles, skipped) = map_role_mappings(&mappings("{}"), &catalogue());
assert!(roles.is_empty());
assert!(skipped.is_empty());
}

#[test]
fn skips_and_reports_a_role_the_import_does_not_create() {
let parsed = mappings(
r#"{
"realmMappings": [{"name": "admin"}, {"name": "ghost"}],
"clientMappings": {
"web": {"client": "web", "mappings": [{"name": "viewer"}, {"name": "ghost"}]}
}
}"#,
);
let (roles, skipped) = map_role_mappings(&parsed, &catalogue());
assert_eq!(roles, vec!["admin".to_owned(), "web:viewer".to_owned()]);
assert_eq!(skipped.len(), 2);
assert!(skipped[0].contains("realm role 'ghost'"));
assert!(skipped[1].contains("client role 'web:ghost'"));
}

#[test]
fn skips_names_a_blueprint_cannot_express() {
let parsed = mappings(
r#"{
"realmMappings": [{"name": "ops:oncall"}],
"clientMappings": {
"urn:app": {"client": "urn:app", "mappings": [{"name": "editor"}]}
}
}"#,
);
let (roles, skipped) = map_role_mappings(&parsed, &catalogue());
assert!(roles.is_empty());
assert_eq!(skipped.len(), 2);
assert!(skipped[0].contains("realm role 'ops:oncall'"));
assert!(skipped[1].contains("urn:app"));
}

#[test]
fn client_mappings_come_out_in_a_stable_order() {
let mut catalogue = catalogue();
catalogue
.clients
.insert(("api".to_owned(), "reader".to_owned()));
let parsed = mappings(
r#"{"clientMappings": {
"web": {"client": "web", "mappings": [{"name": "viewer"}]},
"api": {"client": "api", "mappings": [{"name": "reader"}]}
}}"#,
);
let (roles, _) = map_role_mappings(&parsed, &catalogue);
assert_eq!(
roles,
vec!["api:reader".to_owned(), "web:viewer".to_owned()]
);
}

#[test]
fn map_user_carries_the_resolved_roles() {
let user = KcUser {
id: "u1".to_owned(),
username: "alice".to_owned(),
email: None,
first_name: None,
last_name: None,
email_verified: None,
};
let bp = map_user(user, vec!["admin".to_owned()]);
assert_eq!(bp.roles, vec!["admin".to_owned()]);
}
}
28 changes: 28 additions & 0 deletions libs/ferriskey-cli-core/src/realm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,11 @@ fn render_blueprints(output_format: &str, blueprints: &[RealmBlueprint]) -> Resu
.filter(|user| user.credential.is_some())
.count()
);
let mappings = role_mappings(blueprint);
println!("role mappings: {}", mappings.len());
for (username, role) in mappings {
println!(" {username} -> {role}");
}
}
Ok(())
}
Expand All @@ -405,6 +410,18 @@ fn render_blueprints(output_format: &str, blueprints: &[RealmBlueprint]) -> Resu
}
}

fn role_mappings(blueprint: &RealmBlueprint) -> Vec<(&str, &str)> {
blueprint
.users
.iter()
.flat_map(|user| {
user.roles
.iter()
.map(|role| (user.username.as_str(), role.as_str()))
})
.collect()
}

fn redact_secrets(blueprints: &[RealmBlueprint]) -> Vec<RealmBlueprint> {
blueprints
.iter()
Expand Down Expand Up @@ -702,6 +719,17 @@ mod tests {
assert!(rendered.contains("hash_iterations"));
}

#[test]
fn lists_every_role_mapping_of_every_user() {
let mut blueprints = blueprint_with_password();
blueprints[0].users[0].roles = vec!["admin".to_owned(), "web:viewer".to_owned()];
assert_eq!(
role_mappings(&blueprints[0]),
vec![("alice", "admin"), ("alice", "web:viewer")]
);
assert!(render_blueprints("table", &blueprints).is_ok());
}

#[test]
fn redacting_leaves_the_rest_of_the_blueprint_alone() {
let redacted = redact_secrets(&blueprint_with_password());
Expand Down
Loading