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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion sv1/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sv1_api"
version = "7.0.0"
version = "7.0.1"
authors = ["The Stratum V2 Developers"]
edition = "2021"
readme = "README.md"
Expand Down
124 changes: 117 additions & 7 deletions sv1/src/json_rpc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! https://www.jsonrpc.org/specification#response_object
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, fmt::Display};
use serde_json::Value;
use std::{borrow::Cow, fmt, fmt::Display};

#[derive(Clone, Serialize, Debug)]
#[serde(untagged)]
Expand Down Expand Up @@ -55,17 +56,85 @@ impl Display for Message {
}
}

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
/// Printed in place of credentials a peer sent.
pub(crate) const REDACTED: &str = "<redacted>";

/// Formats as [`REDACTED`], for `Debug` impls of fields that hold credentials.
pub(crate) struct Redacted;

impl fmt::Debug for Redacted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(REDACTED)
}
}

/// Returns `params` with the credentials a request for `method` can carry replaced by
/// [`REDACTED`], so that they never reach formatted output.
///
/// Those are everything but the worker name in `mining.authorize`, and `info.connection-url` in
/// `mining.configure`, which can embed `user:password@`.
pub(crate) fn redact_params<'a>(method: &str, params: &'a Value) -> Cow<'a, Value> {
match method {
"mining.authorize" => Cow::Owned(match params.as_array() {
Some(params) => params
.iter()
.enumerate()
.map(|(i, param)| {
if i == 0 {
param.clone()
} else {
REDACTED.into()
}
})
.collect(),
None => REDACTED.into(),
}),
"mining.configure" => {
let mut params = params.clone();
redact_connection_url(&mut params);
Cow::Owned(params)
}
_ => Cow::Borrowed(params),
}
}

fn redact_connection_url(value: &mut Value) {
match value {
Value::Array(values) => values.iter_mut().for_each(redact_connection_url),
Value::Object(fields) => {
for (key, value) in fields.iter_mut() {
if key == "info.connection-url" {
*value = REDACTED.into();
} else {
redact_connection_url(value);
}
}
}
_ => {}
}
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StandardRequest {
pub id: u64,
pub method: String,
pub params: serde_json::Value,
}

impl fmt::Debug for StandardRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StandardRequest")
.field("id", &self.id)
.field("method", &self.method)
.field("params", &redact_params(&self.method, &self.params))
.finish()
}
}

impl fmt::Display for StandardRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let params =
serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string());
let params = redact_params(&self.method, &self.params);
let params = serde_json::to_string_pretty(&params).unwrap_or_else(|_| params.to_string());
write!(
f,
"{{ id: {}, method: {}, params: {} }}",
Expand All @@ -74,16 +143,25 @@ impl fmt::Display for StandardRequest {
}
}

#[derive(Clone, Serialize, Deserialize, Debug)]
#[derive(Clone, Serialize, Deserialize)]
pub struct Notification {
pub method: String,
pub params: serde_json::Value,
}

impl fmt::Debug for Notification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Notification")
.field("method", &self.method)
.field("params", &redact_params(&self.method, &self.params))
.finish()
}
}

impl fmt::Display for Notification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let params =
serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string());
let params = redact_params(&self.method, &self.params);
let params = serde_json::to_string_pretty(&params).unwrap_or_else(|_| params.to_string());

write!(f, "{{ method: \"{}\", params: {} }}", self.method, params)
}
Expand Down Expand Up @@ -327,4 +405,36 @@ mod tests {
.unwrap();
assert!(matches!(success, Message::OkResponse(_)));
}

#[test]
fn formatted_requests_redact_credentials() {
for wire in [
r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2"]}"#,
r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2","extra"]}"#,
r#"{"id":1,"method":"mining.authorize","params":{"password":"hunter2"}}"#,
r#"{"id":null,"method":"mining.authorize","params":["worker","hunter2"]}"#,
r#"{"id":2,"method":"mining.configure","params":[["info"],{"info.connection-url":"stratum+tcp://worker:hunter2@pool.example:3333"}]}"#,
] {
let message: Message = serde_json::from_str(wire).unwrap();
for formatted in [format!("{message}"), format!("{message:?}")] {
assert!(!formatted.contains("hunter2"), "{formatted}");
assert!(formatted.contains(REDACTED), "{formatted}");
}
}
}

#[test]
fn formatted_requests_keep_other_params() {
let message: Message = serde_json::from_str(
r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2"]}"#,
)
.unwrap();
assert!(format!("{message}").contains("worker"));

let message: Message =
serde_json::from_str(r#"{"id":1,"method":"mining.subscribe","params":["agent"]}"#)
.unwrap();
assert!(format!("{message}").contains("agent"));
assert!(format!("{message:?}").contains("agent"));
}
}
43 changes: 43 additions & 0 deletions sv1/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1056,4 +1056,47 @@ mod tests {
let msg: Message = serde_json::from_value(raw).unwrap();
assert!(Method::try_from(msg).is_err());
}

#[test]
fn credentials_never_reach_formatted_output() {
let secret = "hunter2";
let authorize = client_to_server::Authorize {
id: 1,
name: "worker".to_string(),
password: secret.to_string(),
};
let wrapped = Error::InvalidReceiver(Box::new(Method::Client2Server(
methods::Client2Server::Authorize(authorize.clone()),
)));
for formatted in [
format!("{authorize}"),
format!("{authorize:?}"),
format!("{wrapped}"),
format!("{wrapped:?}"),
] {
assert!(!formatted.contains(secret), "{formatted}");
}

for wire in [
r#"{"id":1,"method":"mining.authorize","params":["worker","hunter2",1]}"#,
r#"{"id":1,"method":"mining.authorize","params":{"password":"hunter2"}}"#,
r#"{"id":2,"method":"mining.configure","params":[["info"],{"info.connection-url":"stratum+tcp://worker:hunter2@pool.example:3333"}]}"#,
r#"{"id":2,"method":"mining.configure","params":{"info.connection-url":"stratum+tcp://worker:hunter2@pool.example:3333"}}"#,
] {
let message: Message = serde_json::from_str(wire).unwrap();
let formatted = match methods::Client2Server::try_from(message) {
Ok(methods::Client2Server::Configure(configure)) => {
vec![format!("{configure}"), format!("{configure:?}")]
}
Ok(request) => vec![format!("{request:?}")],
Err(error) => {
let error = Error::from(error);
vec![format!("{error}"), format!("{error:?}")]
}
};
for formatted in formatted {
assert!(!formatted.contains(secret), "{formatted}");
}
}
}
}
49 changes: 41 additions & 8 deletions sv1/src/methods/client_to_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::fmt;

use crate::{
error::Error,
json_rpc::{JsonRpcError, Message, Response, StandardRequest},
json_rpc::{redact_params, JsonRpcError, Message, Redacted, Response, StandardRequest},
methods::ParsingMethodError,
utils::{Extranonce, HexU32Be, VERSION_ROLLING_MASK},
};
Expand All @@ -24,13 +24,23 @@ use quickcheck_macros;
///
/// The result from an authorize request is usually true (successful), or false.
/// The password may be omitted if the server does not require passwords.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Clone, PartialEq, Eq)]
pub struct Authorize {
pub id: u64,
pub name: String,
pub password: String,
}

impl fmt::Debug for Authorize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Authorize")
.field("id", &self.id)
.field("name", &self.name)
.field("password", &Redacted)
.finish()
}
}

impl fmt::Display for Authorize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
Expand Down Expand Up @@ -71,12 +81,18 @@ impl TryFrom<StandardRequest> for Authorize {
Some(params) => {
let (name, password) = match &params[..] {
[JString(a), JString(b)] => (a.into(), b.into()),
_ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)),
_ => {
return Err(ParsingMethodError::wrong_args_from_value(
redact_params(&msg.method, &msg.params).into_owned(),
))
}
};
let id = msg.id;
Ok(Self { id, name, password })
}
None => Err(ParsingMethodError::not_array_from_value(msg.params)),
None => Err(ParsingMethodError::not_array_from_value(
redact_params(&msg.method, &msg.params).into_owned(),
)),
}
}
}
Expand Down Expand Up @@ -647,9 +663,11 @@ impl fmt::Display for ConfigureExtension {
impl ConfigureExtension {
pub fn from_value(val: &Value) -> Result<Vec<ConfigureExtension>, ParsingMethodError> {
let mut res = vec![];
let root = val
.as_array()
.ok_or_else(|| ParsingMethodError::not_array_from_value(val.clone()))?;
let root = val.as_array().ok_or_else(|| {
ParsingMethodError::not_array_from_value(
redact_params("mining.configure", val).into_owned(),
)
})?;
if root.is_empty() {
return Err(ParsingMethodError::Todo);
};
Expand Down Expand Up @@ -841,7 +859,7 @@ impl From<VersionRollingParams> for serde_json::Map<String, Value> {
}
}

#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct InfoParams {
pub connection_url: Option<String>,
#[allow(dead_code)]
Expand All @@ -852,6 +870,21 @@ pub struct InfoParams {
pub sw_version: Option<String>,
}

impl fmt::Debug for InfoParams {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// The connection URL can embed `user:password@`.
f.debug_struct("InfoParams")
.field(
"connection_url",
&self.connection_url.as_ref().map(|_| Redacted),
)
.field("hw_id", &self.hw_id)
.field("hw_version", &self.hw_version)
.field("sw_version", &self.sw_version)
.finish()
}
}

impl From<InfoParams> for serde_json::Map<String, Value> {
fn from(info: InfoParams) -> Self {
let mut params = serde_json::Map::new();
Expand Down
Loading