Skip to content
Open
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
266 changes: 207 additions & 59 deletions crates/openshell-core/src/secrets.rs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions crates/openshell-supervisor-network/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ Later WebSocket frames do not reuse the handshake receipt. Terminal errors carry
and policy-reload cancellation records the active request before dropping it.
Idle connection closures have no HTTP receipt.
The request span ends after its owned stages, not when response headers are logged.
Credential stages finish with a `CredentialPreparation` built from what the
rewriter reports it substituted.
The `openshell.upstream.send` stage measures request writes and flush; response
handling is measured separately. Handled middleware failures remain stage errors
even when the local rejection response is delivered successfully. Receipt
Expand Down
227 changes: 227 additions & 0 deletions crates/openshell-supervisor-network/src/l7/credential_preparation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Bounded, secret-free description of how credential preparation finished.

use std::future::Future;

use openshell_core::secrets::{CredentialSubstitutions, UnresolvedPlaceholderError};
use openshell_core::token_grant_failure::{TokenGrantFailure, TokenGrantFailureKind};
use tracing::Span;
use tracing::instrument::{Instrument as _, Instrumented};

use crate::l7::correlation::{RequestCorrelation, RequestStage};

/// What one credential preparation step did.
pub enum CredentialPreparation {
Prepared {
mechanism: &'static str,
placement: &'static str,
},
NotNeeded,
Refused(&'static str),
Failed(&'static str),
Stale,
GrantRefused(GrantFailure),
GrantFailed(GrantFailure),
}

/// A token grant failure's bounded code and stage.
pub struct GrantFailure {
code: &'static str,
stage: &'static str,
}

impl CredentialPreparation {
/// Classify a placeholder rewrite.
pub fn from_static_rewrite(
result: Result<CredentialSubstitutions, &UnresolvedPlaceholderError>,
) -> Self {
match result {
Ok(substitutions) if substitutions.is_empty() => Self::NotNeeded,
Ok(substitutions) => Self::Prepared {
mechanism: static_mechanism(substitutions),
placement: static_placement(substitutions),
},
Err(error) if error.is_endpoint_mismatch() || error.is_placement_mismatch() => {
Self::Refused("credential_resolution_refused")
}
Err(_) => Self::Failed("credential_resolution_failed"),
}
}

/// Classify token-grant acquisition and header injection.
pub fn from_token_grant(result: Result<(), TokenGrantFailure>) -> Self {
let failure = match result {
Ok(()) => {
return Self::Prepared {
mechanism: "token_grant",
placement: "header",
};
}
Err(failure) => failure,
};
let detail = GrantFailure {
code: failure.code(),
stage: failure.stage().code(),
};
match failure.kind() {
TokenGrantFailureKind::ProviderAuthorizationRequired
| TokenGrantFailureKind::WorkloadIdentityRejected => Self::GrantRefused(detail),
TokenGrantFailureKind::Configuration
| TokenGrantFailureKind::Timeout
| TokenGrantFailureKind::Unavailable
| TokenGrantFailureKind::Unclassified => Self::GrantFailed(detail),
}
}

fn record(&self, span: &Span) {
let (preparation, failure_reason) = match self {
Self::Prepared {
mechanism,
placement,
} => {
span.record("openshell.credential.mechanism", *mechanism);
span.record("openshell.credential.placement", *placement);
("prepared", None)
}
Self::NotNeeded => ("not_needed", None),
Self::Refused(reason) => ("refused", Some(*reason)),
Self::Failed(reason) => ("failed", Some(*reason)),
Self::Stale => ("stale", Some("credential_generation_stale")),
Self::GrantRefused(detail) => {
detail.record(span);
("refused", Some("token_grant_refused"))
}
Self::GrantFailed(detail) => {
detail.record(span);
("failed", Some("token_grant_failed"))
}
};
span.record("openshell.credential.preparation", preparation);
if let Some(reason) = failure_reason {
span.record("otel.status_code", "ERROR");
span.record("openshell.request.failure_reason", reason);
} else {
span.record("otel.status_code", "OK");
}
}
}

impl GrantFailure {
fn record(&self, span: &Span) {
span.record("openshell.credential.failure_code", self.code);
span.record("openshell.credential.failure_stage", self.stage);
}
}

fn static_mechanism(substitutions: CredentialSubstitutions) -> &'static str {
let plain = substitutions.path || substitutions.query || substitutions.header;
match (plain, substitutions.basic) {
(true, true) => "static,basic",
(false, true) => "basic",
_ => "static",
}
}

fn static_placement(substitutions: CredentialSubstitutions) -> &'static str {
let header = substitutions.header || substitutions.basic;
match (substitutions.path, substitutions.query, header) {
(true, true, true) => "path,query,header",
(true, true, false) => "path,query",
(true, false, true) => "path,header",
(true, false, false) => "path",
(false, true, true) => "query,header",
(false, true, false) => "query",
(false, false, _) => "header",
}
}

/// A `CredentialPrepare` stage that must be finished with its preparation
/// result. Dropping it unfinished records the stage as cancelled.
pub struct CredentialStage {
span: Span,
finished: bool,
}

impl CredentialStage {
pub fn open(correlation: Option<&RequestCorrelation>) -> Self {
Self {
span: correlation.map_or_else(Span::none, |correlation| {
correlation.stage(RequestStage::CredentialPrepare)
}),
finished: false,
}
}

pub fn in_scope<T>(&self, operation: impl FnOnce() -> T) -> T {
self.span.in_scope(operation)
}

pub fn instrumented<F: Future>(&self, future: F) -> Instrumented<F> {
future.instrument(self.span.clone())
}

pub fn finish(mut self, preparation: &CredentialPreparation) {
preparation.record(&self.span);
self.finished = true;
}
}

impl Drop for CredentialStage {
fn drop(&mut self) {
if !self.finished {
self.span.record("otel.status_code", "ERROR");
self.span
.record("openshell.request.failure_reason", "cancelled");
}
}
}

#[cfg(test)]
mod tests {
use std::borrow::Cow;
use std::collections::HashMap;

use opentelemetry_sdk::trace::Sampler;

use super::*;
use crate::l7::provider::{BodyLength, L7Request};
use crate::test_support::request_tracing::{RequestTracing, span_attribute};

#[tokio::test]
async fn unfinished_stage_records_cancelled() {
let _lock = openshell_otel_test_support::tracing_test_lock().await;
let capture = RequestTracing::new(Some(Sampler::AlwaysOn));
tracing::subscriber::with_default(capture.subscriber(), || {
let request = L7Request {
action: "GET".into(),
target: "/".into(),
query_params: HashMap::new(),
raw_header: b"GET / HTTP/1.1\r\n\r\n".to_vec(),
body_length: BodyLength::None,
};
let correlation =
RequestCorrelation::new(&request, &crate::l7::relay::L7EvalContext::default());
drop(CredentialStage::open(Some(&correlation)));
});
let stage = capture
.spans()
.into_iter()
.find(|span| span.name == "openshell.credential.prepare")
.expect("credential stage");
capture.shutdown();
assert!(matches!(
stage.status,
opentelemetry::trace::Status::Error { .. }
));
assert_eq!(
span_attribute(&stage, "openshell.request.failure_reason").map(|value| value.as_str()),
Some(Cow::Borrowed("cancelled"))
);
assert_eq!(
span_attribute(&stage, "openshell.credential.preparation"),
None
);
}
}
1 change: 1 addition & 0 deletions crates/openshell-supervisor-network/src/l7/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! evaluated against OPA policy, and either forwarded or denied.

pub(crate) mod correlation;
pub(crate) mod credential_preparation;
pub mod graphql;
pub(crate) mod http;
pub mod jsonrpc;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ struct GrantCall {
struct ScriptedResolver {
calls: Mutex<Vec<GrantCall>>,
fail_once: AtomicBool,
reject_once: AtomicBool,
hold_once: AtomicBool,
entered: Notify,
release: Notify,
Expand Down Expand Up @@ -81,6 +82,12 @@ impl TokenGrantResolver for ScriptedResolver {
TokenGrantStage::TokenEndpoint,
));
}
if self.reject_once.swap(false, Ordering::SeqCst) {
return Err(TokenGrantFailure::new(
TokenGrantFailureKind::WorkloadIdentityRejected,
TokenGrantStage::WorkloadIdentity,
));
}
Ok(format!("inert-{}", request.audience))
})
}
Expand Down Expand Up @@ -998,6 +1005,91 @@ async fn failure_then_reconnect(route_selection: bool) {
]);
}

#[tokio::test]
async fn token_grant_stage_describes_preparation_outcome() {
use super::correlation_dispatch_tests::capture_request_spans;
use crate::test_support::request_tracing::span_attribute;

for (fail, reject, expected) in [
(
false,
false,
[
("openshell.credential.preparation", Some("prepared")),
("openshell.credential.mechanism", Some("token_grant")),
("openshell.credential.placement", Some("header")),
("openshell.request.failure_reason", None),
("openshell.credential.failure_code", None),
("openshell.credential.failure_stage", None),
],
),
(
true,
false,
[
("openshell.credential.preparation", Some("failed")),
("openshell.credential.mechanism", None),
("openshell.credential.placement", None),
(
"openshell.request.failure_reason",
Some("token_grant_failed"),
),
("openshell.credential.failure_code", Some("unavailable")),
("openshell.credential.failure_stage", Some("token_endpoint")),
],
),
(
false,
true,
[
("openshell.credential.preparation", Some("refused")),
("openshell.credential.mechanism", None),
("openshell.credential.placement", None),
(
"openshell.request.failure_reason",
Some("token_grant_refused"),
),
(
"openshell.credential.failure_code",
Some("workload_identity_rejected"),
),
(
"openshell.credential.failure_stage",
Some("workload_identity"),
),
],
),
] {
let evidence = capture_request_spans(true, async {
let fixture = Fixture::new(&[route("a", "/a/**")], &[("/a/**", "a", "aud-a")], 1);
fixture.resolver.fail_once.store(fail, Ordering::SeqCst);
fixture.resolver.reject_once.store(reject, Ordering::SeqCst);
let mut connection = fixture.connect();
let response = connection.exchange("GET", "/a/item", true).await;
connection.finish().await;
response
})
.await;
let stage = evidence
.spans
.iter()
.find(|span| span.name == "openshell.credential.prepare")
.expect("credential preparation stage");
for (name, value) in expected {
assert_eq!(
span_attribute(stage, name).map(|value| value.as_str().into_owned()),
value.map(str::to_owned),
"{name} (fail={fail}, reject={reject})"
);
}
assert_eq!(
matches!(stage.status, opentelemetry::trace::Status::Error { .. }),
fail || reject
);
assert!(!format!("{stage:?}").contains("inert-"), "{stage:?}");
}
}

#[tokio::test]
async fn token_grant_refusal_never_creates_a_denial_only_span() {
use super::correlation_dispatch_tests::capture_request_spans;
Expand Down
14 changes: 14 additions & 0 deletions crates/openshell-supervisor-network/src/l7/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ impl RequestTrace {
if self.span.is_disabled() || !self.span.context().span().span_context().is_valid() {
return Span::none();
}
if matches!(stage, RequestStage::CredentialPrepare) {
return tracing::info_span!(
parent: &self.span,
"openshell.http.stage",
otel.name = stage.name(),
otel.status_code = tracing::field::Empty,
openshell.request.failure_reason = tracing::field::Empty,
openshell.credential.preparation = tracing::field::Empty,
openshell.credential.mechanism = tracing::field::Empty,
openshell.credential.placement = tracing::field::Empty,
openshell.credential.failure_code = tracing::field::Empty,
openshell.credential.failure_stage = tracing::field::Empty,
);
}
tracing::info_span!(
parent: &self.span,
"openshell.http.stage",
Expand Down
Loading
Loading