Order recent requests first and cover inbox authorization and pagination
This commit is contained in:
@@ -224,3 +224,6 @@ async fn list(s: &crate::State, p: &Principal, q: Filters) -> Result<Value, Erro
|
||||
"truncated":truncated,"completeness":if truncated{"partial"}else{"complete"}}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn inbox_count_cursor_history_and_customer_permissions() {
|
||||
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let a = Uuid::new_v4();
|
||||
let b = Uuid::new_v4();
|
||||
let c = Uuid::new_v4();
|
||||
let user = format!("fixture:{a}");
|
||||
let op = Uuid::new_v4();
|
||||
let plan = Uuid::new_v4();
|
||||
let agent = Uuid::new_v4();
|
||||
let stamp = Utc::now() - chrono::Duration::minutes(1);
|
||||
|
||||
for (tenant, name) in [(a, "Kunde A"), (b, "Kunde B"), (c, "Nur Leser")] {
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,$2)")
|
||||
.bind(tenant)
|
||||
.bind(name)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut permissions = vec!["operations:read"];
|
||||
if tenant != c {
|
||||
permissions.push("plans:approve");
|
||||
}
|
||||
if tenant == a {
|
||||
permissions.push("inventory:read");
|
||||
}
|
||||
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',$3)")
|
||||
.bind(tenant).bind(&user).bind(permissions).execute(&admin).await.unwrap();
|
||||
|
||||
// IDs can coincide across customers. A human-readable label may only
|
||||
// come from the customer's own authenticated membership and inventory.
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(tenant)
|
||||
.bind(agent)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$2,$3)")
|
||||
.bind(tenant).bind(agent).bind(rmm_domain::jobs::hash(tenant.as_bytes())).execute(&admin).await.unwrap();
|
||||
let snapshot = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256)
|
||||
VALUES($1,$2,$3,$3,1,now(),'linux.base','valid','partial',$3,$4,$5)")
|
||||
.bind(tenant).bind(agent).bind(snapshot).bind(json!({"hostname":name})).bind("0".repeat(64)).execute(&admin).await.unwrap();
|
||||
|
||||
for (i, status, expired) in [
|
||||
(0, "pending_approval", false),
|
||||
(1, "pending_approval", true),
|
||||
(2, "rejected", false),
|
||||
] {
|
||||
let (op_id, plan_id) = if i == 0 {
|
||||
(op, plan)
|
||||
} else {
|
||||
(Uuid::new_v4(), Uuid::new_v4())
|
||||
};
|
||||
let payload = json!({"jobs":[{"payload":{"asset_id":agent,"agent_id":agent,"action":{"action":"run_script"}}}],
|
||||
"reason":"Testauftrag","script_revision":{"revision_id":op,"name":"Kernelversion","version":3}});
|
||||
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at)
|
||||
VALUES($1,$2,'mcp:fixture',$3,'fixture',CASE WHEN $4 THEN now()-interval '1 hour' ELSE now()+interval '1 hour' END)")
|
||||
.bind(tenant).bind(plan_id).bind(serde_json::to_vec(&payload).unwrap()).bind(expired).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,created_at,approval_state)
|
||||
VALUES($1,$2,$3,'mcp:fixture',$4,'fixture',$5,$6)")
|
||||
.bind(tenant).bind(op_id).bind(plan_id).bind(plan_id.to_string()).bind(stamp).bind(status).execute(&admin).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("approvals-{a}"));
|
||||
let state = crate::State {
|
||||
pool,
|
||||
signer: None,
|
||||
viewer_a: [0; 32],
|
||||
viewer_b: [1; 32],
|
||||
auth: Arc::new(crate::auth::Auth::from_env("development").await.unwrap()),
|
||||
job_signer: Arc::new(
|
||||
crate::job_signer::JobSigner::load_or_create(&dir.join("inbox.key")).unwrap(),
|
||||
),
|
||||
};
|
||||
let mut p = Principal {
|
||||
tenant: a,
|
||||
tenants: vec![a, b, c],
|
||||
name: user.clone(),
|
||||
operator: true,
|
||||
session_hash: Some("session".into()),
|
||||
csrf: None,
|
||||
scopes: None,
|
||||
testsimulation: true,
|
||||
identity: None,
|
||||
};
|
||||
|
||||
let first = list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
limit: Some(1),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first["pending_count"], 2);
|
||||
assert_eq!(first["customers"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(first["can_review"], true);
|
||||
let cursor = first["next_cursor"].as_str().unwrap().to_owned();
|
||||
let second = list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
cursor: Some(cursor.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second["pending_count"], 2);
|
||||
assert!(second["next_cursor"].is_null());
|
||||
let rows = [&first["items"][0], &second["items"][0]];
|
||||
assert_ne!(rows[0]["tenant_id"], rows[1]["tenant_id"]);
|
||||
for row in rows {
|
||||
assert_eq!(row["operation_id"], json!(op));
|
||||
assert_eq!(row["title"], "Kernelversion");
|
||||
assert_eq!(row["script_revision"]["version"], 3);
|
||||
assert_eq!(row["action"], "run_script");
|
||||
assert_eq!(row["requester"], "mcp:fixture");
|
||||
assert_eq!(row["targets"][0]["asset_id"], json!(agent));
|
||||
if row["tenant_id"] == json!(a) {
|
||||
assert_eq!(row["targets"][0]["hostname"], "Kunde A");
|
||||
} else {
|
||||
assert!(row["targets"][0]["hostname"].is_null());
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
cursor: Some(cursor.clone()),
|
||||
status: Status::History,
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
let history = list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
tenant_id: Some(a),
|
||||
status: Status::History,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(history["pending_count"], 1);
|
||||
let states: Vec<_> = history["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|item| item["approval_state"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(states.len(), 2);
|
||||
assert!(states.contains(&"expired") && states.contains(&"rejected"));
|
||||
let count = list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
count_only: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count["pending_count"], 2);
|
||||
assert_eq!(count["items"], json!([]));
|
||||
assert_eq!(
|
||||
list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
tenant_id: Some(c),
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
assert_eq!(
|
||||
list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
tenant_id: Some(Uuid::new_v4()),
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET permissions=ARRAY['operations:read'] WHERE principal=$1 AND tenant_id=$2")
|
||||
.bind(&user).bind(b).execute(&admin).await.unwrap();
|
||||
assert_eq!(
|
||||
list(
|
||||
&state,
|
||||
&p,
|
||||
Filters {
|
||||
cursor: Some(cursor),
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
p.tenants = vec![c];
|
||||
p.tenant = c;
|
||||
let none = list(&state, &p, Filters::default()).await.unwrap();
|
||||
assert_eq!(none["pending_count"], 0);
|
||||
assert_eq!(none["items"], json!([]));
|
||||
assert_eq!(none["can_review"], false);
|
||||
p.session_hash = None;
|
||||
assert_eq!(
|
||||
list(&state, &p, Filters::default()).await.unwrap_err().0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -1339,31 +1339,61 @@ async fn cancel_http(
|
||||
let p = principal(&s, &h, true).await?;
|
||||
Ok(Json(cancel(&s, &p, t, id, i).await?))
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum OrderSort {
|
||||
Recent,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OrderListQuery {
|
||||
sort: Option<OrderSort>,
|
||||
cursor: Option<String>,
|
||||
limit: Option<u16>,
|
||||
}
|
||||
|
||||
async fn operations_http(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
axum::extract::Query(query): axum::extract::Query<crate::pagination::PageQuery>,
|
||||
axum::extract::Query(query): axum::extract::Query<OrderListQuery>,
|
||||
) -> Result<Json<Value>> {
|
||||
let p = principal(&s, &h, false).await?;
|
||||
scope(&p, t, false)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "operations:read").await?;
|
||||
let mut page = crate::pagination::Cursor::parse(&s, &p, "operations:operation_id:asc", query)
|
||||
.map_err(|status| Error(status, "VALIDATION_ERROR"))?;
|
||||
let ids:Vec<Uuid>=sqlx::query_scalar("SELECT operation_id FROM approval_requests WHERE operation_id>$1 AND created_at<=$2 ORDER BY operation_id LIMIT $3").bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
||||
let recent = matches!(query.sort, Some(OrderSort::Recent));
|
||||
let ordering = if recent { "operations:created_at:desc" } else { "operations:operation_id:asc" };
|
||||
let mut page = crate::pagination::Cursor::parse(&s, &p, ordering, crate::pagination::PageQuery {
|
||||
cursor: query.cursor, limit: query.limit,
|
||||
}).map_err(|status| Error(status, "VALIDATION_ERROR"))?;
|
||||
let limit = i64::from(page.limit) + 1;
|
||||
let ids: Vec<(Uuid, DateTime<Utc>)> = if recent {
|
||||
sqlx::query_as("SELECT operation_id,created_at FROM approval_requests WHERE created_at<=$1
|
||||
AND ($2::timestamptz IS NULL OR (created_at,operation_id)<($2,$3))
|
||||
ORDER BY created_at DESC,operation_id DESC LIMIT $4")
|
||||
.bind(page.as_of).bind(page.last_created_at).bind(page.last).bind(limit)
|
||||
.fetch_all(&mut *tx).await?
|
||||
} else {
|
||||
sqlx::query_as("SELECT operation_id,created_at FROM approval_requests WHERE operation_id>$1 AND created_at<=$2
|
||||
ORDER BY operation_id LIMIT $3")
|
||||
.bind(page.last).bind(page.as_of).bind(limit).fetch_all(&mut *tx).await?
|
||||
};
|
||||
tx.commit().await?;
|
||||
let truncated = ids.len() > usize::from(page.limit);
|
||||
let next = if truncated {
|
||||
let (id, date) = ids[usize::from(page.limit) - 1];
|
||||
page.last_created_at = recent.then_some(date);
|
||||
Some(
|
||||
page.next(&s, ids[usize::from(page.limit) - 1])
|
||||
page.next(&s, id)
|
||||
.map_err(|status| Error(status, "VALIDATION_ERROR"))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut items = Vec::new();
|
||||
for id in ids.into_iter().take(usize::from(page.limit)) {
|
||||
for (id, _) in ids.into_iter().take(usize::from(page.limit)) {
|
||||
items.push(operation(&s, &p, t, id).await?)
|
||||
}
|
||||
Ok(Json(
|
||||
|
||||
Reference in New Issue
Block a user