Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions crates/openshell-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,9 @@ pub struct Config {
/// sandbox identity is always carried by gateway-minted sandbox JWTs.
pub mtls_auth: MtlsAuthConfig,

/// Optional details gateway mutation records capture.
pub audit: GatewayAuditConfig,

/// Gateway-minted sandbox JWT configuration. When `Some`, the gateway
/// loads the signing key from disk and accepts gateway-issued sandbox
/// JWTs as `Principal::Sandbox`. Required for the per-sandbox identity
Expand Down Expand Up @@ -626,6 +629,17 @@ pub struct OidcConfig {
pub scopes_claim: String,
}

/// `[openshell.gateway.audit]`: optional details gateway mutation records
/// capture. Secrets are never captured.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GatewayAuditConfig {
/// Record the values of gateway and sandbox settings that `UpdateConfig`
/// sets. Bytes values are never recorded.
#[serde(default)]
pub capture_setting_values: bool,
}

/// mTLS user authentication for gateway users.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
Expand Down Expand Up @@ -1114,6 +1128,7 @@ impl Config {
gateway_interceptors: Vec::new(),
provider_profile_sources: vec![GatewayProviderProfileSourceConfig::User],
mtls_auth: MtlsAuthConfig::default(),
audit: GatewayAuditConfig::default(),
gateway_jwt: None,
database_url: String::new(),
database_auth: DatabaseAuthMode::default(),
Expand Down
2 changes: 1 addition & 1 deletion crates/openshell-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ pub mod transport_errors;
pub mod upload;

pub use config::{
AppArmorProfile, Config, ExtensionBindingPolicy, GatewayAuthConfig,
AppArmorProfile, Config, ExtensionBindingPolicy, GatewayAuditConfig, GatewayAuthConfig,
GatewayInterceptorBindingOverride, GatewayInterceptorBindingPolicy, GatewayInterceptorConfig,
GatewayInterceptorFailurePolicy, GatewayInterceptorPhaseConfig, GatewayJwtConfig,
GatewayProviderProfileSourceConfig, ImagePullPolicy, MetricsTlsConfig, MtlsAuthConfig,
Expand Down
24 changes: 24 additions & 0 deletions crates/openshell-ocsf/src/objects/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ pub struct ResourceDetails {
/// Resource type (e.g. "sandbox", "workspace").
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub type_label: Option<String>,

/// Additional details about the resource.
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
}

impl ResourceDetails {
Expand All @@ -32,6 +36,7 @@ impl ResourceDetails {
uid: Some(uid.into()),
name: None,
type_label: Some(type_label.into()),
data: None,
}
}

Expand All @@ -42,8 +47,16 @@ impl ResourceDetails {
uid: None,
name: Some(name.into()),
type_label: Some(type_label.into()),
data: None,
}
}

/// This resource with additional details.
#[must_use]
pub fn with_data(mut self, data: serde_json::Value) -> Self {
self.data = Some(data);
self
}
}

#[cfg(test)]
Expand All @@ -56,6 +69,17 @@ mod tests {
assert_eq!(json, serde_json::json!({"uid": "sb-1", "type": "sandbox"}));
}

#[test]
fn resource_carries_data() {
let resource = ResourceDetails::named("setting", "log_level")
.with_data(serde_json::json!({"value": "debug"}));
let json = serde_json::to_value(resource).unwrap();
assert_eq!(
json,
serde_json::json!({"name": "log_level", "type": "setting", "data": {"value": "debug"}})
);
}

#[test]
fn named_resource_has_no_uid() {
let json = serde_json::to_value(ResourceDetails::named("workspace", "default")).unwrap();
Expand Down
84 changes: 61 additions & 23 deletions crates/openshell-server/src/auth/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -699,10 +699,10 @@ impl AuthzDenial<'_> {
}
}

/// Longest identifier recorded on an event.
/// Longest identifier or value recorded on an event.
const MAX_ID_LEN: usize = 128;

/// Cap an identifier so a caller cannot inflate events.
/// Cap a value so a caller cannot inflate events.
fn bounded(value: &str) -> String {
if value.len() <= MAX_ID_LEN {
return value.to_string();
Expand Down Expand Up @@ -775,16 +775,20 @@ fn emit_denial(
.request_id
.clone()
.or_else(|| finding.then(|| uuid::Uuid::new_v4().to_string()));
if let Some(resource) = denial.resource().filter(|r| !resources.contains(r)) {
resources.push(resource);
}
let (resources, omitted) = limited_resources(resources);
let mut builder = api_activity(&ctx, path, origin, principal)
.action(ActionId::Denied)
.disposition(DispositionId::Blocked)
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.status_detail(category)
.message(format!("authorization denied: {category}"));
if let Some(resource) = denial.resource().filter(|r| !resources.contains(r)) {
resources.push(resource);
}
.message(with_omitted(
format!("authorization denied: {category}"),
omitted,
));
for resource in resources {
builder = builder.resource(resource);
}
Expand Down Expand Up @@ -870,26 +874,62 @@ fn api_activity<'a>(
builder
}

/// Most resources one mutation record lists.
/// Most resources one record lists: the first ones recorded and the last,
/// which is what the change produced.
const MAX_RECORDED_RESOURCES: usize = 16;

/// `data` with every string in it bounded.
fn bounded_data(data: serde_json::Value) -> serde_json::Value {
use serde_json::Value;
match data {
Value::String(value) => Value::String(bounded(&value)),
Value::Array(values) => values.into_iter().map(bounded_data).collect(),
Value::Object(fields) => fields
.into_iter()
.map(|(key, value)| (bounded(&key), bounded_data(value)))
.collect(),
scalar => scalar,
}
}

/// At most [`MAX_RECORDED_RESOURCES`] of `resources`, every field bounded,
/// and how many were left out.
fn limited_resources(mut resources: Vec<ResourceDetails>) -> (Vec<ResourceDetails>, usize) {
let omitted = resources.len().saturating_sub(MAX_RECORDED_RESOURCES);
if omitted > 0 {
resources.drain(MAX_RECORDED_RESOURCES - 1..resources.len() - 1);
}
let resources = resources
.into_iter()
.map(|resource| ResourceDetails {
name: resource.name.as_deref().map(bounded),
uid: resource.uid.as_deref().map(bounded),
type_label: resource.type_label,
data: resource.data.map(bounded_data),
Comment thread
krishicks marked this conversation as resolved.
Resolved
})
.collect();
(resources, omitted)
}

/// `message`, noting the `omitted` resources a record does not list.
fn with_omitted(message: String, omitted: usize) -> String {
if omitted == 0 {
message
} else {
format!("{message}; {omitted} more resources not listed")
}
}

/// Emit the record of a mutation that ended with `code`, or that never
/// finished when `code` is `None`.
fn emit_mutation(request: &RequestContext, principal: &Principal, code: Option<Code>) {
let RequestContext { path, origin, .. } = request;
let mutation = std::mem::take(&mut *lock(&request.mutation));
let ctx = crate::gateway_ocsf::context("", "");
let mut builder = api_activity(&ctx, path, origin, principal);
let omitted = mutation
.resources
.len()
.saturating_sub(MAX_RECORDED_RESOURCES);
for resource in mutation.resources.into_iter().take(MAX_RECORDED_RESOURCES) {
builder = builder.resource(ResourceDetails {
name: resource.name.as_deref().map(bounded),
uid: resource.uid.as_deref().map(bounded),
..resource
});
let (resources, omitted) = limited_resources(mutation.resources);
for resource in resources {
builder = builder.resource(resource);
}
let code = code.map(|code| match mutation.outcome {
Some(Outcome::Rejected(rejected)) if code == Code::Ok => rejected,
Expand Down Expand Up @@ -922,12 +962,10 @@ fn emit_mutation(request: &RequestContext, principal: &Principal, code: Option<C
Some(failure),
),
};
let message = if omitted == 0 {
message
} else {
format!("{message}; {omitted} more resources not listed")
};
builder = builder.severity(severity).status(status).message(message);
builder = builder
.severity(severity)
.status(status)
.message(with_omitted(message, omitted));
if let Some(detail) = detail {
builder = builder.status_detail(detail);
}
Expand Down
6 changes: 6 additions & 0 deletions crates/openshell-server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,12 @@ fn prepare_server_config_with_drivers(
if let Some(auth) = file.as_ref().and_then(|f| f.openshell.gateway.auth.clone()) {
config.auth = auth;
}
if let Some(audit) = file
.as_ref()
.and_then(|f| f.openshell.gateway.audit.clone())
{
config.audit = audit;
}
config.mtls_auth.enabled = mtls_auth_enabled;
config.mtls_auth.operator_enabled = args.enable_operator_auth;

Expand Down
14 changes: 12 additions & 2 deletions crates/openshell-server/src/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ use openshell_core::proto::{
};
use openshell_core::sandbox_env::OtlpProtocol;
use openshell_core::{
ExtensionBindingPolicy, GatewayAuthConfig, GatewayInterceptorConfig, GatewayJwtConfig,
GatewayProviderProfileSourceConfig, MtlsAuthConfig, OidcConfig,
ExtensionBindingPolicy, GatewayAuditConfig, GatewayAuthConfig, GatewayInterceptorConfig,
GatewayJwtConfig, GatewayProviderProfileSourceConfig, MtlsAuthConfig, OidcConfig,
};
use rustls::pki_types::pem::{PemObject, SectionKind};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -225,6 +225,8 @@ pub struct GatewayFileSection {
#[serde(default)]
pub mtls_auth: Option<MtlsAuthConfig>,
#[serde(default)]
pub audit: Option<GatewayAuditConfig>,
#[serde(default)]
pub gateway_jwt: Option<GatewayJwtConfig>,
#[serde(default)]
pub otlp: Option<OtlpConfig>,
Expand Down Expand Up @@ -2123,6 +2125,14 @@ service_name = "openshell-gateway-dev"
assert_eq!(otlp.service_name.as_deref(), Some("openshell-gateway-dev"));
}

#[test]
fn gateway_audit_capture_is_opt_in() {
let tmp = write_tmp("[openshell.gateway.audit]\ncapture_setting_values = true\n");
let audit = load(tmp.path()).unwrap().openshell.gateway.audit.unwrap();
assert!(audit.capture_setting_values);
assert!(!GatewayAuditConfig::default().capture_setting_values);
}

#[test]
fn gateway_accepts_a_single_ocsf_log_destination() {
let tmp = write_tmp("[openshell.gateway.ocsf_log]\npath = 'events.jsonl'\n");
Expand Down
Loading
Loading