Skip to main content

ruso_runtime/runtime/
context.rs

1//! The mutable state a single script run carries: variables, stored probe
2//! responses, open sockets, collected evidence, and the loop stack.
3//!
4//! One [`Context`] exists per execution. The executor threads it through every
5//! instruction; nothing else in the runtime holds state between instructions.
6
7use std::collections::HashMap;
8
9use crate::runtime::report::{Finding, Report};
10use crate::runtime::response::ProbeResponse;
11use crate::runtime::session::ProbeSession;
12use crate::runtime::spec::{CheckMetadata, ProgramSpec};
13
14/// What a script variable can hold.
15///
16/// RSL has two kinds of variable: a plain string (`set x = "…"`) and a list
17/// (`set xs = ["a", "b"]`, or the loop variable of a `for`).
18#[derive(Debug, Clone, PartialEq)]
19pub enum VariableValue {
20    /// A single string. Interpolation (`{{ x }}`) substitutes this directly.
21    String(String),
22    /// An ordered list of strings, iterated by `for` and expanded by
23    /// list-valued interpolation.
24    List(Vec<String>),
25}
26
27impl VariableValue {
28    /// The string behind a [`VariableValue::String`], or `None` for a list.
29    ///
30    /// Call sites that interpolate a variable into a request use this to
31    /// reject a list where a scalar is required.
32    pub fn as_string(&self) -> Option<&str> {
33        match self {
34            Self::String(value) => Some(value),
35            Self::List(_) => None,
36        }
37    }
38}
39
40/// The per-iteration bookkeeping of an active loop.
41#[derive(Debug)]
42pub enum LoopState {
43    /// A `for <item> in <list>` loop.
44    ForEach {
45        /// Name of the loop variable rebound on each iteration.
46        item: String,
47        /// The values being iterated, snapshotted when the loop was entered.
48        values: Vec<String>,
49        /// Index of the current iteration into `values`.
50        index: usize,
51        /// Whatever `item` was bound to before the loop, restored on exit so a
52        /// loop variable cannot leak into the enclosing scope.
53        previous: Option<VariableValue>,
54    },
55}
56
57/// One entry on the loop stack: the loop's state plus the jump targets the
58/// control-flow opcodes resolve against.
59#[derive(Debug)]
60pub struct LoopFrame {
61    /// Iteration state for this loop.
62    pub state: LoopState,
63    /// Program counter of the loop header, re-entered on `loop_back`.
64    pub head_pc: usize,
65    /// Where `continue` jumps to.
66    pub continue_pc: usize,
67    /// Where `break` (and normal exhaustion) jumps to.
68    pub end_pc: usize,
69}
70
71/// All mutable state of one script run.
72#[derive(Debug)]
73pub struct Context {
74    /// Variables currently in scope, by name.
75    pub variables: HashMap<String, VariableValue>,
76    /// Responses of probes that have been sent, keyed by probe name. A matcher
77    /// like `home.status == 200` reads from here.
78    pub responses: HashMap<String, ProbeResponse>,
79    /// Live TCP/UDP sessions, keyed by probe name, kept open so a later `send`
80    /// to the same probe reuses the connection.
81    pub sessions: HashMap<String, ProbeSession>,
82    /// The check's declared metadata (name, severity, impact, …), used to build
83    /// the finding.
84    pub metadata: CheckMetadata,
85    /// The report being accumulated; receives the finding at the end of the run.
86    pub report: Report,
87    /// Proof strings collected by `evidence` instructions so far.
88    pub evidence: Vec<String>,
89    /// Delay inserted between retry attempts, set by `retry_delay`.
90    pub retry_delay: Option<std::time::Duration>,
91    /// Set when `fail` ran or a probe errored fatally; the run is reported as
92    /// failed rather than clean.
93    pub failed: bool,
94    /// Whether every matcher evaluated so far has held. Starts `true` — a
95    /// script with no matchers at all is a match.
96    pub matched: bool,
97    /// When false, `stop` was hit — do not emit a finding even if matchers passed.
98    pub emit_finding: bool,
99    /// Active loops, innermost last.
100    pub loop_stack: Vec<LoopFrame>,
101}
102
103impl Default for Context {
104    fn default() -> Self {
105        Self {
106            variables: HashMap::new(),
107            responses: HashMap::new(),
108            sessions: HashMap::new(),
109            metadata: CheckMetadata::default(),
110            report: Report::default(),
111            evidence: Vec::new(),
112            retry_delay: None,
113            failed: false,
114            matched: true,
115            emit_finding: true,
116            loop_stack: Vec::new(),
117        }
118    }
119}
120
121impl Context {
122    /// A fresh context seeded with the program's declared metadata.
123    pub fn from_spec(spec: &ProgramSpec) -> Self {
124        Self {
125            metadata: spec.metadata.clone(),
126            ..Default::default()
127        }
128    }
129
130    /// Bind `name` to a string value, replacing any previous binding.
131    pub fn set_variable(&mut self, name: impl Into<String>, value: impl Into<String>) {
132        self.variables
133            .insert(name.into(), VariableValue::String(value.into()));
134    }
135
136    /// Bind `name` to a list value, replacing any previous binding.
137    pub fn set_list_variable(&mut self, name: impl Into<String>, values: Vec<String>) {
138        self.variables
139            .insert(name.into(), VariableValue::List(values));
140    }
141
142    /// Put a saved binding back, or remove the variable when there was none.
143    ///
144    /// This is how a loop undoes its loop variable on exit: `value` is whatever
145    /// [`LoopState::ForEach::previous`] held.
146    pub fn restore_or_remove_variable(
147        &mut self,
148        name: impl Into<String>,
149        value: Option<VariableValue>,
150    ) {
151        let name = name.into();
152        match value {
153            Some(value) => {
154                self.variables.insert(name, value);
155            }
156            None => {
157                self.variables.remove(&name);
158            }
159        }
160    }
161
162    /// The stored response of probe `name`, if it has been sent.
163    pub fn response(&self, name: &str) -> Option<&ProbeResponse> {
164        self.responses.get(name)
165    }
166
167    /// Record a probe's response, replacing an earlier one under the same name
168    /// (a re-sent or retried probe reports its latest attempt).
169    pub fn store_response(&mut self, name: impl Into<String>, response: ProbeResponse) {
170        self.responses.insert(name.into(), response);
171    }
172
173    /// Make the response stored under `from` also reachable as `alias`.
174    ///
175    /// Used so an inline probe can be referred to by the name the script gave
176    /// it. A no-op when `from` has no stored response.
177    pub fn alias_response(&mut self, from: &str, alias: impl Into<String>) {
178        if let Some(response) = self.responses.get(from).cloned() {
179            self.responses.insert(alias.into(), response);
180        }
181    }
182
183    /// Drop every open socket session, closing the connections.
184    pub fn close_sessions(&mut self) {
185        self.sessions.clear();
186    }
187
188    /// Turn the run into a finding on the report, if it earned one.
189    ///
190    /// Nothing is emitted when a matcher failed (`matched == false`) or the
191    /// script ran `stop` (`emit_finding == false`). Collected evidence is moved
192    /// onto the finding.
193    pub fn finalize_finding(&mut self) {
194        if !self.matched || !self.emit_finding {
195            return;
196        }
197        let evidence = std::mem::take(&mut self.evidence);
198        if let Some(finding) = Finding::from_metadata(&self.metadata, evidence) {
199            self.report.set_finding(finding);
200        }
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use crate::contract::Severity;
207
208    use super::Context;
209
210    #[test]
211    fn finalize_emits_finding_when_matched() {
212        let mut ctx = Context {
213            matched: true,
214            ..Context::default()
215        };
216        ctx.metadata.name = Some("Exposed .env".into());
217        ctx.metadata.severity = Some(Severity::High);
218        ctx.evidence.push("DB_PASSWORD=secret".into());
219        ctx.finalize_finding();
220        assert_eq!(ctx.report.findings.len(), 1);
221        assert_eq!(ctx.report.findings[0].name, "Exposed .env");
222        assert_eq!(ctx.report.findings[0].severity, Severity::High);
223    }
224
225    #[test]
226    fn finalize_skips_when_match_chain_failed() {
227        let mut ctx = Context {
228            matched: false,
229            ..Context::default()
230        };
231        ctx.metadata.name = Some("Should not emit".into());
232        ctx.finalize_finding();
233        assert!(ctx.report.findings.is_empty());
234    }
235
236    #[test]
237    fn finalize_skips_after_stop() {
238        let mut ctx = Context {
239            matched: true,
240            emit_finding: false,
241            ..Context::default()
242        };
243        ctx.metadata.name = Some("Stopped".into());
244        ctx.finalize_finding();
245        assert!(ctx.report.findings.is_empty());
246    }
247}