Remove one retired device pairing and its owned history from the device detail
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
use crate::jobs::Error;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
routing::post,
|
||||
routing::{delete, post},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -25,6 +25,7 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/revocation",
|
||||
post(revoke_device),
|
||||
)
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
|
||||
post(archive_device),
|
||||
@@ -127,23 +128,53 @@ async fn archive_device(
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Pairing {
|
||||
agent_id: Uuid,
|
||||
}
|
||||
|
||||
async fn remove_device(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(pairing): Query<Pairing>,
|
||||
) -> Result<StatusCode, Error> {
|
||||
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", "device_deleted").await?;
|
||||
let status: String = sqlx::query_scalar("SELECT remove_revoked_device($1,$2,$3,$4)")
|
||||
.bind(tenant).bind(asset).bind(pairing.agent_id).bind(&p.name)
|
||||
.fetch_one(&mut *tx).await?;
|
||||
match status.as_str() {
|
||||
"deleted" => audit(&mut tx, &p, "device_deleted",
|
||||
json!({"asset_id":asset, "agent_id":pairing.agent_id})).await?,
|
||||
"absent" => (),
|
||||
"active" => return Err(Error(StatusCode::CONFLICT, "DEVICE_REVOCATION_REQUIRED")),
|
||||
"busy" => return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK")),
|
||||
"forbidden" => return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN")),
|
||||
_ => return Err(Error(StatusCode::INTERNAL_SERVER_ERROR, "DEVICE_DELETION_FAILED")),
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn revoke_device(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path((t, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(selection): Query<crate::devices::DetailQuery>,
|
||||
Json(i): Json<Reason>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let (p, mut tx) = context(&s, &h, t, "devices:revoke", &i.reason).await?;
|
||||
let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1").bind(asset).execute(&mut *tx).await?.rows_affected();
|
||||
let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2)").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?.rows_affected();
|
||||
if n == 0 {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2) AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?;
|
||||
audit(
|
||||
&mut tx,
|
||||
&p,
|
||||
"device_revoked",
|
||||
json!({"asset_id":asset,"reason":i.reason}),
|
||||
json!({"asset_id":asset,"agent_id":selection.agent_id,"reason":i.reason}),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -443,7 +443,8 @@ mod tests {
|
||||
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 password = "test pairing removal";
|
||||
let mut config = sample(&issuer, a, &hex::encode(derive_password(password.as_bytes(), &[7; 32]).unwrap()));
|
||||
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());
|
||||
@@ -458,14 +459,16 @@ mod tests {
|
||||
.unwrap(),
|
||||
),
|
||||
};
|
||||
let router = crate::jobs::routes(
|
||||
let router = crate::controls::routes(crate::jobs::routes(
|
||||
Router::new()
|
||||
.route("/api/v1/tenants", get(crate::api::tenants))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}",
|
||||
get(crate::devices::detail),
|
||||
),
|
||||
)
|
||||
))
|
||||
.route("/auth/local/login", axum::routing::post(crate::auth::local_login))
|
||||
.route("/auth/session", get(crate::auth::session))
|
||||
.layer(middleware::from_fn(crate::auth::context))
|
||||
.with_state(state.clone());
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
|
||||
@@ -489,6 +492,7 @@ mod tests {
|
||||
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
|
||||
for request in [
|
||||
client.get(format!("{base}/{b}/devices/{asset}")),
|
||||
client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")),
|
||||
client
|
||||
.post(format!("{base}/{b}/operation-plans"))
|
||||
.json(&forbidden_plan),
|
||||
@@ -511,6 +515,40 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(created, 0);
|
||||
let pair = format!("{base}/{a}/devices/{asset}?agent_id={id}");
|
||||
let same_customer = client.delete(&pair).bearer_auth(&token).send().await.unwrap();
|
||||
assert_eq!(same_customer.status(), StatusCode::FORBIDDEN);
|
||||
|
||||
let api = base.strip_suffix("/api/v1/tenants").unwrap();
|
||||
let origin = &state.auth.origin;
|
||||
let credentials = input(password, &configured(&config).users[0].secret);
|
||||
let logged_in = client.post(format!("{api}/auth/local/login")).header("origin", origin)
|
||||
.json(&json!({"username":credentials.username,"password":credentials.password,"totp_code":credentials.totp_code}))
|
||||
.send().await.unwrap().error_for_status().unwrap();
|
||||
let cookie = logged_in.headers()["set-cookie"].to_str().unwrap().split(';').next().unwrap();
|
||||
let session = client.get(format!("{api}/auth/session")).header("cookie", cookie)
|
||||
.send().await.unwrap().json::<Value>().await.unwrap();
|
||||
let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie);
|
||||
let csrf = session["csrf_token"].as_str().unwrap();
|
||||
assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(a).bind(&issuer).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(a).bind(asset).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)")
|
||||
.bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap();
|
||||
assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT);
|
||||
let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}"))
|
||||
.header("origin", origin).header("cookie",cookie).header("x-csrf-token",csrf)
|
||||
.json(&json!({"reason":"isolated retirement"})).send().await.unwrap();
|
||||
assert_eq!(revoked.status(), StatusCode::OK);
|
||||
for _ in 0..2 {
|
||||
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::NO_CONTENT);
|
||||
}
|
||||
let records: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1 AND event_type='device_deleted' AND data#>>'{decision,agent_id}'=$2")
|
||||
.bind(a).bind(id.to_string()).fetch_one(&admin).await.unwrap();
|
||||
assert_eq!(records, 1);
|
||||
server.abort();
|
||||
config["users"][0]["disabled"] = json!(true);
|
||||
let mut disabled = crate::auth::Auth::from_env("development").await.unwrap();
|
||||
|
||||
Reference in New Issue
Block a user