use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Redirect, Response};
use rustango::extractors::Tenant;
use crate::page::Page;
use crate::view_restriction::{self, RestrictionKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Denial {
NeedsLogin,
Forbidden,
NeedsPassword { page_id: i64 },
}
pub async fn decide(
tenant: &Tenant,
page: &Page,
viewer: Option<&rustango::tenancy::auth::User>,
headers: &HeaderMap,
) -> Option<Denial> {
let restriction = match view_restriction::effective_or_type_for_page(tenant.pool(), page).await
{
Ok(opt) => opt?,
Err(e) => {
tracing::warn!(
target: "rustango_cms::view_restriction",
error = %e,
page_id = ?page.id.get().copied(),
"restriction lookup failed; denying request"
);
return Some(Denial::Forbidden);
}
};
let Some(kind) = restriction.parsed_kind() else {
return Some(Denial::Forbidden);
};
match kind {
RestrictionKind::Login => {
if viewer.is_some() {
None
} else {
Some(Denial::NeedsLogin)
}
}
RestrictionKind::Groups => {
let allowed = restriction.parsed_groups();
match viewer {
None => Some(Denial::NeedsLogin),
Some(u) => {
if u.is_superuser {
return None;
}
let uid = u.id.get().copied().unwrap_or_default();
if user_in_any_role(tenant, uid, &allowed).await {
None
} else {
Some(Denial::Forbidden)
}
}
}
}
RestrictionKind::Permission => {
let allowed = restriction.parsed_codenames();
match viewer {
None => Some(Denial::NeedsLogin),
Some(u) => {
let uid = u.id.get().copied().unwrap_or_default();
if viewer_has_any_codename(tenant.pool(), uid, &allowed).await {
None
} else {
Some(Denial::Forbidden)
}
}
}
}
RestrictionKind::Password => {
let page_id = restriction.page_id;
if has_valid_password_grant(headers, &tenant.org.slug, &restriction, page_id, now_secs()) {
None
} else {
Some(Denial::NeedsPassword { page_id })
}
}
}
}
pub async fn enforce(
tenant: &Tenant,
page: &Page,
viewer: Option<&rustango::tenancy::auth::User>,
headers: &HeaderMap,
raw_path: &str,
) -> Option<Response> {
Some(match decide(tenant, page, viewer, headers).await? {
Denial::NeedsLogin => login_redirect(raw_path),
Denial::Forbidden => {
(StatusCode::FORBIDDEN, "You don't have access to this page.").into_response()
}
Denial::NeedsPassword { page_id } => password_prompt_redirect(page_id, raw_path),
})
}
pub(crate) async fn viewer_has_any_codename(
pool: &rustango::sql::Pool,
user_id: i64,
codenames: &[String],
) -> bool {
if codenames.is_empty() {
return false;
}
let refs: Vec<&str> = codenames.iter().map(String::as_str).collect();
rustango::tenancy::has_any_perm_pool(user_id, &refs, pool)
.await
.unwrap_or(false)
}
fn login_redirect(raw_path: &str) -> Response {
let encoded = url_encode(raw_path);
Redirect::to(&format!("/members/login?next={encoded}")).into_response()
}
fn password_prompt_redirect(page_id: i64, raw_path: &str) -> Response {
let encoded = url_encode(raw_path);
Redirect::to(&format!(
"/__cms-view-password?page={page_id}&next={encoded}"
))
.into_response()
}
pub fn url_encode_path(s: &str) -> String {
url_encode(s)
}
fn url_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for byte in s.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
out.push(byte as char);
}
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
async fn user_in_any_role(tenant: &Tenant, user_id: i64, role_ids: &[i64]) -> bool {
if role_ids.is_empty() {
return false;
}
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let rows: Vec<rustango::tenancy::permissions::UserRole> =
rustango::tenancy::permissions::UserRole::objects()
.where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
.where_(
rustango::tenancy::permissions::UserRole::role_id.is_in(role_ids.iter().copied()),
)
.fetch(tenant.pool())
.await
.unwrap_or_default();
!rows.is_empty()
}
pub const GRANT_TTL_SECS: i64 = 7 * 24 * 60 * 60;
#[must_use]
pub fn grant_cookie_name(page_id: i64) -> String {
format!("rcms_view_grant_{page_id}")
}
fn now_secs() -> i64 {
chrono::Utc::now().timestamp()
}
fn has_valid_password_grant(
headers: &HeaderMap,
tenant_slug: &str,
restriction: &view_restriction::PageViewRestriction,
page_id: i64,
now: i64,
) -> bool {
let Some(cookie_str) = headers
.get(axum::http::header::COOKIE)
.and_then(|v| v.to_str().ok())
else {
return false;
};
let prefix = format!("{}=", grant_cookie_name(page_id));
cookie_str.split(';').filter_map(|c| c.trim().strip_prefix(&prefix)).any(|value| {
let Some((issued, hex)) = value.split_once(':') else {
return false;
};
let Ok(issued) = issued.parse::<i64>() else {
return false;
};
let fresh = issued <= now && now - issued <= GRANT_TTL_SECS;
let expected = grant_signature(tenant_slug, restriction, page_id, issued);
fresh && crate::signing::constant_time_eq(expected.as_bytes(), hex.as_bytes())
})
}
#[must_use]
pub fn grant_signature(
tenant_slug: &str,
restriction: &view_restriction::PageViewRestriction,
page_id: i64,
issued_at: i64,
) -> String {
let fingerprint =
crate::signing::hmac_sha256_hex(b"rcms-grant-fp", restriction.password_hash.as_bytes());
crate::signing::hmac_sha256_hex(
crate::signing::secret(),
format!("view_grant|{tenant_slug}|{page_id}|{fingerprint}|{issued_at}").as_bytes(),
)
}
#[must_use]
pub fn grant_cookie(
tenant_slug: &str,
restriction: &view_restriction::PageViewRestriction,
page_id: i64,
) -> String {
let issued = now_secs();
format!(
"{}={issued}:{}; Path=/; Max-Age={GRANT_TTL_SECS}; SameSite=Lax; HttpOnly",
grant_cookie_name(page_id),
grant_signature(tenant_slug, restriction, page_id, issued),
)
}
#[cfg(test)]
mod grant_tests {
use super::*;
use rustango::sql::Auto;
fn restriction(hash: &str) -> view_restriction::PageViewRestriction {
view_restriction::PageViewRestriction {
id: Auto::Unset,
page_id: 42,
kind: "password".into(),
password_hash: hash.into(),
group_ids: serde_json::json!([]),
codenames: serde_json::json!([]),
created_at: Auto::Unset,
updated_at: Auto::Unset,
}
}
fn with_cookie(value: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert(axum::http::header::COOKIE, value.parse().expect("header"));
h
}
#[test]
fn a_grant_is_scoped_and_expires() {
let r = restriction("$argon2id$v=19$m=19456,t=2,p=1$abc$def");
let now = 1_800_000_000;
let sig = grant_signature("acme", &r, 42, now);
let ok = with_cookie(&format!("other=1; rcms_view_grant_42={now}:{sig}"));
assert!(has_valid_password_grant(&ok, "acme", &r, 42, now + 60));
assert!(!has_valid_password_grant(&ok, "globex", &r, 42, now), "another tenant");
assert!(!has_valid_password_grant(&ok, "acme", &r, 43, now), "another page");
assert!(
!has_valid_password_grant(&ok, "acme", &restriction("$argon2id$new"), 42, now),
"a new password revokes it"
);
assert!(
!has_valid_password_grant(&ok, "acme", &r, 42, now + GRANT_TTL_SECS + 1),
"expired on the server"
);
let forged = with_cookie(&format!("rcms_view_grant_42={}:{sig}", now + 3600));
assert!(!has_valid_password_grant(&forged, "acme", &r, 42, now + 3600), "issue time is signed");
}
#[test]
fn grants_for_two_pages_coexist() {
assert_ne!(grant_cookie_name(1), grant_cookie_name(2));
let c = grant_cookie("acme", &restriction("h"), 7);
assert!(c.starts_with("rcms_view_grant_7=") && c.contains("HttpOnly"), "{c}");
}
}