agentmux_srv_core/backend/rpc/
action_record.rs1use serde_json::Value;
15
16use super::actor::{actor_of, Actor};
17use crate::backend::rpc_types::RpcContext;
18
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
21pub struct Target {
22 pub agent: Option<String>,
23 pub block_id: Option<String>,
24 pub subject: Option<String>,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ActionRecord {
30 pub actor: Actor,
31 pub command: String,
32 pub target: Target,
33 pub request_id: String,
34 pub error: Option<String>,
36}
37
38const MAX_FIELD: usize = 200;
40
41const AGENT_KEYS: &[&str] = &["agentid", "agentname", "agent", "agentslug", "slug"];
45const BLOCK_KEYS: &[&str] = &["blockid", "block"];
46const SUBJECT_KEYS: &[&str] = &[
47 "id", "widgetid", "accountid", "definitionid", "providerid", "provider", "name", "templateid", "bundleid", "skillid",
48 "droneid", "jobid", "groupid", "connname", "host", "path", "oldpath", "newpath", "pid", "signal",
49];
50
51fn fold(key: &str) -> String {
52 key.chars().filter(|c| *c != '_' && *c != '-').collect::<String>().to_lowercase()
53}
54
55fn text_of(v: &Value) -> Option<String> {
56 let s = match v {
57 Value::String(s) => s.trim().to_string(),
58 Value::Number(n) => n.to_string(),
59 _ => return None,
60 };
61 (!s.is_empty()).then(|| s.chars().take(MAX_FIELD).collect())
62}
63
64pub fn target_of(data: &Value) -> Target {
66 let Some(map) = data.as_object() else { return Target::default() };
67 let find = |keys: &[&str]| -> Option<String> {
68 keys.iter().find_map(|want| map.iter().find(|(k, _)| fold(k) == *want).and_then(|(_, v)| text_of(v)))
69 };
70 let subjects: Vec<String> = SUBJECT_KEYS
71 .iter()
72 .filter_map(|want| map.iter().find(|(k, _)| fold(k) == *want).and_then(|(k, v)| text_of(v).map(|t| format!("{}={t}", fold(k)))))
73 .collect();
74 Target {
75 agent: find(AGENT_KEYS),
76 block_id: find(BLOCK_KEYS),
77 subject: (!subjects.is_empty()).then(|| subjects.join(" ").chars().take(MAX_FIELD * 2).collect()),
78 }
79}
80
81fn target_for(command: &str, data: &Value) -> Target {
84 use crate::backend::rpc_types::{COMMAND_REMOTE_SET_CONFIG, COMMAND_SET_CONFIG};
85 let mut target = target_of(data);
86 if command == COMMAND_SET_CONFIG {
87 target.subject = data.as_object().map(|keys| format!("keys={}", crate::backend::settings_consent::key_names(keys)));
88 } else if command == COMMAND_REMOTE_SET_CONFIG {
89 let connection = data.get("connection").and_then(Value::as_str).unwrap_or_default();
90 let keys = data.get("values").and_then(Value::as_object).map(crate::backend::settings_consent::key_names);
91 target.subject = Some(format!("connection={} keys={}", connection.chars().take(MAX_FIELD).collect::<String>(), keys.unwrap_or_default()));
92 } else if let Some(device) = command.strip_prefix("viewer.").and(data.get("device_id")).and_then(text_of) {
93 let set = ["can_send", "resume"].iter().find_map(|k| data.get(*k).and_then(Value::as_bool).map(|v| format!(" {k}={v}")));
95 target.subject = Some(format!("device={device}{}", set.unwrap_or_default()));
96 }
97 target
98}
99
100const ANSWERS_OK_FLAG: &[&str] = &["agent.kill-process", "agent.kill-tree"];
102
103pub fn outcome_of_response(command: &str, response: Option<&Value>) -> Result<(), String> {
106 let refused = ANSWERS_OK_FLAG.contains(&command)
107 && response.and_then(|r| r.get("ok")).and_then(Value::as_bool) == Some(false);
108 if refused { Err("not done: the command answered ok=false".to_string()) } else { Ok(()) }
109}
110
111pub fn after_call(command: &str, data: &Value, ctx: &RpcContext, request_id: &str, outcome: &Result<(), String>) {
113 let actor = actor_of(ctx);
114 if !super::action_commands::is_recorded(command, actor.is_operator()) || super::action_commands::is_a_read(command, data) {
115 return;
116 }
117 let record = ActionRecord {
118 actor,
119 command: command.to_string(),
120 target: target_for(command, data),
121 request_id: request_id.to_string(),
122 error: outcome.as_ref().err().map(|e| e.chars().take(MAX_FIELD).collect()),
123 };
124 crate::backend::reactive::get_global_handler().audit_action(&record);
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130 use serde_json::json;
131
132 #[test]
133 fn the_target_is_read_from_identifying_fields_in_any_spelling() {
134 let t = target_of(&json!({"blockId": "b1", "pid": 42, "agent_id": "opaz", "signal": "SIGKILL"}));
135 assert_eq!((t.agent.as_deref(), t.block_id.as_deref()), (Some("opaz"), Some("b1")));
136 assert_eq!(t.subject.as_deref(), Some("pid=42 signal=SIGKILL"));
137 let t = target_of(&json!({"block_id": "b2", "id": "acme.widget"}));
138 assert_eq!((t.block_id.as_deref(), t.subject.as_deref()), (Some("b2"), Some("id=acme.widget")));
139 }
140
141 #[test]
142 fn a_settings_write_is_recorded_with_the_names_of_the_settings_and_never_their_values() {
143 let write = json!({"messaging:telegram:token": "s3cret-value", "term:fontsize": 12});
144 let subject = target_for("setconfig", &write).subject.unwrap();
145 assert!(subject.starts_with("keys=") && subject.contains("messaging:telegram:token") && subject.contains("term:fontsize"));
146 assert!(!subject.contains("s3cret-value"), "{subject}");
147 assert_eq!(target_for("agent.stop", &json!({"agent_id": "a1"})).subject, None);
148 }
149
150 #[test]
151 fn a_remotes_settings_write_is_recorded_with_the_connection_and_the_names_and_never_the_values() {
152 let write = json!({"connection": "ops@build-host", "values": {"ssh:identityfile": "C:/keys/s3cret", "conn:wshenabled": true}});
153 let subject = target_for("remotesetconfig", &write).subject.unwrap();
154 assert!(subject.starts_with("connection=ops@build-host keys="), "{subject}");
155 assert!(subject.contains("ssh:identityfile") && subject.contains("conn:wshenabled"), "{subject}");
156 assert!(!subject.contains("s3cret") && !subject.contains("true"), "{subject}");
157 }
158
159 #[test]
160 fn a_change_to_a_paired_device_names_the_device_and_the_switch_set() {
161 let subject = |cmd: &str, data: Value| target_for(cmd, &data).subject;
162 assert_eq!(subject("viewer.can-send", json!({"device_id": "d1", "can_send": true})).as_deref(), Some("device=d1 can_send=true"));
163 assert_eq!(subject("viewer.stop-watching", json!({"device_id": "d1", "resume": false})).as_deref(), Some("device=d1 resume=false"));
164 assert_eq!(subject("viewer.stop-watching", json!({"device_id": "d1"})).as_deref(), Some("device=d1"));
165 assert_eq!(subject("viewer.revoke", json!({"device_id": "d1"})).as_deref(), Some("device=d1"));
166 assert_eq!(super::super::action_commands::policy("viewer.can-send"), Some(super::super::action_commands::Policy::Always));
167 }
168
169 #[test]
170 fn a_kill_that_answers_not_ok_is_recorded_as_not_done() {
171 let no = json!({"ok": false});
172 assert!(outcome_of_response("agent.kill-tree", Some(&no)).is_err());
173 assert!(outcome_of_response("agent.kill-process", Some(&no)).is_err());
174 assert!(outcome_of_response("agent.kill-tree", Some(&json!({"ok": true}))).is_ok());
175 assert!(outcome_of_response("agent.kill-tree", None).is_ok());
176 assert!(outcome_of_response("agent.send", Some(&no)).is_ok());
177 }
178
179 #[test]
180 fn contents_keys_and_tokens_are_never_read() {
181 let t = target_of(&json!({
182 "id": "acct-1", "clientSecret": "s3cret", "token": "t0ken", "apiKey": "k", "password": "p",
183 "content": "file body", "message": "hello", "data": "x", "env": {"A": "b"}, "value": "v"
184 }));
185 let all = format!("{t:?}");
186 for secret in ["s3cret", "t0ken", "file body", "hello", "\"k\"", "\"p\""] {
187 assert!(!all.contains(secret), "{secret} leaked into {all}");
188 }
189 assert_eq!(t.subject.as_deref(), Some("id=acct-1"));
190 }
191
192 #[test]
193 fn a_long_or_empty_field_is_cut_or_dropped() {
194 let t = target_of(&json!({"id": "x".repeat(900), "agentId": " ", "name": 7}));
195 assert_eq!(t.agent, None);
196 assert!(t.subject.unwrap().len() <= MAX_FIELD * 2);
197 assert_eq!(target_of(&Value::Null), Target::default());
198 assert_eq!(target_of(&json!("a string")), Target::default());
199 }
200}