952 lines
30 KiB
Rust
952 lines
30 KiB
Rust
use super::*;
|
|
use crate::model::RecoverAdminPasswordRequest;
|
|
use time::OffsetDateTime;
|
|
const MAX_ADMIN_BOOTSTRAP_ATTEMPTS: i32 = 5;
|
|
fn map_auth_user_row(row: &PgRow) -> Result<AuthUserRecord, RegistryError> {
|
|
let status = row.try_get::<String, _>("status")?;
|
|
Ok(AuthUserRecord {
|
|
user: User {
|
|
id: UserId::new(row.try_get::<String, _>("id")?),
|
|
email: row.try_get("email")?,
|
|
display_name: row.try_get("display_name")?,
|
|
status: deserialize_enum_text(&status, "status")?,
|
|
created_at: row.try_get::<OffsetDateTime, _>("created_at")?,
|
|
},
|
|
password_hash: row
|
|
.try_get::<Option<String>, _>("password_hash")?
|
|
.unwrap_or_default(),
|
|
})
|
|
}
|
|
impl PostgresRegistry {
|
|
pub async fn create_admin_bootstrap_contract(
|
|
&self,
|
|
request: CreateAdminBootstrapContractRequest<'_>,
|
|
) -> Result<AdminBootstrapContractRecord, RegistryError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
sqlx::query(
|
|
"update admin_bootstrap_contracts
|
|
set status = 'expired'
|
|
where status = 'active'
|
|
and expires_at <= now()",
|
|
)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
let row = sqlx::query(
|
|
"insert into admin_bootstrap_contracts (
|
|
id, token_hash, email, display_name, status, expires_at, created_at
|
|
) values (
|
|
$1, $2, $3, $4, 'active', $5::timestamptz, now()
|
|
)
|
|
returning id, email, display_name, status, expires_at, created_at, used_at",
|
|
)
|
|
.bind(request.id)
|
|
.bind(request.token_hash)
|
|
.bind(request.email)
|
|
.bind(request.display_name)
|
|
.bind(*request.expires_at)
|
|
.fetch_one(&mut *tx)
|
|
.await
|
|
.map_err(|error| match error {
|
|
sqlx::Error::Database(db_error)
|
|
if db_error.constraint() == Some("admin_bootstrap_contracts_single_active_idx") =>
|
|
{
|
|
RegistryError::AdminBootstrapUnavailable
|
|
}
|
|
other => RegistryError::Storage(other),
|
|
})?;
|
|
tx.commit().await?;
|
|
Ok(AdminBootstrapContractRecord {
|
|
id: row.try_get("id")?,
|
|
email: row.try_get("email")?,
|
|
display_name: row.try_get("display_name")?,
|
|
status: row.try_get("status")?,
|
|
expires_at: row.try_get("expires_at")?,
|
|
created_at: row.try_get("created_at")?,
|
|
used_at: row.try_get("used_at")?,
|
|
})
|
|
}
|
|
pub async fn consume_admin_bootstrap_contract(
|
|
&self,
|
|
request: ConsumeAdminBootstrapContractRequest<'_>,
|
|
) -> Result<UserId, RegistryError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
let existing_admins = sqlx::query_scalar::<_, i64>(
|
|
"select count(*)::bigint
|
|
from users
|
|
where coalesce(password_hash, '') <> ''",
|
|
)
|
|
.fetch_one(&mut *tx)
|
|
.await?;
|
|
if existing_admins > 0 {
|
|
return Err(RegistryError::AdminBootstrapRejected);
|
|
}
|
|
let contract = sqlx::query(
|
|
"select id, email, display_name
|
|
from admin_bootstrap_contracts
|
|
where token_hash = $1
|
|
and status = 'active'
|
|
and expires_at > $2::timestamptz
|
|
and attempts < $3
|
|
for update",
|
|
)
|
|
.bind(request.token_hash)
|
|
.bind(*request.now)
|
|
.bind(MAX_ADMIN_BOOTSTRAP_ATTEMPTS)
|
|
.fetch_optional(&mut *tx)
|
|
.await?;
|
|
let Some(contract) = contract else {
|
|
let _ = sqlx::query(
|
|
"update admin_bootstrap_contracts
|
|
set attempts = least(attempts + 1, 100),
|
|
status = case
|
|
when attempts + 1 >= $2 then 'revoked'
|
|
else status
|
|
end
|
|
where token_hash = $1
|
|
and status = 'active'",
|
|
)
|
|
.bind(request.token_hash)
|
|
.bind(MAX_ADMIN_BOOTSTRAP_ATTEMPTS)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
return Err(RegistryError::AdminBootstrapRejected);
|
|
};
|
|
let user_id = format!("user_{}", uuid::Uuid::now_v7().simple());
|
|
let email: String = contract.try_get("email")?;
|
|
let display_name: String = contract.try_get("display_name")?;
|
|
let user_row = sqlx::query(
|
|
"insert into users (
|
|
id, email, display_name, password_hash, status, created_at
|
|
) values (
|
|
$1, $2, $3, $4, 'active', now()
|
|
)
|
|
on conflict (email) do update
|
|
set display_name = excluded.display_name,
|
|
password_hash = excluded.password_hash,
|
|
status = 'active'
|
|
where users.password_hash is null
|
|
returning id",
|
|
)
|
|
.bind(&user_id)
|
|
.bind(&email)
|
|
.bind(&display_name)
|
|
.bind(request.password_hash)
|
|
.fetch_optional(&mut *tx)
|
|
.await
|
|
.map_err(RegistryError::Storage)?;
|
|
let Some(user_row) = user_row else {
|
|
return Err(RegistryError::AdminBootstrapRejected);
|
|
};
|
|
let user_id: String = user_row.try_get("id")?;
|
|
sqlx::query(
|
|
"insert into memberships (
|
|
workspace_id, user_id, role, created_at
|
|
) values (
|
|
'ws_default', $1, 'owner', now()
|
|
)
|
|
on conflict (workspace_id, user_id) do update
|
|
set role = 'owner'",
|
|
)
|
|
.bind(&user_id)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
sqlx::query(
|
|
"update admin_bootstrap_contracts
|
|
set status = 'used',
|
|
used_at = $2::timestamptz,
|
|
used_by_user_id = $3
|
|
where id = $1
|
|
and status = 'active'",
|
|
)
|
|
.bind(contract.try_get::<String, _>("id")?)
|
|
.bind(*request.now)
|
|
.bind(&user_id)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
Ok(UserId::new(user_id))
|
|
}
|
|
pub async fn admin_bootstrap_contract_is_consumable(
|
|
&self,
|
|
token_hash: &str,
|
|
now: &OffsetDateTime,
|
|
) -> Result<bool, RegistryError> {
|
|
let existing_admins = sqlx::query_scalar::<_, i64>(
|
|
"select count(*)::bigint
|
|
from users
|
|
where coalesce(password_hash, '') <> ''",
|
|
)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
if existing_admins > 0 {
|
|
return Ok(false);
|
|
}
|
|
let exists = sqlx::query_scalar::<_, bool>(
|
|
"select exists(
|
|
select 1
|
|
from admin_bootstrap_contracts
|
|
where token_hash = $1
|
|
and status = 'active'
|
|
and expires_at > $2::timestamptz
|
|
and attempts < $3
|
|
)",
|
|
)
|
|
.bind(token_hash)
|
|
.bind(*now)
|
|
.bind(MAX_ADMIN_BOOTSTRAP_ATTEMPTS)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
Ok(exists)
|
|
}
|
|
pub async fn has_password_admin(&self) -> Result<bool, RegistryError> {
|
|
let exists = sqlx::query_scalar::<_, bool>(
|
|
"select exists(
|
|
select 1 from users
|
|
where coalesce(password_hash, '') <> ''
|
|
)",
|
|
)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
Ok(exists)
|
|
}
|
|
pub async fn ensure_bootstrap_user(
|
|
&self,
|
|
email: &str,
|
|
display_name: &str,
|
|
password_hash: &str,
|
|
) -> Result<UserId, RegistryError> {
|
|
let user_id = format!("user_{}", uuid::Uuid::now_v7().simple());
|
|
if let Some(id) = sqlx::query_scalar::<_, String>(
|
|
"insert into users (
|
|
id,
|
|
email,
|
|
display_name,
|
|
password_hash,
|
|
status,
|
|
created_at
|
|
) values (
|
|
$1, $2, $3, $4, 'active', now()
|
|
)
|
|
on conflict (email) do update
|
|
set display_name = excluded.display_name,
|
|
password_hash = excluded.password_hash,
|
|
status = 'active'
|
|
where users.password_hash is null
|
|
returning id",
|
|
)
|
|
.bind(user_id)
|
|
.bind(email)
|
|
.bind(display_name)
|
|
.bind(password_hash)
|
|
.fetch_optional(&self.pool)
|
|
.await?
|
|
{
|
|
return Ok(UserId::new(id));
|
|
}
|
|
let existing = sqlx::query_scalar::<_, String>(
|
|
"select id
|
|
from users
|
|
where email = $1
|
|
limit 1",
|
|
)
|
|
.bind(email)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
Ok(UserId::new(existing))
|
|
}
|
|
pub async fn upsert_bootstrap_user(
|
|
&self,
|
|
email: &str,
|
|
display_name: &str,
|
|
password_hash: &str,
|
|
) -> Result<UserId, RegistryError> {
|
|
self.ensure_bootstrap_user(email, display_name, password_hash)
|
|
.await
|
|
}
|
|
pub async fn ensure_membership(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
user_id: &UserId,
|
|
role: MembershipRole,
|
|
) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"insert into memberships (
|
|
workspace_id,
|
|
user_id,
|
|
role,
|
|
created_at
|
|
) values (
|
|
$1, $2, $3, now()
|
|
)
|
|
on conflict (workspace_id, user_id) do update
|
|
set role = excluded.role",
|
|
)
|
|
.bind(workspace_id.as_str())
|
|
.bind(user_id.as_str())
|
|
.bind(serialize_enum_text(&role, "role")?)
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn get_auth_user_by_email(
|
|
&self,
|
|
email: &str,
|
|
) -> Result<Option<AuthUserRecord>, RegistryError> {
|
|
let row = sqlx::query(
|
|
"select
|
|
id,
|
|
email,
|
|
display_name,
|
|
password_hash,
|
|
status,
|
|
created_at
|
|
from users
|
|
where email = $1
|
|
limit 1",
|
|
)
|
|
.bind(email)
|
|
.fetch_optional(&self.pool)
|
|
.await?;
|
|
row.as_ref().map(map_auth_user_row).transpose()
|
|
}
|
|
pub async fn get_auth_user_by_id(
|
|
&self,
|
|
user_id: &UserId,
|
|
) -> Result<Option<AuthUserRecord>, RegistryError> {
|
|
let row = sqlx::query(
|
|
"select
|
|
id,
|
|
email,
|
|
display_name,
|
|
password_hash,
|
|
status,
|
|
created_at
|
|
from users
|
|
where id = $1
|
|
limit 1",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.fetch_optional(&self.pool)
|
|
.await?;
|
|
row.as_ref().map(map_auth_user_row).transpose()
|
|
}
|
|
pub async fn update_user_profile(
|
|
&self,
|
|
user_id: &UserId,
|
|
email: &str,
|
|
display_name: &str,
|
|
) -> Result<User, RegistryError> {
|
|
let row = sqlx::query!(
|
|
"update users
|
|
set email = $2,
|
|
display_name = $3
|
|
where id = $1
|
|
returning
|
|
id,
|
|
email,
|
|
display_name,
|
|
status,
|
|
created_at as \"created_at!: OffsetDateTime\"",
|
|
user_id.as_str(),
|
|
email,
|
|
display_name,
|
|
)
|
|
.fetch_one(&self.pool)
|
|
.await
|
|
.map_err(|error| map_user_update_error(error, user_id, email))?;
|
|
build_user(
|
|
row.id,
|
|
row.email,
|
|
row.display_name,
|
|
row.status,
|
|
row.created_at,
|
|
)
|
|
}
|
|
pub async fn update_user_password(
|
|
&self,
|
|
user_id: &UserId,
|
|
password_hash: &str,
|
|
) -> Result<(), RegistryError> {
|
|
let result = sqlx::query(
|
|
"update users
|
|
set password_hash = $2
|
|
where id = $1",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.bind(password_hash)
|
|
.execute(&self.pool)
|
|
.await?;
|
|
if result.rows_affected() == 0 {
|
|
return Err(RegistryError::UserNotFound {
|
|
user_id: user_id.as_str().to_owned(),
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
pub async fn update_user_password_and_revoke_other_sessions(
|
|
&self,
|
|
user_id: &UserId,
|
|
current_session_id: &UserSessionId,
|
|
password_hash: &str,
|
|
) -> Result<(), RegistryError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
let result = sqlx::query(
|
|
"update users
|
|
set password_hash = $2
|
|
where id = $1",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.bind(password_hash)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
if result.rows_affected() == 0 {
|
|
return Err(RegistryError::UserNotFound {
|
|
user_id: user_id.as_str().to_owned(),
|
|
});
|
|
}
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set status = 'revoked'
|
|
where user_id = $1
|
|
and id <> $2
|
|
and status = 'active'",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.bind(current_session_id.as_str())
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
Ok(())
|
|
}
|
|
pub async fn update_user_password_and_revoke_all_sessions(
|
|
&self,
|
|
user_id: &UserId,
|
|
password_hash: &str,
|
|
) -> Result<(), RegistryError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
let result = sqlx::query(
|
|
"update users
|
|
set password_hash = $2
|
|
where id = $1",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.bind(password_hash)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
if result.rows_affected() == 0 {
|
|
return Err(RegistryError::UserNotFound {
|
|
user_id: user_id.as_str().to_owned(),
|
|
});
|
|
}
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set status = 'revoked',
|
|
revoked_at = coalesce(revoked_at, now())
|
|
where user_id = $1
|
|
and status = 'active'",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
Ok(())
|
|
}
|
|
pub async fn create_user_session(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
user_id: &UserId,
|
|
current_workspace_id: Option<&WorkspaceId>,
|
|
secret_hash: &str,
|
|
csrf_hash: Option<&str>,
|
|
expires_at: &OffsetDateTime,
|
|
) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"insert into user_sessions (
|
|
id,
|
|
user_id,
|
|
current_workspace_id,
|
|
secret_hash,
|
|
csrf_hash,
|
|
status,
|
|
expires_at,
|
|
last_seen_at,
|
|
created_at
|
|
) values (
|
|
$1,
|
|
$2,
|
|
$3,
|
|
$4,
|
|
$5,
|
|
'active',
|
|
$6::timestamptz,
|
|
now(),
|
|
now()
|
|
)",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.bind(user_id.as_str())
|
|
.bind(current_workspace_id.map(|id| id.as_str()))
|
|
.bind(secret_hash)
|
|
.bind(csrf_hash)
|
|
.bind(*expires_at)
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn get_user_session(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
secret_hash: &str,
|
|
) -> Result<Option<SessionRecord>, RegistryError> {
|
|
let row = sqlx::query(
|
|
"select
|
|
s.id,
|
|
s.user_id,
|
|
s.current_workspace_id,
|
|
s.csrf_hash,
|
|
u.email,
|
|
u.display_name,
|
|
u.status,
|
|
u.created_at as created_at
|
|
from user_sessions s
|
|
join users u on u.id = s.user_id
|
|
where s.id = $1
|
|
and s.secret_hash = $2
|
|
and s.status = 'active'
|
|
and u.status = 'active'
|
|
and s.expires_at > now()
|
|
limit 1",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.bind(secret_hash)
|
|
.fetch_optional(&self.pool)
|
|
.await?;
|
|
let Some(row) = row else {
|
|
return Ok(None);
|
|
};
|
|
let user_id = UserId::new(row.try_get::<String, _>("user_id")?);
|
|
let user = User {
|
|
id: user_id.clone(),
|
|
email: row.try_get("email")?,
|
|
display_name: row.try_get("display_name")?,
|
|
status: deserialize_enum_text(&row.try_get::<String, _>("status")?, "status")?,
|
|
created_at: row.try_get("created_at")?,
|
|
};
|
|
let memberships = self.list_workspaces_for_user(&user_id).await?;
|
|
let stored_workspace_id = row
|
|
.try_get::<Option<String>, _>("current_workspace_id")?
|
|
.map(WorkspaceId::new);
|
|
let default_workspace_id = memberships
|
|
.iter()
|
|
.find(|membership| membership.workspace.id.as_str() == "ws_default")
|
|
.map(|membership| membership.workspace.id.clone());
|
|
let current_workspace_id = default_workspace_id.or_else(|| {
|
|
stored_workspace_id
|
|
.filter(|workspace_id| {
|
|
memberships
|
|
.iter()
|
|
.any(|membership| membership.workspace.id == *workspace_id)
|
|
})
|
|
.or_else(|| {
|
|
memberships
|
|
.first()
|
|
.map(|membership| membership.workspace.id.clone())
|
|
})
|
|
});
|
|
Ok(Some(SessionRecord {
|
|
session_id: UserSessionId::new(row.try_get::<String, _>("id")?),
|
|
user,
|
|
memberships,
|
|
current_workspace_id,
|
|
csrf_hash: row.try_get("csrf_hash")?,
|
|
}))
|
|
}
|
|
pub async fn verify_session_csrf(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
csrf_hash: &str,
|
|
) -> Result<bool, RegistryError> {
|
|
let allowed = sqlx::query_scalar::<_, bool>(
|
|
"select exists(
|
|
select 1
|
|
from user_sessions
|
|
where id = $1
|
|
and csrf_hash = $2
|
|
and status = 'active'
|
|
and expires_at > now()
|
|
)",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.bind(csrf_hash)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
Ok(allowed)
|
|
}
|
|
pub async fn update_user_session_csrf(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
csrf_hash: &str,
|
|
) -> Result<(), RegistryError> {
|
|
let result = sqlx::query(
|
|
"update user_sessions
|
|
set csrf_hash = $2
|
|
where id = $1
|
|
and status = 'active'
|
|
and expires_at > now()",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.bind(csrf_hash)
|
|
.execute(&self.pool)
|
|
.await?;
|
|
if result.rows_affected() == 0 {
|
|
return Err(RegistryError::AdminCsrfRejected);
|
|
}
|
|
Ok(())
|
|
}
|
|
pub async fn touch_user_session(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set last_seen_at = now()
|
|
where id = $1
|
|
and (
|
|
last_seen_at is null
|
|
or last_seen_at < now() - interval '1 minute'
|
|
)",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn revoke_user_session(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set status = 'revoked',
|
|
revoked_at = coalesce(revoked_at, now())
|
|
where id = $1",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn revoke_all_user_sessions(&self, user_id: &UserId) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set status = 'revoked',
|
|
revoked_at = coalesce(revoked_at, now())
|
|
where user_id = $1
|
|
and status = 'active'",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn recover_admin_password(
|
|
&self,
|
|
request: RecoverAdminPasswordRequest<'_>,
|
|
) -> Result<UserId, RegistryError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
let row = sqlx::query(
|
|
"update users
|
|
set password_hash = $2,
|
|
status = 'active'
|
|
where email = $1
|
|
and coalesce(password_hash, '') <> ''
|
|
returning id",
|
|
)
|
|
.bind(request.email)
|
|
.bind(request.password_hash)
|
|
.fetch_optional(&mut *tx)
|
|
.await?;
|
|
let Some(row) = row else {
|
|
return Err(RegistryError::AdminRecoveryRejected);
|
|
};
|
|
let user_id = UserId::new(row.try_get::<String, _>("id")?);
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set status = 'revoked',
|
|
revoked_at = coalesce(revoked_at, now())
|
|
where user_id = $1
|
|
and status = 'active'",
|
|
)
|
|
.bind(user_id.as_str())
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
sqlx::query(
|
|
"insert into admin_security_audit_events (
|
|
id, action, outcome, actor_user_id, session_id, request_id, trace_id, source, created_at
|
|
) values (
|
|
$1, 'recovery_completed', 'success', $2, null, null, null, 'local_cli', now()
|
|
)",
|
|
)
|
|
.bind(request.audit_id)
|
|
.bind(user_id.as_str())
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
Ok(user_id)
|
|
}
|
|
pub async fn login_backoff_locked_until(
|
|
&self,
|
|
scope_hash: &str,
|
|
) -> Result<Option<OffsetDateTime>, RegistryError> {
|
|
let value = sqlx::query_scalar::<_, Option<OffsetDateTime>>(
|
|
"select locked_until
|
|
from admin_login_backoff
|
|
where scope_hash = $1
|
|
and locked_until > now()",
|
|
)
|
|
.bind(scope_hash)
|
|
.fetch_optional(&self.pool)
|
|
.await?
|
|
.flatten();
|
|
Ok(value)
|
|
}
|
|
pub async fn record_login_failure(
|
|
&self,
|
|
scope_hash: &str,
|
|
now: &OffsetDateTime,
|
|
) -> Result<OffsetDateTime, RegistryError> {
|
|
let row = sqlx::query(
|
|
"insert into admin_login_backoff (
|
|
scope_hash, failure_count, locked_until, last_attempt_at, updated_at
|
|
) values (
|
|
$1, 1, $2::timestamptz + interval '1 second', $2::timestamptz, $2::timestamptz
|
|
)
|
|
on conflict (scope_hash) do update
|
|
set failure_count = least(admin_login_backoff.failure_count + 1, 1000),
|
|
locked_until = $2::timestamptz + (
|
|
least(300, power(2, least(admin_login_backoff.failure_count + 1, 8)))::int
|
|
* interval '1 second'
|
|
),
|
|
last_attempt_at = $2::timestamptz,
|
|
updated_at = $2::timestamptz
|
|
returning locked_until",
|
|
)
|
|
.bind(scope_hash)
|
|
.bind(*now)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
row.try_get("locked_until").map_err(RegistryError::Storage)
|
|
}
|
|
pub async fn reset_login_backoff(&self, scope_hash: &str) -> Result<(), RegistryError> {
|
|
sqlx::query("delete from admin_login_backoff where scope_hash = $1")
|
|
.bind(scope_hash)
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn record_admin_security_audit(
|
|
&self,
|
|
request: AdminSecurityAuditRequest<'_>,
|
|
) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"insert into admin_security_audit_events (
|
|
id, action, outcome, actor_user_id, session_id, request_id, trace_id, source, created_at
|
|
) values (
|
|
$1, $2, $3, $4, $5, $6, $7, $8, now()
|
|
)",
|
|
)
|
|
.bind(request.id)
|
|
.bind(request.action)
|
|
.bind(request.outcome)
|
|
.bind(request.actor_user_id.map(|id| id.as_str()))
|
|
.bind(request.session_id.map(|id| id.as_str()))
|
|
.bind(request.request_id)
|
|
.bind(request.trace_id)
|
|
.bind(request.source)
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn set_user_session_current_workspace(
|
|
&self,
|
|
session_id: &UserSessionId,
|
|
workspace_id: &WorkspaceId,
|
|
) -> Result<(), RegistryError> {
|
|
sqlx::query(
|
|
"update user_sessions
|
|
set current_workspace_id = $2
|
|
where id = $1",
|
|
)
|
|
.bind(session_id.as_str())
|
|
.bind(workspace_id.as_str())
|
|
.execute(&self.pool)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
pub async fn user_has_workspace_access(
|
|
&self,
|
|
user_id: &UserId,
|
|
workspace_id: &WorkspaceId,
|
|
) -> Result<bool, RegistryError> {
|
|
let row = sqlx::query!(
|
|
"select exists(
|
|
select 1
|
|
from memberships
|
|
where user_id = $1
|
|
and workspace_id = $2
|
|
) as \"allowed!\"",
|
|
user_id.as_str(),
|
|
workspace_id.as_str(),
|
|
)
|
|
.fetch_one(&self.pool)
|
|
.await?;
|
|
Ok(row.allowed)
|
|
}
|
|
pub async fn save_auth_profile(
|
|
&self,
|
|
request: SaveAuthProfileRequest<'_>,
|
|
) -> Result<(), RegistryError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
let mut secret_ids = request.profile.config.secret_ids();
|
|
secret_ids.sort_by(|left, right| left.as_str().cmp(right.as_str()));
|
|
secret_ids.dedup_by(|left, right| left.as_str() == right.as_str());
|
|
for secret_id in &secret_ids {
|
|
super::secret::lock_secret_reference(&mut tx, request.workspace_id, secret_id).await?;
|
|
let row = sqlx::query(
|
|
"select status
|
|
from secrets
|
|
where workspace_id = $1 and id = $2
|
|
for update",
|
|
)
|
|
.bind(request.workspace_id.as_str())
|
|
.bind(secret_id.as_str())
|
|
.fetch_optional(&mut *tx)
|
|
.await?;
|
|
let Some(row) = row else {
|
|
return Err(RegistryError::SecretNotFound {
|
|
secret_id: secret_id.as_str().to_owned(),
|
|
});
|
|
};
|
|
if row.get::<String, _>("status") != "active" {
|
|
return Err(RegistryError::SecretInactive {
|
|
secret_id: secret_id.as_str().to_owned(),
|
|
});
|
|
}
|
|
}
|
|
sqlx::query(
|
|
"insert into auth_profiles (
|
|
id,
|
|
workspace_id,
|
|
name,
|
|
kind,
|
|
config_json,
|
|
created_at,
|
|
updated_at
|
|
) values ($1, $2, $3, $4, $5, $6::timestamptz, $7::timestamptz)
|
|
on conflict(id) do update set
|
|
workspace_id = excluded.workspace_id,
|
|
name = excluded.name,
|
|
kind = excluded.kind,
|
|
config_json = excluded.config_json,
|
|
updated_at = excluded.updated_at",
|
|
)
|
|
.bind(request.profile.id.as_str())
|
|
.bind(request.workspace_id.as_str())
|
|
.bind(&request.profile.name)
|
|
.bind(serialize_enum_text(&request.profile.kind, "kind")?)
|
|
.bind(Json(serialize_json_value(&request.profile.config)?))
|
|
.bind(request.profile.created_at)
|
|
.bind(request.profile.updated_at)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
Ok(())
|
|
}
|
|
pub async fn get_auth_profile(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
auth_profile_id: &crank_core::AuthProfileId,
|
|
) -> Result<Option<AuthProfile>, RegistryError> {
|
|
let row = sqlx::query!(
|
|
"select
|
|
id,
|
|
workspace_id,
|
|
name,
|
|
kind,
|
|
config_json,
|
|
created_at as \"created_at!: OffsetDateTime\",
|
|
updated_at as \"updated_at!: OffsetDateTime\"
|
|
from auth_profiles
|
|
where workspace_id = $1 and id = $2",
|
|
workspace_id.as_str(),
|
|
auth_profile_id.as_str(),
|
|
)
|
|
.fetch_optional(&self.pool)
|
|
.await?;
|
|
row.map(|row| {
|
|
build_auth_profile(
|
|
row.id,
|
|
row.workspace_id,
|
|
row.name,
|
|
row.kind,
|
|
row.config_json,
|
|
row.created_at,
|
|
row.updated_at,
|
|
)
|
|
})
|
|
.transpose()
|
|
}
|
|
pub async fn list_auth_profiles(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
) -> Result<Vec<AuthProfile>, RegistryError> {
|
|
let rows = sqlx::query!(
|
|
"select
|
|
id,
|
|
workspace_id,
|
|
name,
|
|
kind,
|
|
config_json,
|
|
created_at as \"created_at!: OffsetDateTime\",
|
|
updated_at as \"updated_at!: OffsetDateTime\"
|
|
from auth_profiles
|
|
where workspace_id = $1
|
|
order by name asc",
|
|
workspace_id.as_str(),
|
|
)
|
|
.fetch_all(&self.pool)
|
|
.await?;
|
|
rows.into_iter()
|
|
.map(|row| {
|
|
build_auth_profile(
|
|
row.id,
|
|
row.workspace_id,
|
|
row.name,
|
|
row.kind,
|
|
row.config_json,
|
|
row.created_at,
|
|
row.updated_at,
|
|
)
|
|
})
|
|
.collect()
|
|
}
|
|
pub async fn list_auth_profiles_referencing_secret(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
secret_id: &SecretId,
|
|
) -> Result<Vec<AuthProfile>, RegistryError> {
|
|
let profiles = self.list_auth_profiles(workspace_id).await?;
|
|
Ok(profiles
|
|
.into_iter()
|
|
.filter(|profile| {
|
|
profile
|
|
.config
|
|
.secret_ids()
|
|
.into_iter()
|
|
.any(|candidate| candidate == secret_id)
|
|
})
|
|
.collect())
|
|
}
|
|
}
|