Skip to content

Commit 1fccc5c

Browse files
committed
refactor(auth): share audit helpers for gateway denials and rejections
Handlers recorded each refusal by emitting an OCSF event and then building the status by hand, so a new refusal could skip the event. These helpers do both in one call: - audit::deny emits an authorization denial for the current request and returns the permission-denied status. Guards, workspace authorization, and the token and current-user handlers use it. - audit::reject_credential emits an Authentication failure for a credential a handler verifies itself and returns the rejection's status. It replaces emit_credential_failure for SSH session tokens and IssueSandboxToken. RefreshSandboxToken now takes its path and origin from the request scope, as every other handler does, instead of rebuilding them from the request. - Failure and logon events share one Authentication builder. - AuthMechanism and AuthFailureReason carry their audit labels. The logon digest uses the label instead of the variant's Debug name. Events and statuses are unchanged. Refs #2912 Signed-off-by: Kris Hicks <[email protected]>
1 parent 7892e4e commit 1fccc5c

8 files changed

Lines changed: 189 additions & 215 deletions

File tree

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

Lines changed: 61 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@
99
1010
use openshell_ocsf::{
1111
ActionId, ActivityId, ApiActivityBuilder, AuthProtocolId, AuthenticationBuilder, ConfidenceId,
12-
DetectionFindingBuilder, DispositionId, Endpoint, FindingInfo, HttpMethod, HttpRequest,
13-
ResourceDetails, Service, SeverityId, StatusId, Url, User, UserTypeId, ocsf_emit,
12+
DetectionFindingBuilder, DispositionId, Endpoint, EventContext, FindingInfo, HttpMethod,
13+
HttpRequest, ResourceDetails, Service, SeverityId, StatusId, Url, User, UserTypeId, ocsf_emit,
1414
};
1515
use std::collections::{HashSet, VecDeque};
1616
use std::future::Future;
1717
use std::net::SocketAddr;
1818
use std::sync::{Arc, Mutex, PoisonError};
1919
use std::time::{Duration, Instant};
20+
use tonic::Status;
2021

2122
use super::identity::IdentityProvider;
2223
use super::principal::{Principal, SandboxIdentitySource};
@@ -60,21 +61,7 @@ impl RequestOrigin {
6061
}
6162
}
6263

63-
use super::authenticator::{AuthFailureReason, AuthMechanism, bearer_credential};
64-
65-
fn category(reason: AuthFailureReason) -> &'static str {
66-
match reason {
67-
AuthFailureReason::MissingCredential => "missing_credential",
68-
AuthFailureReason::ConflictingCredentials => "conflicting_credentials",
69-
AuthFailureReason::MalformedCredential => "malformed_credential",
70-
AuthFailureReason::InvalidCredential => "invalid_credential",
71-
AuthFailureReason::ExpiredCredential => "expired_credential",
72-
AuthFailureReason::AudienceOrIssuerMismatch => "audience_or_issuer_mismatch",
73-
AuthFailureReason::UnknownIdentity => "unknown_identity",
74-
AuthFailureReason::StaleIdentity => "stale_identity",
75-
AuthFailureReason::IdentityProviderUnavailable => "identity_provider_unavailable",
76-
}
77-
}
64+
use super::authenticator::{AuthFailureReason, AuthMechanism, AuthRejection, bearer_credential};
7865

7966
fn severity(reason: AuthFailureReason) -> SeverityId {
8067
match reason {
@@ -91,18 +78,37 @@ fn severity(reason: AuthFailureReason) -> SeverityId {
9178
}
9279
}
9380

94-
fn with_protocol(
95-
builder: AuthenticationBuilder<'_>,
96-
mechanism: AuthMechanism,
97-
) -> AuthenticationBuilder<'_> {
81+
/// The request to `path` as an OCSF HTTP request; gRPC calls are POSTs.
82+
fn post(path: &str) -> HttpRequest {
83+
HttpRequest {
84+
http_method: HttpMethod::Post,
85+
url: Some(Url::from_path(path)),
86+
}
87+
}
88+
89+
/// An Authentication event for `user`'s request to `path` from `origin`,
90+
/// naming the protocol of `mechanism` when known.
91+
fn authentication<'a>(
92+
ctx: &'a EventContext,
93+
path: &str,
94+
origin: &RequestOrigin,
95+
user: User,
96+
mechanism: Option<AuthMechanism>,
97+
) -> AuthenticationBuilder<'a> {
98+
let mut builder = AuthenticationBuilder::new(ctx, user, Service::new("openshell-gateway"))
99+
.http_request(post(path));
98100
match mechanism {
99-
AuthMechanism::Oidc => builder.auth_protocol(AuthProtocolId::OpenId),
100-
AuthMechanism::Mtls => builder.auth_protocol_other("mtls"),
101-
AuthMechanism::SandboxJwt => builder.auth_protocol_other("sandbox_jwt"),
102-
AuthMechanism::ComputeDriver => builder.auth_protocol_other("compute_driver"),
103-
AuthMechanism::GatewayPeer => builder.auth_protocol_other("k8s_service_account"),
104-
AuthMechanism::SshSessionToken => builder.auth_protocol_other("ssh_session_token"),
101+
Some(AuthMechanism::Oidc) => builder = builder.auth_protocol(AuthProtocolId::OpenId),
102+
Some(mechanism) => builder = builder.auth_protocol_other(mechanism.as_str()),
103+
None => {}
104+
}
105+
if let Some(source) = origin.source {
106+
builder = builder.src_endpoint(source.endpoint());
105107
}
108+
if let Some(request_id) = &origin.request_id {
109+
builder = builder.correlation_uid(request_id);
110+
}
111+
builder
106112
}
107113

108114
/// Emit an Authentication failure event for a gRPC request to `path`.
@@ -116,20 +122,21 @@ pub fn emit_authentication_failure(
116122
}
117123

118124
/// Emit an Authentication failure event for a credential that a handler
119-
/// verifies itself, after the router established `principal`.
120-
pub fn emit_credential_failure(
121-
principal: &Principal,
122-
mechanism: AuthMechanism,
123-
reason: AuthFailureReason,
124-
) {
125+
/// verifies itself, returning the status that refuses the current request.
126+
///
127+
/// The event names `principal`, the caller the router established from a
128+
/// separate credential, or leaves the user unidentified when the rejected
129+
/// credential is the one that named the caller.
130+
pub fn reject_credential(principal: Option<&Principal>, rejection: AuthRejection) -> Status {
125131
let (path, origin) = current_request();
126132
authentication_failure(
127133
&path,
128134
&origin,
129-
principal_user(principal),
130-
Some(mechanism),
131-
reason,
135+
principal.map_or_else(User::unidentified, principal_user),
136+
Some(rejection.mechanism),
137+
rejection.reason,
132138
);
139+
rejection.status
133140
}
134141

135142
fn authentication_failure(
@@ -140,26 +147,13 @@ fn authentication_failure(
140147
reason: AuthFailureReason,
141148
) {
142149
let ctx = crate::gateway_ocsf::context("", "");
143-
let mut builder = AuthenticationBuilder::new(&ctx, user, Service::new("openshell-gateway"))
150+
let builder = authentication(&ctx, path, origin, user, mechanism)
144151
.action(ActionId::Denied)
145152
.disposition(DispositionId::Blocked)
146153
.severity(severity(reason))
147154
.status(StatusId::Failure)
148-
.status_detail(category(reason))
149-
.http_request(HttpRequest {
150-
http_method: HttpMethod::Post,
151-
url: Some(Url::from_path(path)),
152-
})
153-
.message(format!("authentication failed: {}", category(reason)));
154-
if let Some(mechanism) = mechanism {
155-
builder = with_protocol(builder, mechanism);
156-
}
157-
if let Some(source) = origin.source {
158-
builder = builder.src_endpoint(source.endpoint());
159-
}
160-
if let Some(request_id) = &origin.request_id {
161-
builder = builder.correlation_uid(request_id);
162-
}
155+
.status_detail(reason.as_str())
156+
.message(format!("authentication failed: {}", reason.as_str()));
163157
ocsf_emit!(builder.build());
164158
}
165159

@@ -271,7 +265,7 @@ fn digest(
271265
let mut material = principal.audit_actor().into_bytes();
272266
material.push(0);
273267
if let Some(mechanism) = mechanism {
274-
material.extend_from_slice(format!("{mechanism:?}").as_bytes());
268+
material.extend_from_slice(mechanism.as_str().as_bytes());
275269
material.push(0);
276270
}
277271
material.extend_from_slice(credential.as_bytes());
@@ -355,29 +349,12 @@ fn logon(
355349
mechanism: Option<AuthMechanism>,
356350
) {
357351
let ctx = crate::gateway_ocsf::context("", "");
358-
let mut builder = AuthenticationBuilder::new(
359-
&ctx,
360-
principal_user(principal),
361-
Service::new("openshell-gateway"),
362-
)
363-
.action(ActionId::Allowed)
364-
.disposition(DispositionId::Allowed)
365-
.severity(SeverityId::Informational)
366-
.status(StatusId::Success)
367-
.http_request(HttpRequest {
368-
http_method: HttpMethod::Post,
369-
url: Some(Url::from_path(path)),
370-
})
371-
.message("authentication succeeded");
372-
if let Some(mechanism) = mechanism {
373-
builder = with_protocol(builder, mechanism);
374-
}
375-
if let Some(source) = origin.source {
376-
builder = builder.src_endpoint(source.endpoint());
377-
}
378-
if let Some(request_id) = &origin.request_id {
379-
builder = builder.correlation_uid(request_id);
380-
}
352+
let builder = authentication(&ctx, path, origin, principal_user(principal), mechanism)
353+
.action(ActionId::Allowed)
354+
.disposition(DispositionId::Allowed)
355+
.severity(SeverityId::Informational)
356+
.status(StatusId::Success)
357+
.message("authentication succeeded");
381358
ocsf_emit!(builder.build());
382359
}
383360

@@ -536,6 +513,13 @@ pub fn emit_authorization_denial(principal: &Principal, denial: AuthzDenial<'_>)
536513
emit_authorization_denial_for(&path, &origin, principal, denial);
537514
}
538515

516+
/// Emit an authorization denial raised by a handler for the current request,
517+
/// returning the status that refuses it with `message`.
518+
pub fn deny(principal: &Principal, denial: AuthzDenial<'_>, message: impl Into<String>) -> Status {
519+
emit_authorization_denial(principal, denial);
520+
Status::permission_denied(message)
521+
}
522+
539523
/// Emit an API Activity denial for a gRPC request to `path`, paired with a
540524
/// Detection Finding when a sandbox principal crossed its boundary.
541525
pub fn emit_authorization_denial_for(
@@ -573,10 +557,7 @@ pub fn emit_authorization_denial_for(
573557
if !service.is_empty() {
574558
builder = builder
575559
.api_service(Service::new(service))
576-
.http_request(HttpRequest {
577-
http_method: HttpMethod::Post,
578-
url: Some(Url::from_path(path)),
579-
});
560+
.http_request(post(path));
580561
}
581562
if let Some(resource) = denial.resource() {
582563
builder = builder.resource(resource);

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@ pub enum AuthFailureReason {
9191
IdentityProviderUnavailable,
9292
}
9393

94+
impl AuthFailureReason {
95+
/// The category recorded in audit events.
96+
pub fn as_str(self) -> &'static str {
97+
match self {
98+
Self::MissingCredential => "missing_credential",
99+
Self::ConflictingCredentials => "conflicting_credentials",
100+
Self::MalformedCredential => "malformed_credential",
101+
Self::InvalidCredential => "invalid_credential",
102+
Self::ExpiredCredential => "expired_credential",
103+
Self::AudienceOrIssuerMismatch => "audience_or_issuer_mismatch",
104+
Self::UnknownIdentity => "unknown_identity",
105+
Self::StaleIdentity => "stale_identity",
106+
Self::IdentityProviderUnavailable => "identity_provider_unavailable",
107+
}
108+
}
109+
}
110+
94111
/// The mechanism a caller attempted to authenticate with.
95112
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96113
pub enum AuthMechanism {
@@ -103,6 +120,21 @@ pub enum AuthMechanism {
103120
SshSessionToken,
104121
}
105122

123+
impl AuthMechanism {
124+
/// A stable label for the mechanism. Audit events record it as the
125+
/// protocol, except OIDC, which they record as the OCSF `OpenID` protocol.
126+
pub fn as_str(self) -> &'static str {
127+
match self {
128+
Self::Mtls => "mtls",
129+
Self::Oidc => "oidc",
130+
Self::SandboxJwt => "sandbox_jwt",
131+
Self::ComputeDriver => "compute_driver",
132+
Self::GatewayPeer => "k8s_service_account",
133+
Self::SshSessionToken => "ssh_session_token",
134+
}
135+
}
136+
}
137+
106138
/// A rejected authentication attempt: the status returned to the caller and
107139
/// the category recorded in the audit event.
108140
#[derive(Debug, Clone)]

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

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
//! `sandbox_id`. User principals retain the broad scope the RBAC layer
99
//! already evaluated.
1010
11-
use super::audit::{AuthzDenial, emit_authorization_denial};
11+
use super::audit::{AuthzDenial, deny};
1212
use super::principal::Principal;
1313
use super::principal::SandboxPrincipal;
1414
use tonic::Status;
@@ -30,23 +30,20 @@ use tonic::Status;
3030
pub fn ensure_sandbox_scope(principal: &Principal, claimed_sandbox_id: &str) -> Result<(), Status> {
3131
match principal {
3232
Principal::User(_) | Principal::Operator(_) => Ok(()),
33-
Principal::Peer(_) => {
34-
emit_authorization_denial(principal, AuthzDenial::MethodNotPermitted);
35-
Err(Status::permission_denied(
36-
"gateway peer principals may not call sandbox-scoped methods",
37-
))
38-
}
33+
Principal::Peer(_) => Err(deny(
34+
principal,
35+
AuthzDenial::MethodNotPermitted,
36+
"gateway peer principals may not call sandbox-scoped methods",
37+
)),
3938
Principal::Sandbox(p) => {
4039
if p.sandbox_id == claimed_sandbox_id {
4140
Ok(())
4241
} else {
43-
emit_authorization_denial(
42+
Err(deny(
4443
principal,
4544
AuthzDenial::CrossSandbox {
4645
sandbox_id: claimed_sandbox_id,
4746
},
48-
);
49-
Err(Status::permission_denied(
5047
"cross-sandbox access denied: principal does not own this sandbox",
5148
))
5249
}
@@ -91,12 +88,11 @@ pub fn ensure_sandbox_principal_scope(
9188
ensure_sandbox_scope(principal, claimed_sandbox_id)?;
9289
Ok(p.clone())
9390
}
94-
Principal::User(_) | Principal::Operator(_) | Principal::Peer(_) => {
95-
emit_authorization_denial(principal, AuthzDenial::MethodNotPermitted);
96-
Err(Status::permission_denied(
97-
"supervisor RPCs require a sandbox principal",
98-
))
99-
}
91+
Principal::User(_) | Principal::Operator(_) | Principal::Peer(_) => Err(deny(
92+
principal,
93+
AuthzDenial::MethodNotPermitted,
94+
"supervisor RPCs require a sandbox principal",
95+
)),
10096
Principal::Anonymous => Err(Status::unauthenticated(
10197
"supervisor RPCs require an authenticated sandbox principal",
10298
)),
@@ -123,10 +119,11 @@ pub fn require_operator<T>(
123119
None | Some(Principal::Anonymous) => {
124120
Err(Status::unauthenticated("operator authentication required"))
125121
}
126-
Some(principal) => {
127-
emit_authorization_denial(principal, AuthzDenial::OperatorRequired);
128-
Err(Status::permission_denied("verified mTLS operator required"))
129-
}
122+
Some(principal) => Err(deny(
123+
principal,
124+
AuthzDenial::OperatorRequired,
125+
"verified mTLS operator required",
126+
)),
130127
}
131128
}
132129

0 commit comments

Comments
 (0)