Skip to content

Commit cb85c09

Browse files
authored
feat(audit): name deleted resources and record no-op deletes (#5609)
A gateway mutation record named the method and outcome of a delete but not what it deleted, and a delete of a resource that was already gone looked the same as one that removed it. Delete records now list the selected workspace and the requested resource by name, with the sandbox ID once a sandbox delete is accepted. A delete that found nothing to remove records status_detail no_op:already_absent, and an asynchronous sandbox delete records accepted. Rejected, cancelled, and handler-denied deletes still name the requested resource. Refs #2911 Signed-off-by: Kris Hicks <khicks@nvidia.com>
1 parent d989d61 commit cb85c09

5 files changed

Lines changed: 699 additions & 26 deletions

File tree

‎crates/openshell-server/src/auth/audit.rs‎

Lines changed: 79 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ struct RequestContext {
378378
origin: RequestOrigin,
379379
/// Set once a handler has emitted the request's authorization denial.
380380
denied: Arc<AtomicBool>,
381+
mutation: Arc<Mutex<Mutation>>,
381382
}
382383

383384
impl RequestContext {
@@ -386,10 +387,46 @@ impl RequestContext {
386387
path,
387388
origin,
388389
denied: Arc::default(),
390+
mutation: Arc::default(),
389391
}
390392
}
391393
}
392394

395+
/// What a state-changing request acted on and, when it succeeded without a
396+
/// plain change, how it ended.
397+
#[derive(Debug, Default)]
398+
struct Mutation {
399+
resources: Vec<ResourceDetails>,
400+
outcome: Option<&'static str>,
401+
}
402+
403+
/// Record that the current request's change acts on `resource`.
404+
pub fn record_target(resource: ResourceDetails) {
405+
let _ = REQUEST.try_with(|request| {
406+
lock(&request.mutation).resources.push(resource);
407+
});
408+
}
409+
410+
/// Change the resources recorded for the current request.
411+
pub fn amend_targets(amend: impl FnOnce(&mut Vec<ResourceDetails>)) {
412+
let _ = REQUEST.try_with(|request| amend(&mut lock(&request.mutation).resources));
413+
}
414+
415+
/// Record how the current request's change ended when it succeeded without
416+
/// a plain change, such as `no_op:already_absent`.
417+
pub fn record_outcome(outcome: &'static str) {
418+
let _ = REQUEST.try_with(|request| lock(&request.mutation).outcome = Some(outcome));
419+
}
420+
421+
/// A resource of `type_label` named by the caller, bounded in length.
422+
pub fn requested(type_label: &str, name: &str) -> ResourceDetails {
423+
ResourceDetails::named(type_label, bounded(name))
424+
}
425+
426+
fn lock(mutation: &Mutex<Mutation>) -> std::sync::MutexGuard<'_, Mutation> {
427+
mutation.lock().unwrap_or_else(PoisonError::into_inner)
428+
}
429+
393430
/// Run a request handler so the authorization denials it raises are
394431
/// recorded against `path` and `origin`.
395432
///
@@ -474,12 +511,7 @@ impl PendingMutation {
474511
if !std::mem::replace(&mut self.recorded, true)
475512
&& !self.request.denied.load(Ordering::Relaxed)
476513
{
477-
emit_mutation(
478-
&self.request.path,
479-
&self.request.origin,
480-
&self.principal,
481-
code,
482-
);
514+
emit_mutation(&self.request, &self.principal, code);
483515
}
484516
}
485517
}
@@ -674,11 +706,17 @@ fn principal_user(principal: &Principal) -> User {
674706
}
675707
}
676708

677-
/// Emit an authorization denial raised by a handler for the current request.
709+
/// Emit an authorization denial raised by a handler for the current request,
710+
/// naming the targets the request recorded.
678711
pub fn emit_authorization_denial(principal: &Principal, denial: AuthzDenial<'_>) {
679712
let (path, origin) = current_request();
680-
let _ = REQUEST.try_with(|request| request.denied.store(true, Ordering::Relaxed));
681-
emit_authorization_denial_for(&path, &origin, principal, denial);
713+
let targets = REQUEST
714+
.try_with(|request| {
715+
request.denied.store(true, Ordering::Relaxed);
716+
lock(&request.mutation).resources.clone()
717+
})
718+
.unwrap_or_default();
719+
emit_denial(&path, &origin, principal, denial, targets);
682720
}
683721

684722
/// Emit an authorization denial raised by a handler for the current request,
@@ -695,6 +733,16 @@ pub fn emit_authorization_denial_for(
695733
origin: &RequestOrigin,
696734
principal: &Principal,
697735
denial: AuthzDenial<'_>,
736+
) {
737+
emit_denial(path, origin, principal, denial, Vec::new());
738+
}
739+
740+
fn emit_denial(
741+
path: &str,
742+
origin: &RequestOrigin,
743+
principal: &Principal,
744+
denial: AuthzDenial<'_>,
745+
mut resources: Vec<ResourceDetails>,
698746
) {
699747
let ctx = crate::gateway_ocsf::context("", "");
700748
let category = denial.category();
@@ -712,7 +760,10 @@ pub fn emit_authorization_denial_for(
712760
.status(StatusId::Failure)
713761
.status_detail(category)
714762
.message(format!("authorization denied: {category}"));
715-
if let Some(resource) = denial.resource() {
763+
if let Some(resource) = denial.resource().filter(|r| !resources.contains(r)) {
764+
resources.push(resource);
765+
}
766+
for resource in resources {
716767
builder = builder.resource(resource);
717768
}
718769
if let Some(uid) = &correlation_uid {
@@ -799,19 +850,30 @@ fn api_activity<'a>(
799850

800851
/// Emit the record of a mutation that ended with `code`, or that never
801852
/// finished when `code` is `None`.
802-
fn emit_mutation(path: &str, origin: &RequestOrigin, principal: &Principal, code: Option<Code>) {
853+
fn emit_mutation(request: &RequestContext, principal: &Principal, code: Option<Code>) {
854+
let RequestContext { path, origin, .. } = request;
855+
let mutation = std::mem::take(&mut *lock(&request.mutation));
803856
let ctx = crate::gateway_ocsf::context("", "");
804-
let builder = api_activity(&ctx, path, origin, principal);
805-
let mut builder = match code.map(failure) {
857+
let mut builder = api_activity(&ctx, path, origin, principal);
858+
for resource in mutation.resources {
859+
builder = builder.resource(resource);
860+
}
861+
builder = match code.map(failure) {
806862
None => builder
807863
.severity(SeverityId::Medium)
808864
.status(StatusId::Unknown)
809865
.message("mutation did not finish")
810866
.status_detail("unknown:cancelled"),
811-
Some(None) => builder
812-
.severity(SeverityId::Informational)
813-
.status(StatusId::Success)
814-
.message("mutation succeeded"),
867+
Some(None) => {
868+
builder = builder
869+
.severity(SeverityId::Informational)
870+
.status(StatusId::Success)
871+
.message("mutation succeeded");
872+
match mutation.outcome {
873+
Some(outcome) => builder.status_detail(outcome),
874+
None => builder,
875+
}
876+
}
815877
Some(Some(failure)) => builder
816878
.severity(if failure.starts_with("rejected:") {
817879
SeverityId::Low

‎crates/openshell-server/src/auth/audit/test_support.rs‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
//! Fixtures for tests that assert on gateway audit events.
55
66
use super::{ConnectionSource, RequestOrigin};
7+
use crate::auth::principal::Principal;
78
use openshell_ocsf::test_support::OcsfCapture;
89
use serde_json::Value;
910
use std::future::Future;
@@ -40,6 +41,65 @@ pub async fn audited<F: Future>(path: &str, handler: F) -> (F::Output, Vec<Value
4041
(output, capture.json_events())
4142
}
4243

44+
/// Run a gateway service `call` as a routed request to `path` by
45+
/// `principal`, returning its result and the mutation records it produced.
46+
pub async fn audited_mutation<T, F>(
47+
path: &str,
48+
principal: &Principal,
49+
call: F,
50+
) -> (Result<tonic::Response<T>, tonic::Status>, Vec<Value>)
51+
where
52+
F: Future<Output = Result<tonic::Response<T>, tonic::Status>>,
53+
{
54+
let capture = OcsfCapture::default();
55+
let mut result = None;
56+
{
57+
let _guard = capture.install();
58+
let routed = async {
59+
let output = call.await;
60+
let response = match &output {
61+
Ok(_) => http::Response::new(tonic::body::Body::empty()),
62+
Err(status) => status.clone().into_http(),
63+
};
64+
result = Some(output);
65+
Ok::<_, std::convert::Infallible>(response)
66+
};
67+
let _ = super::with_audited_request(path.to_string(), origin(), principal, routed).await;
68+
}
69+
let events = capture
70+
.json_events()
71+
.into_iter()
72+
.filter(|event| event["class_uid"] == 6003)
73+
.collect();
74+
(result.expect("call completed"), events)
75+
}
76+
77+
/// Start a gateway service `call` as a routed request to `path` by
78+
/// `principal`, drop it before it finishes, and return the mutation records
79+
/// it produced.
80+
pub async fn cancelled_mutation<T, F>(path: &str, principal: &Principal, call: F) -> Vec<Value>
81+
where
82+
F: Future<Output = Result<tonic::Response<T>, tonic::Status>>,
83+
{
84+
let capture = OcsfCapture::default();
85+
{
86+
let _guard = capture.install();
87+
let routed = async {
88+
let _ = call.await;
89+
Ok::<_, std::convert::Infallible>(http::Response::new(tonic::body::Body::empty()))
90+
};
91+
let routed = super::with_audited_request(path.to_string(), origin(), principal, routed);
92+
tokio::time::timeout(std::time::Duration::from_millis(10), routed)
93+
.await
94+
.expect_err("call finished");
95+
}
96+
capture
97+
.json_events()
98+
.into_iter()
99+
.filter(|event| event["class_uid"] == 6003)
100+
.collect()
101+
}
102+
43103
/// Assert that `event` records the request from [`origin`].
44104
pub fn assert_origin(event: &Value) {
45105
assert_eq!(event["src_endpoint"]["ip"], PEER_IP, "{event}");

‎crates/openshell-server/src/grpc/mod.rs‎

Lines changed: 75 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
//! gRPC service implementation.
55
66
mod auth_rpc;
7+
mod mutation_audit;
78
pub mod mutation_replay;
89
pub mod policy;
910
pub mod provider;
@@ -395,7 +396,14 @@ impl OpenShell for OpenShellService {
395396
&self,
396397
request: Request<DeleteSandboxTemplateRequest>,
397398
) -> Result<Response<DeleteSandboxTemplateResponse>, Status> {
398-
mutation_replay::run(&self.state, request).await
399+
let targets = {
400+
let request = request.get_ref();
401+
mutation_audit::scoped(
402+
request.workspace_scope.as_ref(),
403+
[mutation_audit::requested("sandbox_template", &request.name)],
404+
)
405+
};
406+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
399407
}
400408

401409
async fn list_sandbox_providers(
@@ -437,7 +445,14 @@ impl OpenShell for OpenShellService {
437445
&self,
438446
request: Request<DeleteSandboxRequest>,
439447
) -> Result<Response<DeleteSandboxResponse>, Status> {
440-
mutation_replay::run(&self.state, request).await
448+
let targets = {
449+
let request = request.get_ref();
450+
mutation_audit::scoped(
451+
request.workspace_scope.as_ref(),
452+
[mutation_audit::requested("sandbox", &request.name)],
453+
)
454+
};
455+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
441456
}
442457

443458
async fn stop_sandbox(
@@ -532,7 +547,21 @@ impl OpenShell for OpenShellService {
532547
&self,
533548
request: Request<DeleteServiceRequest>,
534549
) -> Result<Response<DeleteServiceResponse>, Status> {
535-
mutation_replay::run(&self.state, request).await
550+
let targets = {
551+
let request = request.get_ref();
552+
mutation_audit::scoped(
553+
request.workspace_scope.as_ref(),
554+
[
555+
mutation_audit::requested("sandbox", &request.sandbox),
556+
mutation_audit::requested("service", &request.name),
557+
],
558+
)
559+
};
560+
mutation_audit::deletion(
561+
targets,
562+
Box::pin(mutation_replay::run(&self.state, request)),
563+
)
564+
.await
536565
}
537566

538567
async fn revoke_ssh_session(
@@ -639,21 +668,45 @@ impl OpenShell for OpenShellService {
639668
&self,
640669
request: Request<DeleteProviderRefreshRequest>,
641670
) -> Result<Response<DeleteProviderRefreshResponse>, Status> {
642-
mutation_replay::run(&self.state, request).await
671+
let targets = {
672+
let request = request.get_ref();
673+
mutation_audit::scoped(
674+
request.workspace_scope.as_ref(),
675+
[
676+
mutation_audit::requested("provider", &request.provider),
677+
mutation_audit::requested("provider_credential", &request.credential_key),
678+
],
679+
)
680+
};
681+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
643682
}
644683

645684
async fn delete_provider(
646685
&self,
647686
request: Request<DeleteProviderRequest>,
648687
) -> Result<Response<DeleteProviderResponse>, Status> {
649-
mutation_replay::run(&self.state, request).await
688+
let targets = {
689+
let request = request.get_ref();
690+
mutation_audit::scoped(
691+
request.workspace_scope.as_ref(),
692+
[mutation_audit::requested("provider", &request.name)],
693+
)
694+
};
695+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
650696
}
651697

652698
async fn delete_provider_profile(
653699
&self,
654700
request: Request<DeleteProviderProfileRequest>,
655701
) -> Result<Response<DeleteProviderProfileResponse>, Status> {
656-
mutation_replay::run(&self.state, request).await
702+
let targets = {
703+
let request = request.get_ref();
704+
mutation_audit::scoped(
705+
request.workspace_scope.as_ref(),
706+
[mutation_audit::requested("provider_profile", &request.id)],
707+
)
708+
};
709+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
657710
}
658711

659712
// --- Config / Policy ---
@@ -892,7 +945,11 @@ impl OpenShell for OpenShellService {
892945
&self,
893946
request: Request<DeleteWorkspaceRequest>,
894947
) -> Result<Response<DeleteWorkspaceResponse>, Status> {
895-
mutation_replay::run(&self.state, request).await
948+
let targets = vec![mutation_audit::requested(
949+
"workspace",
950+
&request.get_ref().name,
951+
)];
952+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
896953
}
897954

898955
async fn add_workspace_member(
@@ -906,7 +963,17 @@ impl OpenShell for OpenShellService {
906963
&self,
907964
request: Request<RemoveWorkspaceMemberRequest>,
908965
) -> Result<Response<RemoveWorkspaceMemberResponse>, Status> {
909-
mutation_replay::run(&self.state, request).await
966+
let targets = {
967+
let request = request.get_ref();
968+
mutation_audit::scoped(
969+
request.workspace_scope.as_ref(),
970+
[mutation_audit::requested(
971+
"workspace_member",
972+
&request.principal_subject,
973+
)],
974+
)
975+
};
976+
mutation_audit::deletion(targets, mutation_replay::run(&self.state, request)).await
910977
}
911978

912979
async fn list_workspace_members(

0 commit comments

Comments
 (0)