fix(client-rust): scrub all error variants and redact tonic::Status Display/Debug (CRS-002, CRS-003, #257)
This commit is contained in:
+127
-13
@@ -174,7 +174,9 @@ impl std::fmt::Display for CommandError {
|
||||
let code = status
|
||||
.and_then(|status| ProtocolStatusCode::try_from(status.code).ok())
|
||||
.unwrap_or(ProtocolStatusCode::Unspecified);
|
||||
let message = status.map(|status| status.message.as_str()).unwrap_or("");
|
||||
let message = status
|
||||
.map(|status| redact_credentials(&status.message))
|
||||
.unwrap_or_default();
|
||||
|
||||
if message.is_empty() {
|
||||
write!(formatter, "{code:?}")
|
||||
@@ -368,39 +370,85 @@ impl Error {
|
||||
name,
|
||||
detail: scrub(&detail),
|
||||
},
|
||||
Self::MxAccess(error) => Self::MxAccess(Box::new(
|
||||
error.with_secrets(secrets.iter().map(|secret| (*secret).to_owned()).collect()),
|
||||
)),
|
||||
Self::MxAccess(error) => {
|
||||
// Scrub the stored reply (so `reply()`/`into_reply()` cannot
|
||||
// recover an echoed credential) and keep the secrets attached
|
||||
// for `Display`/`Debug`, together with any attached earlier.
|
||||
let mut all_secrets = error.secrets.clone();
|
||||
all_secrets.extend(secrets.iter().map(|secret| (*secret).to_owned()));
|
||||
let mut reply = error.into_reply();
|
||||
scrub_reply_strings(&mut reply, &all_secrets);
|
||||
Self::MxAccess(Box::new(
|
||||
MxAccessError::new(reply).with_secrets(all_secrets),
|
||||
))
|
||||
}
|
||||
Self::Command(error) => {
|
||||
let owned: Vec<String> =
|
||||
secrets.iter().map(|secret| (*secret).to_owned()).collect();
|
||||
let mut reply = error.into_reply();
|
||||
scrub_reply_strings(&mut reply, &owned);
|
||||
Self::Command(Box::new(CommandError::new(reply)))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace every non-empty secret occurrence with `<redacted>` in the reply's
|
||||
/// caller-readable string fields — `protocol_status.message`,
|
||||
/// `diagnostic_message`, and each `statuses[i].diagnostic_text`. A caller
|
||||
/// reading the structured reply back off an error would otherwise reintroduce
|
||||
/// the leak that `Display`/`Debug` already close.
|
||||
pub(crate) fn scrub_reply_strings(reply: &mut MxCommandReply, secrets: &[String]) {
|
||||
for secret in secrets {
|
||||
if secret.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(status) = reply.protocol_status.as_mut() {
|
||||
status.message = status.message.replace(secret.as_str(), "<redacted>");
|
||||
}
|
||||
reply.diagnostic_message = reply
|
||||
.diagnostic_message
|
||||
.replace(secret.as_str(), "<redacted>");
|
||||
for status in &mut reply.statuses {
|
||||
status.diagnostic_text = status
|
||||
.diagnostic_text
|
||||
.replace(secret.as_str(), "<redacted>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tonic::Status> for Error {
|
||||
fn from(status: tonic::Status) -> Self {
|
||||
// Rebuild the stored status with the redacted message in every arm so
|
||||
// the `Debug` output and `source()` chain cannot reveal what `Display`
|
||||
// hides. The original metadata is dropped on purpose: it can carry the
|
||||
// authorization header value echoed by an intermediary.
|
||||
let message = redact_credentials(status.message());
|
||||
match status.code() {
|
||||
let code = status.code();
|
||||
let redacted = || Box::new(tonic::Status::new(code, message.clone()));
|
||||
match code {
|
||||
Code::Unauthenticated => Self::Authentication {
|
||||
status: redacted(),
|
||||
message,
|
||||
status: Box::new(status),
|
||||
},
|
||||
Code::PermissionDenied => Self::Authorization {
|
||||
status: redacted(),
|
||||
message,
|
||||
status: Box::new(status),
|
||||
},
|
||||
Code::DeadlineExceeded => Self::Timeout {
|
||||
status: redacted(),
|
||||
message,
|
||||
status: Box::new(status),
|
||||
},
|
||||
Code::Cancelled => Self::Cancelled {
|
||||
status: redacted(),
|
||||
message,
|
||||
status: Box::new(status),
|
||||
},
|
||||
Code::Unavailable | Code::ResourceExhausted => Self::Unavailable {
|
||||
status: redacted(),
|
||||
message,
|
||||
status: Box::new(status),
|
||||
},
|
||||
_ => Self::Status(Box::new(status)),
|
||||
_ => Self::Status(redacted()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -507,11 +555,31 @@ pub fn ensure_protocol_success(
|
||||
}
|
||||
}
|
||||
|
||||
/// Redact credential-shaped text: any `mxgw_<id>_<secret>` token wherever it
|
||||
/// appears (quoted, after `key=`, inside parentheses) and the bare word
|
||||
/// `bearer`. Matching is substring-based on the `mxgw_[A-Za-z0-9_-]+` shape; a
|
||||
/// whitespace-token prefix test would miss `"mxgw_..."`, `key=mxgw_...` and
|
||||
/// `(mxgw_...)`.
|
||||
fn redact_credentials(message: &str) -> String {
|
||||
message
|
||||
const MARKER: &str = "mxgw_";
|
||||
let mut scrubbed = String::with_capacity(message.len());
|
||||
let mut rest = message;
|
||||
while let Some(index) = rest.find(MARKER) {
|
||||
scrubbed.push_str(&rest[..index]);
|
||||
scrubbed.push_str("<redacted>");
|
||||
let token = &rest[index..];
|
||||
let end = token
|
||||
.char_indices()
|
||||
.find(|(_, c)| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-'))
|
||||
.map_or(token.len(), |(i, _)| i);
|
||||
rest = &token[end..];
|
||||
}
|
||||
scrubbed.push_str(rest);
|
||||
|
||||
scrubbed
|
||||
.split_whitespace()
|
||||
.map(|part| {
|
||||
if part.starts_with("mxgw_") || part.eq_ignore_ascii_case("bearer") {
|
||||
if part.eq_ignore_ascii_case("bearer") {
|
||||
"<redacted>"
|
||||
} else {
|
||||
part
|
||||
@@ -533,6 +601,52 @@ mod tests {
|
||||
|
||||
use tonic::{Code, Status};
|
||||
|
||||
#[test]
|
||||
fn status_debug_and_display_redact_embedded_key_shapes() {
|
||||
for text in [
|
||||
"bad header \"mxgw_id_secret\"",
|
||||
"key=mxgw_id_secret",
|
||||
"(mxgw_id_secret)",
|
||||
"Bearer mxgw_id_secret",
|
||||
] {
|
||||
for code in [
|
||||
Code::Internal,
|
||||
Code::InvalidArgument,
|
||||
Code::PermissionDenied,
|
||||
] {
|
||||
let error = Error::from(Status::new(code, text));
|
||||
let display = error.to_string();
|
||||
let debug = format!("{error:?}");
|
||||
assert!(!display.contains("secret"), "{text}: display {display}");
|
||||
assert!(!debug.contains("secret"), "{text}: debug {debug}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_secrets_scrubs_command_error_reply() {
|
||||
let reply = MxCommandReply {
|
||||
protocol_status: Some(ProtocolStatus {
|
||||
code: ProtocolStatusCode::InvalidRequest as i32,
|
||||
message: "bad credential hunter2".to_owned(),
|
||||
}),
|
||||
diagnostic_message: "echo hunter2".to_owned(),
|
||||
..MxCommandReply::default()
|
||||
};
|
||||
let error = Error::from(Box::new(super::CommandError::new(reply)));
|
||||
|
||||
let error = error.redact_secrets(&["hunter2"]);
|
||||
|
||||
assert!(!error.to_string().contains("hunter2"));
|
||||
assert!(!format!("{error:?}").contains("hunter2"));
|
||||
match error {
|
||||
Error::Command(command) => {
|
||||
assert!(!command.reply().diagnostic_message.contains("hunter2"));
|
||||
}
|
||||
other => panic!("expected Command, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
use super::{ensure_mxaccess_success, Error};
|
||||
use crate::generated::mxaccess_gateway::v1::{
|
||||
MxCommandReply, MxStatusCategory, MxStatusProxy, ProtocolStatus, ProtocolStatusCode,
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::client::{EventStream, GatewayClient};
|
||||
use crate::error::{ensure_protocol_success, Error, MxAccessError};
|
||||
use crate::error::{ensure_protocol_success, Error};
|
||||
use crate::generated::mxaccess_gateway::v1::mx_command::Payload;
|
||||
use crate::generated::mxaccess_gateway::v1::mx_command_reply;
|
||||
use crate::generated::mxaccess_gateway::v1::{
|
||||
@@ -1209,45 +1209,14 @@ fn string_secret(value: &MxValue) -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach caller-supplied exact secrets to an [`Error::MxAccess`] before it
|
||||
/// propagates. This both scrubs the stored reply's caller-readable string
|
||||
/// fields (so `reply()`/`into_reply()` cannot recover a credential MXAccess
|
||||
/// echoed back verbatim) and keeps the secrets on the error as a
|
||||
/// belt-and-suspenders for `Display`/`Debug`. Any other error variant is
|
||||
/// returned unchanged.
|
||||
/// Attach caller-supplied exact secrets to an error before it propagates, so
|
||||
/// that neither `Display`, `Debug`, `source()` nor the structured reply carried
|
||||
/// by [`Error::MxAccess`] / [`Error::Command`] can reveal them. Every variant is
|
||||
/// scrubbed, not only [`Error::MxAccess`]: a worker- or protocol-level status
|
||||
/// (`WORKER_UNAVAILABLE`, `INVALID_REQUEST`) can echo the credential too.
|
||||
fn attach_secrets(error: Error, secrets: Vec<String>) -> Error {
|
||||
match error {
|
||||
Error::MxAccess(boxed) => {
|
||||
let mut reply = boxed.into_reply();
|
||||
scrub_reply_strings(&mut reply, &secrets);
|
||||
Error::MxAccess(Box::new(MxAccessError::new(reply).with_secrets(secrets)))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace every non-empty secret occurrence with `<redacted>` in the reply's
|
||||
/// caller-readable string fields — `protocol_status.message`,
|
||||
/// `diagnostic_message`, and each `statuses[i].diagnostic_text`. A caller
|
||||
/// reading the structured reply back off an [`Error::MxAccess`] would otherwise
|
||||
/// reintroduce the leak that `Display`/`Debug` already close.
|
||||
fn scrub_reply_strings(reply: &mut MxCommandReply, secrets: &[String]) {
|
||||
for secret in secrets {
|
||||
if secret.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(status) = reply.protocol_status.as_mut() {
|
||||
status.message = status.message.replace(secret.as_str(), "<redacted>");
|
||||
}
|
||||
reply.diagnostic_message = reply
|
||||
.diagnostic_message
|
||||
.replace(secret.as_str(), "<redacted>");
|
||||
for status in &mut reply.statuses {
|
||||
status.diagnostic_text = status
|
||||
.diagnostic_text
|
||||
.replace(secret.as_str(), "<redacted>");
|
||||
}
|
||||
}
|
||||
let secret_refs: Vec<&str> = secrets.iter().map(String::as_str).collect();
|
||||
error.redact_secrets(&secret_refs)
|
||||
}
|
||||
|
||||
fn suspend_status(reply: MxCommandReply) -> Result<MxStatus, Error> {
|
||||
|
||||
@@ -887,6 +887,35 @@ async fn authenticate_user_keeps_credentials_out_of_surfaced_errors() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticate_user_scrubs_credential_from_protocol_level_command_error() {
|
||||
// CRS-002: a protocol-level failure (not MXACCESS_FAILURE) surfaces as
|
||||
// Error::Command; its message and diagnostic must be scrubbed too.
|
||||
let credential = "sup3rSecretVerify9f3a2b";
|
||||
let mut reply = command_reply_fixture("authenticate-user.echoed-credential.reply.json");
|
||||
reply.protocol_status = Some(ProtocolStatus {
|
||||
code: ProtocolStatusCode::InvalidRequest as i32,
|
||||
message: format!("bad request for {credential}"),
|
||||
});
|
||||
reply.diagnostic_message = format!("echo {credential}");
|
||||
let state = Arc::new(FakeState::default());
|
||||
*state.invoke_override.lock().await = Some(InvokeOverride::CannedReply(Box::new(reply)));
|
||||
let endpoint = spawn_fake_gateway(state.clone()).await;
|
||||
let client = GatewayClient::connect(ClientOptions::new(endpoint))
|
||||
.await
|
||||
.unwrap();
|
||||
let session = client.session("session-fixture");
|
||||
|
||||
let error = session
|
||||
.authenticate_user(7, "verifier", credential)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(matches!(error, Error::Command(_)), "{error:?}");
|
||||
assert!(!error.to_string().contains(credential));
|
||||
assert!(!format!("{error:?}").contains(credential));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticate_user_scrubs_exact_caller_credential_echoed_in_diagnostic() {
|
||||
// CLI-40: MXAccess can echo the supplied credential back inside its failure
|
||||
|
||||
Reference in New Issue
Block a user