Skip to content

Commit 3231897

Browse files
authored
feat(audit): name created and updated resources and record no-op mutations (#5611)
Mutation records for creates, updates, and lifecycle changes named no resource, so an operator could not tell which sandbox was started, which template was created, or which workspace member was added. A provider attach that was already in place, a replayed request_id, and a profile import that failed validation all looked like ordinary successful changes. Hook the create, update, and lifecycle RPCs for sandboxes, templates, services, provider attachments, provider profiles, workspaces, and rootfs staging to record the workspace and the requested resources before the call starts, completed with the name and ID of each resource the gateway produced. Record no_op:unchanged and no_op:already_absent for attach and detach calls that changed nothing, no_op:replayed for answers served from a stored request_id result, and rejected:invalid_argument for provider profile imports and updates that failed validation, including their replays. A record lists at most 16 resources and counts the rest. Refs #2911 Signed-off-by: Kris Hicks <khicks@nvidia.com>
1 parent 624acee commit 3231897

6 files changed

Lines changed: 1020 additions & 117 deletions

File tree

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

Lines changed: 81 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use tonic::{Code, Status};
2222

2323
use super::identity::IdentityProvider;
2424
use super::principal::{Principal, SandboxIdentitySource};
25+
use crate::grpc::mutation_replay::REPLAYED_HEADER;
2526

2627
pub mod catalog;
2728
#[cfg(test)]
@@ -397,7 +398,16 @@ impl RequestContext {
397398
#[derive(Debug, Default)]
398399
struct Mutation {
399400
resources: Vec<ResourceDetails>,
400-
outcome: Option<&'static str>,
401+
outcome: Option<Outcome>,
402+
}
403+
404+
/// How a call that returned OK ended, when its response alone does not say.
405+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406+
pub enum Outcome {
407+
/// A success detail, such as `no_op:already_absent`.
408+
Detail(&'static str),
409+
/// The gateway refused the request in its response body.
410+
Rejected(Code),
401411
}
402412

403413
/// Record that the current request's change acts on `resource`.
@@ -412,9 +422,9 @@ pub fn amend_targets(amend: impl FnOnce(&mut Vec<ResourceDetails>)) {
412422
let _ = REQUEST.try_with(|request| amend(&mut lock(&request.mutation).resources));
413423
}
414424

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) {
425+
/// Record how the current request's change ended when its response alone
426+
/// does not say.
427+
pub fn record_outcome(outcome: Outcome) {
418428
let _ = REQUEST.try_with(|request| lock(&request.mutation).outcome = Some(outcome));
419429
}
420430

@@ -464,7 +474,19 @@ where
464474
recorded: false,
465475
};
466476
match REQUEST.scope(request, handler).await {
467-
Ok(response) => Ok(pending.follow(response)),
477+
Ok(response) => {
478+
if response
479+
.headers()
480+
.get(REPLAYED_HEADER)
481+
.is_some_and(|value| value == "true")
482+
{
483+
let mut mutation = lock(&pending.request.mutation);
484+
if !matches!(mutation.outcome, Some(Outcome::Rejected(_))) {
485+
mutation.outcome = Some(Outcome::Detail("no_op:replayed"));
486+
}
487+
}
488+
Ok(pending.follow(response))
489+
}
468490
Err(error) => {
469491
pending.record(Some(Code::Unknown));
470492
Err(error)
@@ -677,15 +699,15 @@ impl AuthzDenial<'_> {
677699
}
678700
}
679701

680-
/// Longest request-supplied identifier recorded on an event.
681-
const MAX_REQUESTED_ID_LEN: usize = 128;
702+
/// Longest identifier recorded on an event.
703+
const MAX_ID_LEN: usize = 128;
682704

683-
/// Cap a request-supplied identifier so a caller cannot inflate events.
705+
/// Cap an identifier so a caller cannot inflate events.
684706
fn bounded(value: &str) -> String {
685-
if value.len() <= MAX_REQUESTED_ID_LEN {
707+
if value.len() <= MAX_ID_LEN {
686708
return value.to_string();
687709
}
688-
let mut end = MAX_REQUESTED_ID_LEN;
710+
let mut end = MAX_ID_LEN;
689711
while !value.is_char_boundary(end) {
690712
end -= 1;
691713
}
@@ -848,42 +870,67 @@ fn api_activity<'a>(
848870
builder
849871
}
850872

873+
/// Most resources one mutation record lists.
874+
const MAX_RECORDED_RESOURCES: usize = 16;
875+
851876
/// Emit the record of a mutation that ended with `code`, or that never
852877
/// finished when `code` is `None`.
853878
fn emit_mutation(request: &RequestContext, principal: &Principal, code: Option<Code>) {
854879
let RequestContext { path, origin, .. } = request;
855880
let mutation = std::mem::take(&mut *lock(&request.mutation));
856881
let ctx = crate::gateway_ocsf::context("", "");
857882
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) {
862-
None => builder
863-
.severity(SeverityId::Medium)
864-
.status(StatusId::Unknown)
865-
.message("mutation did not finish")
866-
.status_detail("unknown:cancelled"),
867-
Some(None) => {
868-
builder = builder
869-
.severity(SeverityId::Informational)
870-
.status(StatusId::Success)
871-
.message("mutation succeeded");
883+
let omitted = mutation
884+
.resources
885+
.len()
886+
.saturating_sub(MAX_RECORDED_RESOURCES);
887+
for resource in mutation.resources.into_iter().take(MAX_RECORDED_RESOURCES) {
888+
builder = builder.resource(ResourceDetails {
889+
name: resource.name.as_deref().map(bounded),
890+
uid: resource.uid.as_deref().map(bounded),
891+
..resource
892+
});
893+
}
894+
let code = code.map(|code| match mutation.outcome {
895+
Some(Outcome::Rejected(rejected)) if code == Code::Ok => rejected,
896+
_ => code,
897+
});
898+
let (severity, status, message, detail) = match code.map(failure) {
899+
None => (
900+
SeverityId::Medium,
901+
StatusId::Unknown,
902+
"mutation did not finish".to_string(),
903+
Some("unknown:cancelled".to_string()),
904+
),
905+
Some(None) => (
906+
SeverityId::Informational,
907+
StatusId::Success,
908+
"mutation succeeded".to_string(),
872909
match mutation.outcome {
873-
Some(outcome) => builder.status_detail(outcome),
874-
None => builder,
875-
}
876-
}
877-
Some(Some(failure)) => builder
878-
.severity(if failure.starts_with("rejected:") {
910+
Some(Outcome::Detail(detail)) => Some(detail.to_string()),
911+
_ => None,
912+
},
913+
),
914+
Some(Some(failure)) => (
915+
if failure.starts_with("rejected:") {
879916
SeverityId::Low
880917
} else {
881918
SeverityId::Medium
882-
})
883-
.status(StatusId::Failure)
884-
.message(format!("mutation failed: {failure}"))
885-
.status_detail(failure),
919+
},
920+
StatusId::Failure,
921+
format!("mutation failed: {failure}"),
922+
Some(failure),
923+
),
924+
};
925+
let message = if omitted == 0 {
926+
message
927+
} else {
928+
format!("{message}; {omitted} more resources not listed")
886929
};
930+
builder = builder.severity(severity).status(status).message(message);
931+
if let Some(detail) = detail {
932+
builder = builder.status_detail(detail);
933+
}
887934
if let Some(request_id) = &origin.request_id {
888935
builder = builder.correlation_uid(request_id);
889936
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,11 @@ where
5858
let routed = async {
5959
let output = call.await;
6060
let response = match &output {
61-
Ok(_) => http::Response::new(tonic::body::Body::empty()),
61+
Ok(response) => {
62+
let mut http = http::Response::new(tonic::body::Body::empty());
63+
*http.headers_mut() = response.metadata().clone().into_headers();
64+
http
65+
}
6266
Err(status) => status.clone().into_http(),
6367
};
6468
result = Some(output);

0 commit comments

Comments
 (0)