use super::{cell, fetch, number_of, text_of, ServerSettings};
use crate::cli::server::ProcessesArgs;
use crate::error::Result;
use crate::output::{Envelope, Gap, Row};
use crate::sql::strip;
use mysql_async::{params, Conn};
use serde_json::{json, Value};
const LISTING: &str = "SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO \
FROM information_schema.PROCESSLIST \
WHERE (:user IS NULL OR USER = :user) \
AND (:min_seconds IS NULL OR TIME >= :min_seconds) \
AND (:command IS NULL OR COMMAND = :command) \
ORDER BY TIME DESC, ID ASC";
pub async fn run(
connection: &mut Conn,
args: &ProcessesArgs,
own_connection_id: u64,
_settings: &ServerSettings,
) -> Result<Envelope> {
let source = fetch(
connection,
LISTING,
params! {
"user" => args.user.clone(),
"min_seconds" => args.min_seconds,
"command" => args.state.map(crate::cli::server::ConnectionState::command_word),
},
)
.await
.map_err(|failure| super::observation_failure(failure, "PROCESS", "other-connections"))?;
let rows = shape_all(&source);
let envelope = Envelope::new(
"server processes",
json!({
"own_connection_id": own_connection_id,
"rows": rows,
}),
);
Ok(match narrowing(&source, own_connection_id) {
Some(gap) => envelope.with_gap(gap),
None => envelope,
})
}
#[must_use]
pub fn shape_all(source: &[Row]) -> Vec<Row> {
source.iter().map(shape_one).collect()
}
fn shape_one(row: &Row) -> Row {
let mut shaped = Row::new();
shaped.insert(
"id".to_owned(),
cell(row, "ID").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"user".to_owned(),
cell(row, "USER").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"host".to_owned(),
cell(row, "HOST").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"database".to_owned(),
cell(row, "DB").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"command".to_owned(),
cell(row, "COMMAND").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"seconds".to_owned(),
cell(row, "TIME").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"state".to_owned(),
cell(row, "STATE").cloned().unwrap_or(Value::Null),
);
shaped.insert("statement".to_owned(), redact(cell(row, "INFO")));
shaped
}
#[must_use]
pub fn redact(statement: Option<&Value>) -> Value {
match statement {
None | Some(Value::Null) => Value::Null,
Some(other) => json!(strip::strip(&text_of(Some(other))).text().to_owned()),
}
}
#[must_use]
pub fn narrowing(source: &[Row], own_connection_id: u64) -> Option<Gap> {
let own_id = i64::try_from(own_connection_id).ok()?;
let own_user = source
.iter()
.find(|row| number_of(cell(row, "ID")) == Some(own_id))
.map(|row| text_of(cell(row, "USER")))?;
let all_ours = source
.iter()
.all(|row| text_of(cell(row, "USER")) == own_user);
all_ours.then(|| {
Gap::new(
"other_connections",
"possibly_restricted",
format!(
"every listed connection belongs to `{own_user}`, which is what a credential \
without the right to observe other connections would see"
),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn listed(id: i64, user: &str, statement: Value) -> Row {
let mut row = Row::new();
row.insert("ID".to_owned(), json!(id));
row.insert("USER".to_owned(), json!(user));
row.insert("HOST".to_owned(), json!("localhost"));
row.insert("DB".to_owned(), json!("sales"));
row.insert("COMMAND".to_owned(), json!("Query"));
row.insert("TIME".to_owned(), json!(12));
row.insert("STATE".to_owned(), json!("Sending data"));
row.insert("INFO".to_owned(), statement);
row
}
#[test]
fn an_observed_statement_keeps_its_shape_and_loses_its_values() {
let redacted = redact(Some(&json!("SELECT * FROM users WHERE token = 'sekret'")));
let text = text_of(Some(&redacted));
assert!(
!text.contains("sekret"),
"a literal must not survive: {text}"
);
assert!(text.contains("SELECT"), "the shape must survive: {text}");
assert!(text.contains("users"), "the object must survive: {text}");
}
#[test]
fn an_idle_connection_carries_no_statement() {
assert_eq!(redact(Some(&Value::Null)), Value::Null);
assert_eq!(redact(None), Value::Null);
}
#[test]
fn the_shaped_row_carries_every_published_field() {
let rows = shape_all(&[listed(7, "app", json!("SELECT 1"))]);
for field in [
"id",
"user",
"host",
"database",
"command",
"seconds",
"state",
"statement",
] {
assert!(rows[0].contains_key(field), "{field} is missing");
}
}
#[test]
fn a_listing_of_only_our_own_connections_declares_the_narrowing() {
let source = vec![listed(7, "app", Value::Null), listed(9, "app", Value::Null)];
let gap = narrowing(&source, 7).expect("the narrowing must be declared");
assert_eq!(gap.object, "other_connections");
assert!(gap.detail.contains("app"));
}
#[test]
fn a_listing_carrying_another_user_declares_nothing() {
let source = vec![
listed(7, "app", Value::Null),
listed(9, "reporting", Value::Null),
];
assert!(narrowing(&source, 7).is_none());
}
}