feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1,635 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Query, Request, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use rmm_domain::{TENANT_A, TENANT_B, jobs::hash};
|
||||
use rmm_oidc_auth::{CLEAR_BINDING_COOKIE, Callback, Identity};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use sqlx::Row;
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
sync::Mutex,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Principal {
|
||||
pub tenant: Uuid,
|
||||
pub name: String,
|
||||
pub operator: bool,
|
||||
pub session_hash: Option<String>,
|
||||
pub csrf: Option<String>,
|
||||
pub scopes: Option<BTreeSet<String>>,
|
||||
pub testsimulation: bool,
|
||||
pub identity: Option<Identity>,
|
||||
pub tenants: Vec<Uuid>,
|
||||
}
|
||||
impl Principal {
|
||||
pub fn approval_origin(&self) -> &'static str {
|
||||
if self.testsimulation {
|
||||
"dev_test_browser_simulation"
|
||||
} else {
|
||||
"human_webui"
|
||||
}
|
||||
}
|
||||
pub fn permits_scope(&self, permission: &str) -> bool {
|
||||
self.scopes.as_ref().is_none_or(|s| s.contains(permission))
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Session {
|
||||
principal: Principal,
|
||||
expires: DateTime<Utc>,
|
||||
}
|
||||
pub struct Auth {
|
||||
sessions: Mutex<HashMap<String, Session>>,
|
||||
login_attempts: Mutex<Vec<std::time::Instant>>,
|
||||
username: Option<String>,
|
||||
password_hash: Option<String>,
|
||||
operator_a: Option<String>,
|
||||
operator_b: Option<String>,
|
||||
pub origin: String,
|
||||
pub oidc: Option<crate::oidc::Provider>,
|
||||
development: bool,
|
||||
}
|
||||
impl Auth {
|
||||
pub fn validate_separation(&self, a: &[u8; 32], b: &[u8; 32]) -> anyhow::Result<()> {
|
||||
let mut hashes = vec![hex::encode(a), hex::encode(b)];
|
||||
hashes.extend(
|
||||
[
|
||||
self.password_hash.clone(),
|
||||
self.operator_a.clone(),
|
||||
self.operator_b.clone(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
);
|
||||
let count = hashes.len();
|
||||
hashes.sort();
|
||||
hashes.dedup();
|
||||
anyhow::ensure!(
|
||||
hashes.len() == count,
|
||||
"browser, operator and viewer credentials must be distinct"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn operator_enabled(&self, name: &str, tenant: Uuid) -> bool {
|
||||
(self.oidc.is_some() && name.starts_with("oidc:") && name.len() == 69)
|
||||
|| (name == "simulated-testprincipal-a"
|
||||
&& tenant.to_string() == TENANT_A
|
||||
&& self.username.is_some())
|
||||
|| (name == format!("automation:{tenant}")
|
||||
&& ((tenant.to_string() == TENANT_A && self.operator_a.is_some())
|
||||
|| (tenant.to_string() == TENANT_B && self.operator_b.is_some())))
|
||||
}
|
||||
pub async fn from_env(profile: &str) -> anyhow::Result<Self> {
|
||||
let development = profile == "development";
|
||||
let optional = |name: &str| std::env::var(name).ok().filter(|s| !s.is_empty());
|
||||
if !development {
|
||||
anyhow::ensure!(
|
||||
[
|
||||
"RMM_DEV_USERNAME",
|
||||
"RMM_DEV_PASSWORD",
|
||||
"RMM_OPERATOR_A",
|
||||
"RMM_OPERATOR_B",
|
||||
"RMM_VIEWER_A",
|
||||
"RMM_VIEWER_B"
|
||||
]
|
||||
.iter()
|
||||
.all(|n| optional(n).is_none()),
|
||||
"development credentials forbidden in production"
|
||||
);
|
||||
}
|
||||
let username = optional("RMM_DEV_USERNAME");
|
||||
let password = optional("RMM_DEV_PASSWORD");
|
||||
anyhow::ensure!(
|
||||
username.is_some() == password.is_some(),
|
||||
"dev login requires username AND password"
|
||||
);
|
||||
let secret = |name| -> anyhow::Result<Option<String>> {
|
||||
let value = optional(name);
|
||||
if let Some(v) = &value {
|
||||
anyhow::ensure!(v.len() >= 32, "development credential too short");
|
||||
}
|
||||
Ok(value.map(|v| hash(v.as_bytes())))
|
||||
};
|
||||
let origin =
|
||||
optional("RMM_UI_ORIGIN").unwrap_or_else(|| "https://rmm-dev.internal:18443".into());
|
||||
let url = url::Url::parse(&origin)?;
|
||||
anyhow::ensure!(
|
||||
url.scheme() == "https" && url.origin().ascii_serialization() == origin,
|
||||
"UI origin must be an exact HTTPS origin"
|
||||
);
|
||||
let oidc = crate::oidc::configured(profile, &origin).await?;
|
||||
anyhow::ensure!(
|
||||
development || oidc.is_some(),
|
||||
"production OIDC not_configured"
|
||||
);
|
||||
Ok(Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
login_attempts: Mutex::new(vec![]),
|
||||
username,
|
||||
password_hash: secret("RMM_DEV_PASSWORD")?,
|
||||
operator_a: secret("RMM_OPERATOR_A")?,
|
||||
operator_b: secret("RMM_OPERATOR_B")?,
|
||||
origin,
|
||||
oidc,
|
||||
development,
|
||||
})
|
||||
}
|
||||
fn origin(&self, h: &HeaderMap) -> Result<(), StatusCode> {
|
||||
if h.get("origin").and_then(|v| v.to_str().ok()) != Some(self.origin.as_str()) {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn rate_limit(&self) -> Result<(), StatusCode> {
|
||||
let mut attempts = self
|
||||
.login_attempts
|
||||
.lock()
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
attempts.retain(|t| t.elapsed() < std::time::Duration::from_secs(60));
|
||||
if attempts.len() >= 40 {
|
||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
attempts.push(std::time::Instant::now());
|
||||
Ok(())
|
||||
}
|
||||
pub async fn principal(
|
||||
&self,
|
||||
state: &crate::State,
|
||||
h: &HeaderMap,
|
||||
write: bool,
|
||||
) -> Result<Principal, StatusCode> {
|
||||
let selected = h
|
||||
.get("x-rmm-tenant")
|
||||
.map(|v| {
|
||||
v.to_str()
|
||||
.ok()
|
||||
.and_then(|v| Uuid::parse_str(v).ok())
|
||||
.ok_or(StatusCode::BAD_REQUEST)
|
||||
})
|
||||
.transpose()?;
|
||||
let mut p = if let Some(b) = h.get("authorization") {
|
||||
let raw = b
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|s| s.strip_prefix("Bearer "))
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let digest = hash(raw.as_bytes());
|
||||
let local = if !self.development {
|
||||
None
|
||||
} else if self.operator_a.as_ref().is_some_and(|s| equal(s, &digest)) {
|
||||
Some((TENANT_A, true))
|
||||
} else if self.operator_b.as_ref().is_some_and(|s| equal(s, &digest)) {
|
||||
Some((TENANT_B, true))
|
||||
} else if equal(&hex::encode(state.viewer_a), &digest) {
|
||||
Some((TENANT_A, false))
|
||||
} else if equal(&hex::encode(state.viewer_b), &digest) {
|
||||
Some((TENANT_B, false))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((tenant, operator)) = local {
|
||||
let tenant =
|
||||
Uuid::parse_str(tenant).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Principal {
|
||||
tenant,
|
||||
name: format!(
|
||||
"{}:{tenant}",
|
||||
if operator { "automation" } else { "viewer" }
|
||||
),
|
||||
operator,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: None,
|
||||
testsimulation: true,
|
||||
identity: None,
|
||||
tenants: vec![tenant],
|
||||
}
|
||||
} else {
|
||||
let provider = self.oidc.as_ref().ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let bearer = provider
|
||||
.auth
|
||||
.verify_mcp_bearer(raw, &[])
|
||||
.await
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
self.mapped(state, bearer.identity, Some(bearer.scopes), selected, false)
|
||||
.await?
|
||||
}
|
||||
} else {
|
||||
let token = cookie(h, "__Host-rmm_session")?;
|
||||
let mut p = {
|
||||
let sessions = self
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
sessions
|
||||
.get(&hash(token.as_bytes()))
|
||||
.filter(|s| s.expires > Utc::now())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?
|
||||
.principal
|
||||
.clone()
|
||||
};
|
||||
if let Some(identity) = p.identity.clone() {
|
||||
let mapped = self.mapped(state, identity, None, selected, true).await?;
|
||||
p.tenant = mapped.tenant;
|
||||
p.tenants = mapped.tenants;
|
||||
}
|
||||
if write {
|
||||
self.origin(h)?;
|
||||
let csrf = h
|
||||
.get("x-csrf-token")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or(StatusCode::FORBIDDEN)?;
|
||||
if !p.csrf.as_deref().is_some_and(|v| equal(v, csrf)) {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
}
|
||||
p
|
||||
};
|
||||
if selected.is_some_and(|t| t != p.tenant) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, p.tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let active: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM memberships WHERE principal=$1 AND revoked_at IS NULL)",
|
||||
)
|
||||
.bind(&p.name)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if !active {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
if write && !p.operator {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
if h.contains_key("authorization") {
|
||||
p.session_hash = None;
|
||||
p.csrf = None;
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
async fn mapped(
|
||||
&self,
|
||||
state: &crate::State,
|
||||
identity: Identity,
|
||||
scopes: Option<BTreeSet<String>>,
|
||||
selected: Option<Uuid>,
|
||||
browser: bool,
|
||||
) -> Result<Principal, StatusCode> {
|
||||
let row = sqlx::query("SELECT principal,tenant_ids FROM oidc_identity_binding($1,$2)")
|
||||
.bind(&identity.issuer)
|
||||
.bind(&identity.subject)
|
||||
.fetch_optional(&state.pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
|
||||
.ok_or(StatusCode::FORBIDDEN)?;
|
||||
let name: String = row.get("principal");
|
||||
if name != crate::oidc::principal_id(&identity.issuer, &identity.subject) {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let mut tenants: Vec<Uuid> = row.get("tenant_ids");
|
||||
tenants.sort();
|
||||
tenants.dedup();
|
||||
let tenant = selected
|
||||
.or_else(|| tenants.first().copied())
|
||||
.filter(|t| tenants.contains(t))
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let kind: Option<String> = sqlx::query_scalar(
|
||||
"SELECT kind FROM memberships WHERE principal=$1 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(&name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let kind = kind.ok_or(StatusCode::FORBIDDEN)?;
|
||||
if browser && kind != "human" {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
Ok(Principal {
|
||||
tenant,
|
||||
name,
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes,
|
||||
testsimulation: self.oidc.as_ref().is_some_and(|o| o.simulation),
|
||||
identity: Some(identity),
|
||||
tenants,
|
||||
})
|
||||
}
|
||||
fn establish(&self, mut p: Principal) -> Result<Response, StatusCode> {
|
||||
let token = random();
|
||||
let key = hash(token.as_bytes());
|
||||
p.session_hash = Some(key.clone());
|
||||
p.csrf = Some(random());
|
||||
let mut sessions = self
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
sessions.retain(|_, s| s.expires > Utc::now());
|
||||
if sessions.len() >= 128 {
|
||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
sessions.insert(
|
||||
key,
|
||||
Session {
|
||||
principal: p,
|
||||
expires: Utc::now() + Duration::hours(1),
|
||||
},
|
||||
);
|
||||
let mut response = Redirect::to("/").into_response();
|
||||
response.headers_mut().append("set-cookie",HeaderValue::from_str(&format!("__Host-rmm_session={token}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600")).map_err(|_|StatusCode::INTERNAL_SERVER_ERROR)?);
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
fn random() -> String {
|
||||
format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
|
||||
}
|
||||
fn equal(a: &str, b: &str) -> bool {
|
||||
a.len() == b.len() && openssl::memcmp::eq(a.as_bytes(), b.as_bytes())
|
||||
}
|
||||
pub fn error_code(status: StatusCode) -> &'static str {
|
||||
match status {
|
||||
StatusCode::NOT_FOUND => "NOT_FOUND",
|
||||
StatusCode::UNAUTHORIZED => "UNAUTHENTICATED",
|
||||
StatusCode::SERVICE_UNAVAILABLE => "DEPENDENCY_UNAVAILABLE",
|
||||
StatusCode::BAD_REQUEST => "VALIDATION_ERROR",
|
||||
_ => "FORBIDDEN",
|
||||
}
|
||||
}
|
||||
fn cookie<'a>(h: &'a HeaderMap, name: &str) -> Result<&'a str, StatusCode> {
|
||||
let mut values = h
|
||||
.get_all("cookie")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.flat_map(|c| c.split(';'))
|
||||
.filter_map(|s| s.trim().split_once('='))
|
||||
.filter(|(n, _)| *n == name)
|
||||
.map(|(_, v)| v);
|
||||
let result = values.next().ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if values.next().is_some() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Login {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
pub async fn login(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Json(input): Json<Login>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
if !state.auth.development {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
state.auth.origin(&h)?;
|
||||
state.auth.rate_limit()?;
|
||||
if input.username.len() > 128 || input.password.len() > 256 {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if !state
|
||||
.auth
|
||||
.username
|
||||
.as_ref()
|
||||
.is_some_and(|u| equal(u, &input.username))
|
||||
|| !state
|
||||
.auth
|
||||
.password_hash
|
||||
.as_ref()
|
||||
.is_some_and(|p| equal(p, &hash(input.password.as_bytes())))
|
||||
{
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let tenant = Uuid::parse_str(TENANT_A).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let p = Principal {
|
||||
tenant,
|
||||
name: "simulated-testprincipal-a".into(),
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: None,
|
||||
testsimulation: true,
|
||||
identity: None,
|
||||
tenants: vec![tenant],
|
||||
};
|
||||
let mut response = state.auth.establish(p)?;
|
||||
*response.status_mut() = StatusCode::OK;
|
||||
response.headers_mut().remove("location");
|
||||
*response.body_mut() =
|
||||
axum::body::Body::from("{\"authenticated\":true,\"testsimulation\":true}");
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", HeaderValue::from_static("application/json"));
|
||||
Ok(response)
|
||||
}
|
||||
pub async fn configuration(State(state): State<crate::State>) -> Json<serde_json::Value> {
|
||||
Json(
|
||||
json!({"oidc_configured":state.auth.oidc.is_some(),"oidc_login_url":state.auth.oidc.as_ref().map(|_|"/auth/oidc/login"),"dev_login_enabled":state.auth.username.is_some()}),
|
||||
)
|
||||
}
|
||||
pub async fn oidc_login(State(state): State<crate::State>) -> Result<Response, StatusCode> {
|
||||
state.auth.rate_limit()?;
|
||||
let start = state
|
||||
.auth
|
||||
.oidc
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::NOT_IMPLEMENTED)?
|
||||
.auth
|
||||
.login_start()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let mut response = Redirect::to(start.authorization_url.as_str()).into_response();
|
||||
response.headers_mut().append(
|
||||
"set-cookie",
|
||||
HeaderValue::from_str(&start.binding_set_cookie)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Code {
|
||||
code: String,
|
||||
state: String,
|
||||
iss: Option<String>,
|
||||
}
|
||||
pub async fn oidc_callback(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
query: Result<Query<Code>, axum::extract::rejection::QueryRejection>,
|
||||
) -> Response {
|
||||
let result = async {
|
||||
state.auth.rate_limit()?;
|
||||
let Query(code) = query.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let binding = cookie(&h, "__Host-rmm_oidc_binding")?;
|
||||
let provider = state
|
||||
.auth
|
||||
.oidc
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::NOT_IMPLEMENTED)?;
|
||||
let identity = provider
|
||||
.auth
|
||||
.callback(Callback {
|
||||
code: &code.code,
|
||||
state: &code.state,
|
||||
browser_binding: binding,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
if code
|
||||
.iss
|
||||
.as_deref()
|
||||
.is_some_and(|iss| iss != identity.issuer)
|
||||
{
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let p = state
|
||||
.auth
|
||||
.mapped(&state, identity, None, None, true)
|
||||
.await?;
|
||||
state.auth.establish(p)
|
||||
}
|
||||
.await;
|
||||
let mut response = match result {
|
||||
Ok(r) => r,
|
||||
Err(s) => (s, Json(json!({"code":"UNAUTHENTICATED","message":"OIDC callback failed","retryable":false,"correlation_id":Uuid::new_v4(),"details":{}}))).into_response(),
|
||||
};
|
||||
response
|
||||
.headers_mut()
|
||||
.append("set-cookie", HeaderValue::from_static(CLEAR_BINDING_COOKIE));
|
||||
response
|
||||
}
|
||||
pub async fn session(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let p = state.auth.principal(&state, &h, false).await?;
|
||||
if p.session_hash.is_none() {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, p.tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let permissions: Option<Vec<String>> = sqlx::query_scalar(
|
||||
"SELECT permissions FROM memberships WHERE principal=$1 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(&p.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
Ok(Json(
|
||||
json!({"principal":p.name,"tenant_id":p.tenant,"permissions":permissions.ok_or(StatusCode::FORBIDDEN)?,"roles":[if p.testsimulation {"dev_test_member"} else {"member"}],"csrf_token":p.csrf,"testsimulation":p.testsimulation,"approval_origin":p.approval_origin()}),
|
||||
))
|
||||
}
|
||||
pub async fn logout(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let p = state.auth.principal(&state, &h, true).await?;
|
||||
let key = p.session_hash.ok_or(StatusCode::FORBIDDEN)?;
|
||||
state
|
||||
.auth
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
|
||||
.remove(&key);
|
||||
let mut response = StatusCode::NO_CONTENT.into_response();
|
||||
response.headers_mut().insert(
|
||||
"set-cookie",
|
||||
HeaderValue::from_static(
|
||||
"__Host-rmm_session=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0",
|
||||
),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
/// Tenant header is only a selection, never authority; path selection overrides caller headers.
|
||||
pub async fn context(mut request: Request, next: Next) -> Response {
|
||||
if let Some(t) = request
|
||||
.uri()
|
||||
.path()
|
||||
.strip_prefix("/api/v1/tenants/")
|
||||
.and_then(|p| p.split('/').next())
|
||||
.and_then(|s| Uuid::parse_str(s).ok())
|
||||
&& let Ok(value) = HeaderValue::from_str(&t.to_string())
|
||||
{
|
||||
request.headers_mut().insert("x-rmm-tenant", value);
|
||||
}
|
||||
let auth = request.uri().path().starts_with("/auth/");
|
||||
let mut response = next.run(request).await;
|
||||
if auth {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("cache-control", HeaderValue::from_static("no-store"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn duplicate_binding_cookies_are_rejected() {
|
||||
let mut h = HeaderMap::new();
|
||||
h.append(
|
||||
"cookie",
|
||||
HeaderValue::from_static("__Host-rmm_oidc_binding=one"),
|
||||
);
|
||||
assert_eq!(cookie(&h, "__Host-rmm_oidc_binding"), Ok("one"));
|
||||
h.append(
|
||||
"cookie",
|
||||
HeaderValue::from_static("other=x; __Host-rmm_oidc_binding=two"),
|
||||
);
|
||||
assert_eq!(
|
||||
cookie(&h, "__Host-rmm_oidc_binding"),
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn access_scopes_are_not_browser_approval_authority() {
|
||||
let p = Principal {
|
||||
tenant: Uuid::nil(),
|
||||
name: "test".into(),
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: Some(BTreeSet::from(["inventory:read".into()])),
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![],
|
||||
};
|
||||
assert!(p.permits_scope("inventory:read"));
|
||||
assert!(!p.permits_scope("plans:approve"));
|
||||
assert!(p.session_hash.is_none());
|
||||
assert_eq!(p.approval_origin(), "human_webui");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user