Enforce customer boundaries on token administration and finalize fleet navigation

This commit is contained in:
2026-11-17 22:05:44 +01:00
parent 0afaca1d64
commit 312da6f39e
25 changed files with 1207 additions and 208 deletions
+128
View File
@@ -403,6 +403,134 @@ mod tests {
assert!(LocalAuth::parse(&serde_json::to_vec(&duplicate).unwrap()).is_err());
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL with current migrations"]
async fn restricted_token_rejects_foreign_detail_and_plan_routes() {
use axum::{Router, middleware, routing::get};
use serde_json::Value;
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await
.unwrap();
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.acquire_timeout(std::time::Duration::from_secs(3))
.connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await
.unwrap();
let a = Uuid::parse_str(rmm_domain::TENANT_A).unwrap();
let b = Uuid::parse_str(rmm_domain::TENANT_B).unwrap();
let issuer = format!("local:{}", Uuid::new_v4());
let id = Uuid::new_v4();
let asset = Uuid::new_v4();
let token = format!("rmm_mcp_{}", "A".repeat(43));
let scopes = vec!["inventory:read", "operations:plan", "operations:read"];
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',$3)")
.bind(a).bind(&issuer).bind([scopes.as_slice(), &["tokens:manage"]].concat())
.execute(&admin).await.unwrap();
let mut tx = rmm_persistence::tenant_tx(&pool, a).await.unwrap();
sqlx::query("SELECT issue_customer_token($1,$2,'Restricted HTTP fixture',$3,$4,now()+interval '1 hour',false,$5)")
.bind(&issuer).bind(id).bind(hash(token.as_bytes())).bind(&scopes).bind(vec![a]).execute(&mut *tx).await.unwrap();
tx.commit().await.unwrap();
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(b)
.bind(asset)
.execute(&admin)
.await
.unwrap();
let fingerprint = hash(asset.as_bytes());
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,last_contact_at,last_authenticated_certificate_sha256,last_authenticated_at) VALUES($1,$2,$3,$4,now(),$4,now())")
.bind(b).bind(Uuid::new_v4()).bind(asset).bind(fingerprint).execute(&admin).await.unwrap();
let mut config = sample(&issuer, a, &hex::encode([1; 64]));
let mut auth = crate::auth::Auth::from_env("development").await.unwrap();
auth.local = Some(configured(&config));
let key_dir = std::env::temp_dir().join(id.to_string());
let state = crate::State {
pool: pool.clone(),
signer: None,
viewer_a: [0; 32],
viewer_b: [1; 32],
auth: Arc::new(auth),
job_signer: Arc::new(
crate::job_signer::JobSigner::load_or_create(&key_dir.join("http-test.key"))
.unwrap(),
),
};
let router = crate::jobs::routes(
Router::new()
.route("/api/v1/tenants", get(crate::api::tenants))
.route(
"/api/v1/tenants/{tenant}/devices/{asset}",
get(crate::devices::detail),
),
)
.layer(middleware::from_fn(crate::auth::context))
.with_state(state.clone());
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await
.unwrap();
let base = format!("http://{}/api/v1/tenants", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(5))
.build()
.unwrap();
let response = client.get(&base).bearer_auth(&token).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let directory = response.json::<Value>().await.unwrap();
assert_eq!(directory["items"].as_array().unwrap().len(), 1);
assert_eq!(directory["items"][0]["tenant_id"], a.to_string());
let now = Utc::now();
let forbidden_plan = json!({"tenant_id":b,"action":"refresh_inventory","targets":{"asset_ids":[asset]},
"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"scope":"base"},
"schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(5),"offline_policy":"wait_until_deadline"},
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
for request in [
client.get(format!("{base}/{b}/devices/{asset}")),
client
.post(format!("{base}/{b}/operation-plans"))
.json(&forbidden_plan),
] {
let denied = request
.bearer_auth(&token)
.header("x-rmm-tenant", a.to_string())
.send()
.await
.unwrap();
assert_eq!(denied.status(), StatusCode::NOT_FOUND);
}
let member = format!("mcp:{id}");
let created: i64 = sqlx::query_scalar(
"SELECT count(*) FROM operation_plans WHERE tenant_id=$1 AND principal=$2",
)
.bind(b)
.bind(&member)
.fetch_one(&admin)
.await
.unwrap();
assert_eq!(created, 0);
server.abort();
config["users"][0]["disabled"] = json!(true);
let mut disabled = crate::auth::Auth::from_env("development").await.unwrap();
disabled.local = Some(configured(&config));
let suspended = crate::State {
auth: Arc::new(disabled),
..state
};
assert!(matches!(
crate::mcp_tokens::authenticate(&suspended, &token, None).await,
Err(StatusCode::UNAUTHORIZED)
));
let mut tx = rmm_persistence::tenant_tx(&pool, a).await.unwrap();
assert!(
!crate::jobs::requester_enabled(&suspended, &mut tx, &member, a)
.await
.unwrap()
);
tx.commit().await.unwrap();
std::fs::remove_dir_all(key_dir).unwrap();
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL with current migrations"]
async fn local_password_totp_database() {
+11 -5
View File
@@ -122,8 +122,10 @@ async fn list(
) -> Result<Response, Error> {
let (principal, allowed, mut tx) = administration(&state, &headers, tenant, false).await?;
let rows = sqlx::query(&format!(
"SELECT {COLUMNS} FROM mcp_tokens ORDER BY created_at DESC,token_id"
"SELECT {COLUMNS} FROM mcp_tokens WHERE can_manage_mcp_token($1,token_id,$2) ORDER BY created_at DESC,token_id"
))
.bind(&principal.name)
.bind(&principal.tenants)
.fetch_all(&mut *tx)
.await?;
let can_select_all = crate::customers::can_manage(&principal, &mut tx).await?;
@@ -267,10 +269,11 @@ async fn revoke(
Path((tenant, id)): Path<(Uuid, Uuid)>,
) -> Result<Response, Error> {
let (principal, _, mut tx) = administration(&state, &headers, tenant, true).await?;
let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3)")
let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)")
.bind(&principal.name)
.bind(id)
.bind(Uuid::new_v4())
.bind(&principal.tenants)
.fetch_one(&mut *tx)
.await?;
if !found {
@@ -401,7 +404,8 @@ pub async fn issuer_enabled(
}))
}
pub async fn enabled_in(
#[cfg(test)]
async fn enabled_in(
tx: &mut Transaction<'_, Postgres>,
principal: &str,
) -> Result<bool, sqlx::Error> {
@@ -411,7 +415,8 @@ pub async fn enabled_in(
.await
}
pub async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
#[cfg(test)]
async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
let Ok(mut tx) = rmm_persistence::tenant_tx(pool, tenant).await else {
return false;
};
@@ -605,10 +610,11 @@ mod tests {
let (revoked_id, revoked) = mint(&app, tenant, &actor, &["inventory:read"]).await;
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3)")
let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)")
.bind(&actor)
.bind(revoked_id)
.bind(Uuid::new_v4())
.bind(vec![tenant])
.fetch_one(&mut *tx)
.await
.unwrap();