feat(audit): record project assignments in the workspace audit log (#428)
This commit is contained in:
1 parent
202f5ea325
commit
48fbdaee40
4 files changed
+181
-19
No files matched your search
@@ -322,17 +322,18 @@ pub async fn update_target(
|
||||
);
|
||||
}
|
||||
// Both merge with what is stored, so the stored target is read once.
|
||||
let stored = if req.scan_config.is_some() || req.artifacts.is_some() {
|
||||
Some(
|
||||
db.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let stored =
|
||||
if req.scan_config.is_some() || req.artifacts.is_some() || req.project_ids.is_some() {
|
||||
Some(
|
||||
db.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let credential_error = |e: SecretError| {
|
||||
tracing::error!("storing a credential: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
@@ -355,9 +356,18 @@ pub async fn update_target(
|
||||
if let Some(ss) = req.scan_schedule {
|
||||
set.insert("scan_schedule", ss);
|
||||
}
|
||||
if let Some(requested) = req.project_ids {
|
||||
// Written to the audit log once the change is stored.
|
||||
let mut projects_audit = None;
|
||||
if let (Some(requested), Some(stored)) = (req.project_ids, stored.as_ref()) {
|
||||
let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?;
|
||||
let ids = super::projects::validated_project_ids(&requested, &known)?;
|
||||
projects_audit = super::projects::projects_changed_entry(
|
||||
&tenant.0,
|
||||
(&id, &stored.name),
|
||||
&stored.project_ids,
|
||||
&ids,
|
||||
&known,
|
||||
);
|
||||
set.insert("project_ids", ids);
|
||||
}
|
||||
if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) {
|
||||
@@ -373,6 +383,15 @@ pub async fn update_target(
|
||||
.update_one(doc! { "_id": oid }, doc! { "$set": set })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
// Background and best-effort: the registry being down never fails the
|
||||
// change itself.
|
||||
if let (Some(entry), Some(registry)) = (projects_audit, agent.registry.clone()) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = registry.append_audit(&entry).await {
|
||||
tracing::warn!(target_id = %entry.target_id, "project change not audited: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
@@ -66,6 +66,46 @@ pub fn known_project_ids(ids: &[String], known: &[Project]) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The audit entry for a change of target `target_id`'s projects from
|
||||
/// `before` to `after`, naming each project from `known` (a deleted one with
|
||||
/// an empty name). `None` when nothing changed.
|
||||
pub fn projects_changed_entry(
|
||||
ctx: &compliance_core::TenantContext,
|
||||
(target_id, target_name): (&str, &str),
|
||||
before: &[String],
|
||||
after: &[String],
|
||||
known: &[Project],
|
||||
) -> Option<crate::registry::AuditEntry> {
|
||||
let named = |id: &String| {
|
||||
let name = known
|
||||
.iter()
|
||||
.find(|p| &p.id == id)
|
||||
.map_or("", |p| p.name.as_str());
|
||||
serde_json::json!({ "id": id, "name": name })
|
||||
};
|
||||
let added: Vec<_> = after
|
||||
.iter()
|
||||
.filter(|id| !before.contains(id))
|
||||
.map(named)
|
||||
.collect();
|
||||
let removed: Vec<_> = before
|
||||
.iter()
|
||||
.filter(|id| !after.contains(id))
|
||||
.map(named)
|
||||
.collect();
|
||||
if added.is_empty() && removed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
crate::registry::AuditEntry::by(
|
||||
ctx,
|
||||
"target.projects_changed",
|
||||
serde_json::json!({ "added": added, "removed": removed }),
|
||||
)
|
||||
.about_target(target_id, target_name),
|
||||
)
|
||||
}
|
||||
|
||||
/// GET /api/v1/projects — the tenant's projects, for choosing and showing
|
||||
/// them in the dashboard.
|
||||
#[tracing::instrument(skip_all)]
|
||||
@@ -111,6 +151,69 @@ mod tests {
|
||||
assert_eq!(validated_project_ids(&[], &known), Ok(Vec::new()));
|
||||
}
|
||||
|
||||
fn ctx(staff: bool) -> compliance_core::TenantContext {
|
||||
compliance_core::TenantContext {
|
||||
tenant_id: "t-1".to_string(),
|
||||
tenant_slug: "faller".to_string(),
|
||||
org_roles: Vec::new(),
|
||||
products: Vec::new(),
|
||||
plan: String::new(),
|
||||
status: compliance_core::TenantStatus::Active,
|
||||
user_id: "u-1".to_string(),
|
||||
user_name: Some("Anna Faller".to_string()),
|
||||
staff: staff.then(|| compliance_core::StaffAccess {
|
||||
user_id: "u-1".to_string(),
|
||||
user_name: Some("Sharang".to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projects_change_is_audited_with_names() {
|
||||
let known = [project("p1"), project("p2")];
|
||||
let entry = projects_changed_entry(
|
||||
&ctx(false),
|
||||
("abc", "Lok-Steuerung"),
|
||||
&["p1".to_string(), "gone".to_string()],
|
||||
&["p1".to_string(), "p2".to_string()],
|
||||
&known,
|
||||
)
|
||||
.expect("a change");
|
||||
assert_eq!(entry.action, "target.projects_changed");
|
||||
assert_eq!(entry.actor_type, "user");
|
||||
assert_eq!(entry.actor_name, "Anna Faller");
|
||||
assert_eq!(
|
||||
(entry.target_type.as_str(), entry.target_id.as_str()),
|
||||
("target", "abc")
|
||||
);
|
||||
assert_eq!(entry.target_name, "Lok-Steuerung");
|
||||
assert_eq!(
|
||||
entry.metadata,
|
||||
serde_json::json!({
|
||||
"added": [{ "id": "p2", "name": "Projekt p2" }],
|
||||
"removed": [{ "id": "gone", "name": "" }]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_is_audited_as_staff_and_no_change_as_nothing() {
|
||||
let known = [project("p1")];
|
||||
let entry =
|
||||
projects_changed_entry(&ctx(true), ("abc", "x"), &[], &["p1".to_string()], &known)
|
||||
.expect("a change");
|
||||
assert_eq!(entry.actor_type, "staff");
|
||||
assert_eq!(entry.actor_name, "BreakPilot-Support (Sharang)");
|
||||
assert!(projects_changed_entry(
|
||||
&ctx(false),
|
||||
("abc", "x"),
|
||||
&["p1".to_string()],
|
||||
&["p1".to_string()],
|
||||
&known
|
||||
)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_projects_drop_out_on_read() {
|
||||
let known = [project("p1")];
|
||||
|
||||
@@ -210,13 +210,11 @@ fn support_audit_entry(
|
||||
path: &str,
|
||||
status: u16,
|
||||
) -> crate::registry::AuditEntry {
|
||||
crate::registry::AuditEntry {
|
||||
tenant_id: ctx.tenant_id.clone(),
|
||||
action: "pruefwerk.support_access".to_string(),
|
||||
actor_id: ctx.user_id.clone(),
|
||||
actor_name: ctx.actor_label(),
|
||||
metadata: serde_json::json!({ "method": method, "path": path, "status": status }),
|
||||
}
|
||||
crate::registry::AuditEntry::by(
|
||||
ctx,
|
||||
"pruefwerk.support_access",
|
||||
serde_json::json!({ "method": method, "path": path, "status": status }),
|
||||
)
|
||||
}
|
||||
|
||||
fn cors_layer(origins: &[String], app_env: AppEnv) -> CorsLayer {
|
||||
|
||||
@@ -58,13 +58,55 @@ pub struct RegistryTenant {
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
pub struct AuditEntry {
|
||||
pub tenant_id: String,
|
||||
/// The product that wrote it (`pruefwerk`).
|
||||
pub product: String,
|
||||
/// What happened, e.g. `pruefwerk.support_access`.
|
||||
pub action: String,
|
||||
/// `user`, or `staff` for BreakPilot support.
|
||||
pub actor_type: String,
|
||||
pub actor_id: String,
|
||||
pub actor_name: String,
|
||||
/// What it happened to (e.g. `target`), when it concerns one object.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub target_type: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub target_id: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub target_name: String,
|
||||
pub metadata: serde_json::Value,
|
||||
}
|
||||
|
||||
impl AuditEntry {
|
||||
/// An entry about `ctx`'s requester, with no object yet.
|
||||
pub fn by(
|
||||
ctx: &compliance_core::TenantContext,
|
||||
action: &str,
|
||||
metadata: serde_json::Value,
|
||||
) -> Self {
|
||||
Self {
|
||||
tenant_id: ctx.tenant_id.clone(),
|
||||
product: "pruefwerk".to_string(),
|
||||
action: action.to_string(),
|
||||
actor_type: if ctx.staff.is_some() { "staff" } else { "user" }.to_string(),
|
||||
actor_id: ctx.user_id.clone(),
|
||||
actor_name: ctx.actor_label(),
|
||||
target_type: String::new(),
|
||||
target_id: String::new(),
|
||||
target_name: String::new(),
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same entry, about the target `id` named `name`.
|
||||
#[must_use]
|
||||
pub fn about_target(mut self, id: &str, name: &str) -> Self {
|
||||
self.target_type = "target".to_string();
|
||||
self.target_id = id.to_string();
|
||||
self.target_name = name.to_string();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ApiKeyVerify {
|
||||
pub valid: bool,
|
||||
|
||||
Reference in new issue
Block a user