feat: Start implementing roles (and domainless service users)

This commit is contained in:
selfhoster selfhoster 2026-09-04 18:35:46 +02:00
commit 10548295cd
10 changed files with 156 additions and 21 deletions

View file

@ -5,12 +5,18 @@ use crate::db::UserRef;
pub type BoxedError = Box<dyn std::error::Error + Send + Sync + 'static>;
#[derive(Debug)]
pub struct UserAlreadyExists(pub UserRef);
pub enum UserCreationError {
UserAlreadyExists(UserRef),
Permissions,
}
impl fmt::Display for UserAlreadyExists {
impl fmt::Display for UserCreationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "User already exists: {}", self.0)
match self {
Self::UserAlreadyExists(user) => write!(f, "User already exists: {user}"),
Self::Permissions => write!(f, "You do not have permissions to create this user"),
}
}
}
impl std::error::Error for UserAlreadyExists {}
impl std::error::Error for UserCreationError {}

View file

@ -1,4 +1,4 @@
use crate::db::error::{BoxedError, UserAlreadyExists};
use crate::db::error::{BoxedError, UserCreationError};
use crate::db::{Database, User, UserRef};
impl<D: DatabaseInterface> DatabaseInterface for Database<D> {
@ -9,9 +9,21 @@ impl<D: DatabaseInterface> DatabaseInterface for Database<D> {
async fn create_user(
&mut self,
user: User,
) -> Result<Result<(), UserAlreadyExists>, BoxedError> {
) -> Result<Result<(), UserCreationError>, BoxedError> {
self.inner.write().await.create_user(user).await
}
async fn try_create_user(
&mut self,
new_user: User,
current_user: &User,
) -> Result<Result<(), UserCreationError>, BoxedError> {
self.inner
.write()
.await
.try_create_user(new_user, current_user)
.await
}
}
pub trait DatabaseInterface: Clone + Send + Sync + 'static {
@ -19,5 +31,11 @@ pub trait DatabaseInterface: Clone + Send + Sync + 'static {
async fn create_user(
&mut self,
user: User,
) -> Result<Result<(), UserAlreadyExists>, BoxedError>;
) -> Result<Result<(), UserCreationError>, BoxedError>;
#[expect(unused)]
async fn try_create_user(
&mut self,
new_user: User,
current_user: &User,
) -> Result<Result<(), UserCreationError>, BoxedError>;
}

View file

@ -1,7 +1,7 @@
use std::future::{Future, ready};
use crate::db::error::{BoxedError, UserAlreadyExists};
use crate::db::{Database, DatabaseInterface, Group, User, UserRef};
use crate::db::error::{BoxedError, UserCreationError};
use crate::db::{Database, DatabaseInterface, Group, Operation, User, UserRef};
#[derive(Clone, Debug, Default)]
pub struct MemoryDatabase {
@ -33,13 +33,35 @@ impl DatabaseInterface for MemoryDatabase {
async fn create_user(
&mut self,
user: User,
) -> Result<Result<(), UserAlreadyExists>, BoxedError> {
) -> Result<Result<(), UserCreationError>, BoxedError> {
let user_ref = user.user_ref();
if self.get_user(&user_ref).await?.is_some() {
return Ok(Err(UserAlreadyExists(user_ref)));
return Ok(Err(UserCreationError::UserAlreadyExists(user_ref)));
}
self.users.push(user);
Ok(Ok(()))
}
async fn try_create_user(
&mut self,
new_user: User,
current_user: &User,
) -> Result<Result<(), UserCreationError>, BoxedError> {
// First check permissions, then apply the operation
//
// TODO: for now we don't allow creating service users manually
// so we assume there's a domain provided
// TODO: restrict user creation on non-declared domains
let Some(new_user_domain) = &new_user.domain else {
return Ok(Err(UserCreationError::Permissions));
};
let op = Operation::CreateUser(new_user_domain.clone());
if !current_user.can_perform(&op) {
return Ok(Err(UserCreationError::Permissions));
}
self.create_user(new_user).await
}
}

View file

@ -7,5 +7,7 @@ mod interface;
pub use interface::DatabaseInterface;
mod memory;
pub use memory::MemoryDatabase;
mod role;
pub use role::{Operation, Role};
mod user;
pub use user::{User, UserRef};

37
src/db/role.rs Normal file
View file

@ -0,0 +1,37 @@
#[derive(Clone, Debug)]
pub enum Operation {
CreateUser(String),
}
#[derive(Clone, Debug)]
pub enum Role {
/// Can do anything
Admin,
/// Can only read data across all vhosts
#[expect(unused)]
ReadonlyAdmin,
/// Can do anything on a domain, except removing
/// oneself as a domain admin.
///
/// Can not give away roles other than DomainModerator/User
DomainAdmin(String),
/// Can create users and reset passwords on a domain
#[expect(unused)]
DomainModerator(String),
/// Can only edit own profile
User,
}
impl Role {
pub fn can_perform(&self, operation: &Operation) -> bool {
match operation {
Operation::CreateUser(op_domain) => match self {
Self::Admin => true,
Self::DomainAdmin(usr_domain) | Self::DomainModerator(usr_domain) => {
op_domain == usr_domain
}
_ => false,
},
}
}
}

View file

@ -1,23 +1,35 @@
use std::fmt;
use crate::db::{Operation, Role};
#[derive(Clone, Debug)]
pub struct UserRef {
pub username: String,
pub domain: String,
pub domain: Option<String>,
}
impl fmt::Display for UserRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}@{}", self.username, self.domain)
if let Some(domain) = &self.domain {
write!(f, "{}@{}", self.username, domain)
} else {
write!(f, "{}", self.username)
}
}
}
#[derive(Clone, Debug)]
pub struct User {
/// Username, without the domain part. Once set, cannot be edited.
pub username: String,
pub domain: String,
/// Domain of the user. Once set, cannot be edited.
///
/// Service accounts may exist with an empty domain.
pub domain: Option<String>,
pub password: String,
/// Mail for the user. Computed from username/domain, cannot be edited.
pub mail: String,
pub role: Role,
// recovery_mail: String,
}
@ -28,10 +40,19 @@ impl User {
domain: self.domain.clone(),
}
}
#[expect(unused)]
pub fn can_perform(&self, operation: &Operation) -> bool {
self.role.can_perform(operation)
}
}
impl fmt::Display for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}@{}", self.username, self.domain)
if let Some(domain) = &self.domain {
write!(f, "{}@{}", self.username, domain)
} else {
write!(f, "{}", self.username)
}
}
}