Skip to main content

fallow_types/
extract_security.rs

1//! Security control sites, sanitizers, tainted bindings, skipped callees, and
2//! sink sites.
3
4use super::*;
5
6/// Family of a control pattern observed in a file on an import trace.
7#[derive(
8    Debug,
9    Clone,
10    Copy,
11    PartialEq,
12    Eq,
13    PartialOrd,
14    Ord,
15    serde::Serialize,
16    serde::Deserialize,
17    bitcode::Encode,
18    bitcode::Decode,
19)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21#[serde(rename_all = "kebab-case")]
22pub enum SecurityControlKind {
23    /// Sanitization or escaping before a sink.
24    Sanitization,
25    /// Input validation or schema parsing.
26    Validation,
27    /// Authentication check or middleware.
28    Authentication,
29    /// Authorization or permission check.
30    Authorization,
31}
32
33/// An observed control call or guard pattern, without proof that it protects a sink.
34#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
35pub struct SecurityControlSite {
36    /// Control family.
37    pub kind: SecurityControlKind,
38    /// Flattened callee path or a stable synthetic name for guard-derived
39    /// controls.
40    pub callee_path: String,
41    /// Byte offset of the control span start.
42    pub span_start: u32,
43    /// Byte offset of the control span end.
44    pub span_end: u32,
45}
46
47/// Sanitizer output domain. Kept intentionally narrow so a sanitizer for one
48/// domain cannot suppress a different sink family.
49#[derive(
50    Debug,
51    Clone,
52    Copy,
53    PartialEq,
54    Eq,
55    PartialOrd,
56    Ord,
57    serde::Serialize,
58    serde::Deserialize,
59    bitcode::Encode,
60    bitcode::Decode,
61)]
62pub enum SanitizerScope {
63    /// HTML markup sanitized by DOMPurify-compatible APIs.
64    Html,
65    /// URL or redirect target checked against a literal-backed allowlist.
66    Url,
67    /// Path value checked against a high-confidence containment guard.
68    Path,
69    /// SQL identifier quoted with a helper that doubles embedded identifier quotes.
70    SqlIdentifier,
71}
72
73/// A captured sink argument that is itself a recognized sanitizer call.
74#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
75pub struct SanitizedSinkArg {
76    /// Byte offset of the owning sink span start.
77    pub span_start: u32,
78    /// The positional argument index on the owning sink.
79    pub arg_index: u32,
80    /// The sanitizer output domain for this argument.
81    pub scope: SanitizerScope,
82}
83
84/// A local binding tied to the flattened member-access path it was initialized
85/// from. The analyze layer matches `source_path` against the data-driven source
86/// catalogue; when it matches, `local` is treated as carrying untrusted input.
87///
88/// Captured for two shapes: a direct assignment (`const id = req.query.id` ->
89/// `{ local: "id", source_path: "req.query" }`, the literal-key tail dropped so
90/// the path matches a catalogue prefix) and an object destructure
91/// (`const { id } = req.query` -> `{ local: "id", source_path: "req.query" }`).
92#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
93pub struct TaintedBinding {
94    /// The local binding name introduced by the declarator.
95    pub local: String,
96    /// The flattened object member-access path the binding was sourced from.
97    pub source_path: String,
98    /// Byte offset of the source read (the member-access expression the binding
99    /// was sourced from), so the analyze layer can anchor a taint trace's source
100    /// node at the real read line instead of the module import line. Stored as a
101    /// `u32` (not `Span`) to stay bitcode-encodable for the cache. `0` when no
102    /// concrete read expression is available (synthetic framework-param /
103    /// helper-return bindings), in which case the analyze layer falls back to the
104    /// sink site rather than claiming a spurious line.
105    pub source_span_start: u32,
106}
107
108/// Why a sink-shaped callee could not be flattened into a static catalogue
109/// path.
110#[derive(
111    Debug,
112    Clone,
113    Copy,
114    PartialEq,
115    Eq,
116    PartialOrd,
117    Ord,
118    serde::Serialize,
119    serde::Deserialize,
120    bitcode::Encode,
121    bitcode::Decode,
122)]
123#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
124#[serde(rename_all = "kebab-case")]
125pub enum SkippedSecurityCalleeReason {
126    /// A computed member access such as `client[method](input)`.
127    ComputedMember,
128    /// A dynamic non-member callee such as `(factory())(input)`.
129    DynamicDispatch,
130    /// An assignment target whose object could not be flattened.
131    UnsupportedAssignmentObject,
132}
133
134/// Syntactic expression shape for a skipped security callee.
135#[derive(
136    Debug,
137    Clone,
138    Copy,
139    PartialEq,
140    Eq,
141    PartialOrd,
142    Ord,
143    serde::Serialize,
144    serde::Deserialize,
145    bitcode::Encode,
146    bitcode::Decode,
147)]
148#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
149#[serde(rename_all = "kebab-case")]
150pub enum SkippedSecurityCalleeExpressionKind {
151    /// `obj.prop(...)`.
152    StaticMemberExpression,
153    /// `obj[prop](...)`.
154    ComputedMemberExpression,
155    /// A bare identifier or private identifier callee.
156    Identifier,
157    /// Any other call-like expression that cannot be represented compactly.
158    Other,
159}
160
161/// Span-only diagnostic for a skipped security callee inside one module.
162#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
163pub struct SkippedSecurityCalleeSite {
164    /// Why the callee was skipped.
165    pub reason: SkippedSecurityCalleeReason,
166    /// Compact expression shape of the skipped callee.
167    pub expression_kind: SkippedSecurityCalleeExpressionKind,
168    /// Start byte offset of the skipped callee expression.
169    pub span_start: u32,
170    /// End byte offset of the skipped callee expression.
171    pub span_end: u32,
172}
173
174/// The syntactic shape of a captured security sink site. Category-blind: the
175/// extractor records the shape and the dotted/bare callee path; the analyze
176/// layer matches it against the data-driven catalogue. See
177/// `crates/security/data/security_matchers.toml`.
178#[derive(
179    Debug,
180    Clone,
181    Copy,
182    PartialEq,
183    Eq,
184    serde::Serialize,
185    serde::Deserialize,
186    bitcode::Encode,
187    bitcode::Decode,
188)]
189pub enum SinkShape {
190    /// A call to a bare identifier (e.g. `eval(x)`).
191    Call,
192    /// A call to a dotted member path (e.g. `child_process.exec(x)`).
193    MemberCall,
194    /// An assignment to a member target (e.g. `el.innerHTML = x`).
195    MemberAssign,
196    /// A tagged template expression (e.g. ``sql`...${x}...` ``).
197    TaggedTemplate,
198    /// A JSX attribute value (e.g. `dangerouslySetInnerHTML={x}`).
199    JsxAttr,
200    /// A constructor call (e.g. `new Function("return x")`).
201    NewExpression,
202    /// A static string literal assigned to a secret-shaped identifier or known
203    /// provider credential prefix.
204    SecretLiteral,
205}
206
207/// The shape of the argument captured at a sink site. Category-blind like
208/// [`SinkShape`], but finer-grained: it lets the catalogue matcher require or
209/// exclude specific argument shapes. The discriminator is what distinguishes an
210/// unsafe SQL string concatenation or template-into-`.execute()` from a
211/// safely-parameterized `` sql`${x}` `` tagged template, an object-literal
212/// `.execute({ sql, args })` argument, or a literal-aware sink argument.
213#[derive(
214    Debug,
215    Clone,
216    Copy,
217    PartialEq,
218    Eq,
219    serde::Serialize,
220    serde::Deserialize,
221    bitcode::Encode,
222    bitcode::Decode,
223)]
224pub enum SinkArgKind {
225    /// A template literal with at least one `${...}` substitution (e.g.
226    /// `` `SELECT ${x}` ``). On a `tagged-template` shape this is the tag's
227    /// quasi; on a `call`/`member-call` shape it is the positional argument.
228    TemplateWithSubst,
229    /// A binary `+` string concatenation (e.g. `"SELECT " + x`).
230    Concat,
231    /// An object literal (e.g. `.execute({ sql, args })`, the parameterized form).
232    Object,
233    /// A call expression argument (e.g. `query(buildSql())`).
234    Call,
235    /// A literal argument admitted by a literal-aware security matcher.
236    Literal,
237    /// A zero-argument sink captured because the callee itself is the signal.
238    NoArg,
239    /// Any other non-literal expression (bare identifier, member access, etc.).
240    Other,
241}
242
243/// A captured sink site. The visitor records every existing non-literal call /
244/// member-assign / member-call / tagged-template / jsx-attr sink site, and a
245/// small allowlist of literal-aware sites where the literal value is the signal.
246/// It knows nothing about CWE categories.
247#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
248pub struct SinkSite {
249    /// The syntactic shape of the sink site.
250    pub sink_shape: SinkShape,
251    /// The flattened dotted/bare callee or member path.
252    pub callee_path: String,
253    /// The positional argument index. For zero-argument captures this is 0.
254    pub arg_index: u32,
255    /// Whether the relevant argument is non-literal. Existing non-literal
256    /// catalogue rows require this to remain true.
257    pub arg_is_non_literal: bool,
258    /// The finer-grained shape of the captured argument. Lets the catalogue
259    /// require unsafe shapes (concat / template-with-substitution / literal /
260    /// no-arg) and exclude safe ones (object literal, the parameterized form).
261    /// See [`SinkArgKind`].
262    pub arg_kind: SinkArgKind,
263    /// Literal argument value for literal-aware rows.
264    pub arg_literal: Option<SinkLiteralValue>,
265    /// Risky regex fragment for structural ReDoS candidates.
266    pub regex_pattern: Option<String>,
267    /// Static object-literal properties for option-object rows.
268    pub object_properties: Vec<SinkObjectProperty>,
269    /// Static top-level object-literal keys, including keys whose values are not
270    /// literal. Used by missing-option rows that only need key presence.
271    pub object_property_keys: Vec<String>,
272    /// Whether [`object_property_keys`](Self::object_property_keys) is complete.
273    /// False for non-object arguments and object literals with spread or
274    /// non-static keys, where a missing-key claim would be speculative.
275    pub object_property_keys_complete: bool,
276    /// Identifier names referenced anywhere inside the captured non-literal sink
277    /// argument, or contextual names for zero-argument captures such as a
278    /// token-like `Math.random()` assignment target. Deduped in source order.
279    /// Used by the analyze layer to back-trace the sink argument to a known
280    /// untrusted source or to apply narrow context gates. Intra-module,
281    /// name-based, conservative; it is never a taint proof.
282    pub arg_idents: Vec<String>,
283    /// Flattened static member paths referenced inside the captured non-literal
284    /// sink argument. Includes both the full path and source-object path for
285    /// leaf reads (`process.env.SECRET` records `process.env.SECRET` and
286    /// `process.env`) so direct source expressions can be matched without an
287    /// intermediate local binding.
288    pub arg_source_paths: Vec<String>,
289    /// Byte offset of the sink span start. Stored as `u32` (not `Span`) so the
290    /// struct is bitcode-encodable and can be persisted directly in the cache.
291    pub span_start: u32,
292    /// Byte offset of the sink span end.
293    pub span_end: u32,
294    /// The arg-0 URL string literal of a network-shaped call (`fetch`, `axios.*`,
295    /// `got`, ...), captured so the `secret-to-network` category (#890) can carry
296    /// a destination-host signal on its candidate: `Some(literal)` when the
297    /// destination is a static string literal (almost always intended auth, e.g.
298    /// the credential's own provider), `None` when it is dynamic (the suspicious
299    /// case). `None` for non-call sinks and calls with no arg 0.
300    pub url_arg_literal: Option<String>,
301    /// URL construction shape for URL-like sink arguments when the extractor can
302    /// classify it syntactically. `None` for non-URL sinks and URL expressions
303    /// whose shape is not visible at the sink.
304    pub url_shape: Option<SecurityUrlShape>,
305    /// Options-object metadata of the call, on the command argument and the
306    /// argument array of a call whose options position the extractor knows. `None` for every other
307    /// sink, which means that the options are unknown.
308    pub call_options: Option<Box<SinkCallOptions>>,
309}
310
311impl SinkSite {
312    /// Reconstruct the source span from the stored byte offsets.
313    #[must_use]
314    pub fn span(&self) -> Span {
315        Span::new(self.span_start, self.span_end)
316    }
317}