use std::collections::{HashMap, HashSet};
use uuid::Uuid;
use super::spec::{ManagementManifest, RoleBinding};
use crate::AxiamError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Change {
Create,
Update,
NoChange,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Target {
Resource,
Scope,
Permission,
Role,
RoleGrant,
Group,
GroupRole,
User,
UserRole,
GroupMember,
ServiceAccount,
ServiceAccountRole,
NetworkPolicy,
NetworkSegment,
NetworkProfile,
}
impl Target {
#[must_use]
pub fn is_network(self) -> bool {
matches!(
self,
Target::NetworkPolicy | Target::NetworkSegment | Target::NetworkProfile
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannedAction {
pub change: Change,
pub target: Target,
pub key: String,
pub summary: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ManagementPlan {
pub actions: Vec<PlannedAction>,
}
impl ManagementPlan {
pub fn changes(&self) -> impl Iterator<Item = &PlannedAction> {
self.actions.iter().filter(|a| a.change != Change::NoChange)
}
pub fn is_converged(&self) -> bool {
self.changes().next().is_none()
}
pub fn change_count(&self) -> usize {
self.changes().count()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outcome {
Created,
CreatedServiceAccount(CreatedServiceAccount),
Updated,
Unchanged,
Failed(String),
Conflict {
message: String,
reason_code: Option<String>,
},
BindingUpdateFailed {
error: String,
restore: Result<(), String>,
},
NotAttempted,
}
impl Outcome {
#[must_use]
pub fn reason_code(&self) -> Option<&str> {
match self {
Outcome::Conflict { reason_code, .. } => reason_code.as_deref(),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct CreatedServiceAccount(pub Box<crate::management::models::ServiceAccountCreatedResponse>);
impl CreatedServiceAccount {
#[must_use]
pub fn account(&self) -> &crate::management::models::ServiceAccountCreatedResponse {
&self.0
}
}
impl PartialEq for CreatedServiceAccount {
fn eq(&self, other: &Self) -> bool {
self.0.id == other.0.id && self.0.client_id == other.0.client_id
}
}
impl Eq for CreatedServiceAccount {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplyReport {
pub steps: Vec<(PlannedAction, Outcome)>,
}
impl ApplyReport {
pub fn failure(&self) -> Option<(&PlannedAction, &str)> {
self.steps
.iter()
.find_map(|(action, outcome)| match outcome {
Outcome::Failed(message) => Some((action, message.as_str())),
Outcome::Conflict { message, .. } => Some((action, message.as_str())),
Outcome::BindingUpdateFailed { error, .. } => Some((action, error.as_str())),
_ => None,
})
}
pub fn reason_code(&self) -> Option<&str> {
self.steps
.iter()
.find_map(|(_, outcome)| outcome.reason_code())
}
pub fn created_service_accounts(
&self,
) -> impl Iterator<
Item = (
&PlannedAction,
&crate::management::models::ServiceAccountCreatedResponse,
),
> {
self.steps
.iter()
.filter_map(|(action, outcome)| match outcome {
Outcome::CreatedServiceAccount(created) => Some((action, created.account())),
_ => None,
})
}
pub fn is_complete(&self) -> bool {
self.failure().is_none()
}
pub fn changed(&self) -> usize {
self.steps
.iter()
.filter(|(_, o)| {
matches!(
o,
Outcome::Created | Outcome::CreatedServiceAccount(_) | Outcome::Updated
)
})
.count()
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Resolved {
pub resources: HashMap<String, Uuid>,
pub scopes: HashMap<String, Uuid>,
pub permissions: HashMap<String, Uuid>,
pub roles: HashMap<String, Uuid>,
pub groups: HashMap<String, Uuid>,
pub users: HashMap<String, Uuid>,
pub service_accounts: HashMap<String, Uuid>,
pub network_segments: HashMap<String, Uuid>,
pub network_segment_versions: HashMap<String, i64>,
}
pub(crate) fn validate(manifest: &ManagementManifest) -> Result<(), AxiamError> {
let mut problems: Vec<String> = Vec::new();
let resource_keys: HashSet<&str> = manifest.resources.iter().map(|r| r.key.as_str()).collect();
let scope_keys: HashSet<&str> = manifest
.resources
.iter()
.flat_map(|r| r.scopes.iter().map(|s| s.key.as_str()))
.collect();
let permission_keys: HashSet<&str> = manifest
.permissions
.iter()
.map(|p| p.key.as_str())
.collect();
let role_keys: HashSet<&str> = manifest.roles.iter().map(|r| r.key.as_str()).collect();
let group_keys: HashSet<&str> = manifest.groups.iter().map(|g| g.key.as_str()).collect();
duplicates(
"resource",
manifest.resources.iter().map(|r| &r.key),
&mut problems,
);
duplicates(
"scope",
manifest
.resources
.iter()
.flat_map(|r| r.scopes.iter().map(|s| &s.key)),
&mut problems,
);
duplicates(
"permission",
manifest.permissions.iter().map(|p| &p.key),
&mut problems,
);
duplicates("role", manifest.roles.iter().map(|r| &r.key), &mut problems);
duplicates(
"group",
manifest.groups.iter().map(|g| &g.key),
&mut problems,
);
duplicates("user", manifest.users.iter().map(|u| &u.key), &mut problems);
for resource in &manifest.resources {
if let Some(parent) = &resource.parent
&& !resource_keys.contains(parent.as_str())
{
problems.push(format!(
"resource {:?} names parent {parent:?}, which no resource declares",
resource.key
));
}
}
for role in &manifest.roles {
for grant in &role.grants {
if !permission_keys.contains(grant.permission.as_str()) {
problems.push(format!(
"role {:?} grants permission {:?}, which no permission declares",
role.key, grant.permission
));
}
for scope in &grant.scopes {
if !scope_keys.contains(scope.as_str()) {
problems.push(format!(
"role {:?} scopes a grant to {scope:?}, which no scope declares",
role.key
));
}
}
}
}
duplicates(
"service account",
manifest.service_accounts.iter().map(|a| &a.key),
&mut problems,
);
duplicates(
"service account name",
manifest.service_accounts.iter().map(|a| &a.name),
&mut problems,
);
let global_roles: HashSet<&str> = manifest
.roles
.iter()
.filter(|r| r.is_global)
.map(|r| r.key.as_str())
.collect();
let subjects = manifest
.groups
.iter()
.map(|g| ("group", &g.key, &g.roles))
.chain(manifest.users.iter().map(|u| ("user", &u.key, &u.roles)))
.chain(
manifest
.service_accounts
.iter()
.map(|a| ("service account", &a.key, &a.roles)),
);
for (kind, subject, bindings) in subjects {
check_bindings(
kind,
subject,
bindings,
&role_keys,
&resource_keys,
&global_roles,
&mut problems,
);
}
for user in &manifest.users {
for group in &user.groups {
if !group_keys.contains(group.as_str()) {
problems.push(format!(
"user {:?} is in group {group:?}, which no group declares",
user.key
));
}
}
}
if let Err(cycle) = topological_order(manifest) {
problems.push(cycle);
}
super::network::validate(&manifest.network, &mut problems);
if problems.is_empty() {
Ok(())
} else {
Err(AxiamError::network(format!(
"manifest is not reconcilable ({} problem(s)): {}",
problems.len(),
problems.join("; ")
)))
}
}
fn check_bindings(
kind: &str,
subject: &str,
bindings: &[RoleBinding],
role_keys: &HashSet<&str>,
resource_keys: &HashSet<&str>,
global_roles: &HashSet<&str>,
problems: &mut Vec<String>,
) {
let mut seen: HashSet<&str> = HashSet::new();
for binding in bindings {
let role = binding.role();
if !role_keys.contains(role) {
problems.push(format!(
"{kind} {subject:?} is assigned role {role:?}, which no role declares"
));
}
if let Some(resource) = binding.resource()
&& !resource_keys.contains(resource)
{
problems.push(format!(
"{kind} {subject:?} is assigned role {role:?} at resource {resource:?}, which no \
resource declares"
));
}
if !seen.insert(role) {
problems.push(format!(
"{kind} {subject:?} binds role {role:?} more than once; a subject holds a role at \
most once, whatever the resource (the server keys assignments on subject and \
role, and answers 409 to a second)"
));
}
if !binding.inherit() && global_roles.contains(role) {
problems.push(format!(
"{kind} {subject:?} binds global role {role:?} with inherit: false; a global role \
applies everywhere and ignores the resource, so the server refuses the flag"
));
}
}
}
fn duplicates<'a>(kind: &str, keys: impl Iterator<Item = &'a String>, problems: &mut Vec<String>) {
let mut seen: HashSet<&str> = HashSet::new();
for key in keys {
if !seen.insert(key.as_str()) {
problems.push(format!("{kind} key {key:?} is declared more than once"));
}
}
}
pub(crate) fn topological_order(manifest: &ManagementManifest) -> Result<Vec<String>, String> {
let mut parents: HashMap<&str, Option<&str>> = HashMap::new();
for resource in &manifest.resources {
parents.insert(resource.key.as_str(), resource.parent.as_deref());
}
let mut order: Vec<String> = Vec::new();
let mut placed: HashSet<&str> = HashSet::new();
for resource in &manifest.resources {
let mut chain: Vec<&str> = Vec::new();
let mut cursor = Some(resource.key.as_str());
let mut guard: HashSet<&str> = HashSet::new();
while let Some(key) = cursor {
if placed.contains(key) {
break;
}
if !guard.insert(key) {
return Err(format!(
"resource parent graph has a cycle through {key:?}; there is no order in \
which these can be created"
));
}
chain.push(key);
cursor = parents.get(key).copied().flatten();
}
for key in chain.into_iter().rev() {
if placed.insert(key) {
order.push(key.to_string());
}
}
}
Ok(order)
}