Skip to main content

rightkit_browser/
fixture_protocol.rs

1//! Closed, source-only protocol for browser fixtures.
2//!
3//! Fixture source digests hash compact JSON for `{"files":[...]}`. Files are
4//! sorted by their validated UTF-8 path bytes; each object contains `body` as
5//! an array of byte integers, `contentType`, and `path`. `serde_json::Value`
6//! Objects are recursively rebuilt in lexicographic key order before compact
7//! serialization, so this stays stable even when serde_json's preserve_order
8//! feature is enabled. The resulting SHA-256 is lowercase hex prefixed by
9//! `sha256:`.
10
11use serde::{Deserialize, Serialize};
12use serde_json::{Map, Value};
13use sha2::{Digest, Sha256};
14use std::collections::BTreeSet;
15use thiserror::Error;
16use url::Url;
17
18pub const FIXTURE_SCHEMA: &str = "rightkit.browser.fixture-intent.v1";
19pub(crate) const MAX_FIXTURE_FILES: usize = 64;
20pub(crate) const MAX_FIXTURE_BYTES: usize = 16 * 1024 * 1024;
21
22const MAX_STRING_BYTES: usize = 2048;
23const MAX_ACTIONS: usize = 8;
24const MAX_EXPIRY_MS: u64 = 30_000;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct FixtureFile {
28    pub path: String,
29    pub content_type: String,
30    pub body: Vec<u8>,
31}
32
33#[derive(Debug, Clone)]
34pub struct FixtureBundle {
35    fixture_id: String,
36    source_digest: String,
37    files: Vec<FixtureFile>,
38}
39
40impl FixtureBundle {
41    pub fn verify(
42        fixture_id: impl Into<String>,
43        expected_source_digest: &str,
44        mut files: Vec<FixtureFile>,
45    ) -> Result<Self, FixtureError> {
46        let fixture_id = fixture_id.into();
47        validate_id("fixture_id", &fixture_id)?;
48        validate_digest("fixture_source_digest", expected_source_digest)?;
49        validate_files(&files)?;
50        files.sort_by(|a, b| a.path.as_bytes().cmp(b.path.as_bytes()));
51        let source_digest = Self::source_digest(&files)?;
52        if source_digest != expected_source_digest {
53            return Err(FixtureError::Invalid(
54                "fixture source digest does not match files".into(),
55            ));
56        }
57        Ok(Self {
58            fixture_id,
59            source_digest,
60            files,
61        })
62    }
63
64    pub fn source_digest(files: &[FixtureFile]) -> Result<String, FixtureError> {
65        validate_files(files)?;
66        let mut ordered: Vec<&FixtureFile> = files.iter().collect();
67        ordered.sort_by(|a, b| a.path.as_bytes().cmp(b.path.as_bytes()));
68        let value = Value::Object(
69            [(
70                "files".to_owned(),
71                Value::Array(
72                    ordered
73                        .into_iter()
74                        .map(|file| {
75                            serde_json::json!({
76                            "body": &file.body,
77                            "contentType": &file.content_type,
78                            "path": &file.path,
79                            })
80                        })
81                        .collect(),
82                ),
83            )]
84            .into_iter()
85            .collect(),
86        );
87        let bytes = canonical_json_bytes(value)?;
88        Ok(format!("sha256:{}", hex(&Sha256::digest(bytes))))
89    }
90
91    pub fn id(&self) -> &str {
92        &self.fixture_id
93    }
94
95    pub fn digest(&self) -> &str {
96        &self.source_digest
97    }
98
99    pub(crate) fn files(&self) -> &[FixtureFile] {
100        &self.files
101    }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "camelCase", deny_unknown_fields)]
106pub struct FixtureIntent {
107    pub schema: String,
108    pub fixture_id: String,
109    pub fixture_source_digest: String,
110    pub probe_id: String,
111    pub actions_digest: String,
112    pub exact_url: String,
113    pub actions: Vec<FixtureAction>,
114    pub expires_after_ms: u64,
115}
116
117impl FixtureIntent {
118    pub fn validate(&self, bundle: &FixtureBundle) -> Result<(), FixtureError> {
119        if self.schema != FIXTURE_SCHEMA {
120            return Err(FixtureError::Invalid("unsupported fixture schema".into()));
121        }
122        validate_id("fixture_id", &self.fixture_id)?;
123        validate_id("probe_id", &self.probe_id)?;
124        validate_digest("fixture_source_digest", &self.fixture_source_digest)?;
125        validate_digest("actions_digest", &self.actions_digest)?;
126        validate_text("exact_url", &self.exact_url)?;
127        if self.actions.len() > MAX_ACTIONS {
128            return Err(FixtureError::Invalid("too many fixture actions".into()));
129        }
130        if self.expires_after_ms == 0 || self.expires_after_ms > MAX_EXPIRY_MS {
131            return Err(FixtureError::Invalid(
132                "expires_after_ms must be between 1 and 30000".into(),
133            ));
134        }
135        validate_actions(&self.actions)?;
136        let actual_actions_digest = actions_digest(&self.actions)?;
137        if actual_actions_digest != self.actions_digest {
138            return Err(FixtureError::Invalid(
139                "actions digest does not match actions".into(),
140            ));
141        }
142        if self.fixture_id != bundle.id() || self.fixture_source_digest != bundle.digest() {
143            return Err(FixtureError::Invalid(
144                "intent does not reference the owned fixture bundle".into(),
145            ));
146        }
147        let url = parse_fixture_url(&self.exact_url)?;
148        let path = url.path();
149        if !bundle.files().iter().any(|file| file.path == path) {
150            return Err(FixtureError::Invalid(
151                "exact_url does not point to a fixture manifest resource".into(),
152            ));
153        }
154        Ok(())
155    }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
160pub enum FixtureAction {
161    Click {
162        selector: String,
163    },
164    Type {
165        text: String,
166    },
167    Press {
168        key: FixtureKey,
169    },
170    AssertVisible {
171        selector: String,
172        #[serde(default, skip_serializing_if = "Option::is_none")]
173        timeout: Option<u64>,
174    },
175    AssertText {
176        selector: String,
177        text: String,
178    },
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
182pub enum FixtureKey {
183    Tab,
184    Escape,
185    ArrowUp,
186    ArrowDown,
187    ArrowLeft,
188    ArrowRight,
189}
190
191pub fn actions_digest(actions: &[FixtureAction]) -> Result<String, FixtureError> {
192    if actions.len() > MAX_ACTIONS {
193        return Err(FixtureError::Invalid("too many fixture actions".into()));
194    }
195    validate_actions(actions)?;
196    // Match the request producer's Value representation, with explicit key sorting.
197    let value = serde_json::to_value(actions).map_err(|error| {
198        FixtureError::Invalid(format!("cannot encode fixture actions: {error}"))
199    })?;
200    let bytes = canonical_json_bytes(value)?;
201    Ok(format!("sha256:{}", hex(&Sha256::digest(bytes))))
202}
203
204fn canonical_json_bytes(value: Value) -> Result<Vec<u8>, FixtureError> {
205    serde_json::to_vec(&sort_json_objects(value))
206        .map_err(|error| FixtureError::Invalid(format!("cannot encode canonical JSON: {error}")))
207}
208
209fn sort_json_objects(value: Value) -> Value {
210    match value {
211        Value::Array(values) => Value::Array(values.into_iter().map(sort_json_objects).collect()),
212        Value::Object(object) => {
213            let mut entries: Vec<_> = object.into_iter().collect();
214            entries.sort_by(|left, right| left.0.cmp(&right.0));
215            let mut sorted = Map::new();
216            for (key, value) in entries {
217                sorted.insert(key, sort_json_objects(value));
218            }
219            Value::Object(sorted)
220        }
221        scalar => scalar,
222    }
223}
224
225#[derive(Debug, Clone, Error, Serialize, Deserialize)]
226#[serde(tag = "code", content = "message", rename_all = "camelCase")]
227pub enum FixtureError {
228    #[error("invalid fixture request: {0}")]
229    Invalid(String),
230    #[error("fixture server is not owned: {0}")]
231    FixtureServerNotOwned(String),
232    #[error("fixture confinement is unsupported: {0}")]
233    ConfinementUnsupported(String),
234    #[error("fixture confinement is unavailable: {0}")]
235    ConfinementUnavailable(String),
236    #[error("fixture request was revoked: {0}")]
237    Revoked(String),
238    #[error("fixture execution was cancelled: {0}")]
239    Cancelled(String),
240    #[error("fixture execution expired: {0}")]
241    Expired(String),
242    #[error("browser operation failed: {0}")]
243    Browser(String),
244    #[error("fixture cleanup failed: {0}")]
245    Cleanup(String),
246}
247
248pub(crate) fn validate_fixture_path(path: &str) -> Result<(), FixtureError> {
249    if path.is_empty() || !path.starts_with('/') || path.len() > MAX_STRING_BYTES {
250        return Err(FixtureError::Invalid(
251            "fixture paths must be absolute URL paths".into(),
252        ));
253    }
254    if path
255        .chars()
256        .any(|character| matches!(character, '\\' | '?' | '#' | '%') || character.is_control())
257    {
258        return Err(FixtureError::Invalid(
259            "fixture path contains forbidden characters".into(),
260        ));
261    }
262    if path
263        .split('/')
264        .skip(1)
265        .any(|segment| segment.is_empty() || segment == "." || segment == "..")
266    {
267        return Err(FixtureError::Invalid(
268            "fixture path contains an empty or dot segment".into(),
269        ));
270    }
271    if !path.is_ascii() {
272        return Err(FixtureError::Invalid(
273            "fixture paths must use ASCII URL characters".into(),
274        ));
275    }
276    if !path.bytes().all(|byte| {
277        byte == b'/' || byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=@:".contains(&byte)
278    }) {
279        return Err(FixtureError::Invalid(
280            "fixture path contains an unsupported character".into(),
281        ));
282    }
283    Ok(())
284}
285
286pub(crate) fn parse_fixture_url(value: &str) -> Result<Url, FixtureError> {
287    let remainder = value
288        .strip_prefix("http://")
289        .ok_or_else(|| FixtureError::Invalid("exact_url must use lowercase http://".into()))?;
290    let authority_end = remainder.find('/').unwrap_or(remainder.len());
291    let raw_path = if authority_end == remainder.len() {
292        "/"
293    } else {
294        remainder[authority_end..]
295            .split(['?', '#'])
296            .next()
297            .unwrap_or_default()
298    };
299    validate_fixture_path(raw_path)?;
300    let url = Url::parse(value)
301        .map_err(|_| FixtureError::Invalid("exact_url is not a valid URL".into()))?;
302    explicit_fixture_port(value)?;
303    if url.scheme() != "http"
304        || url.host_str() != Some("127.0.0.1")
305        || !url.username().is_empty()
306        || url.password().is_some()
307        || url.query().is_some()
308        || url.fragment().is_some()
309    {
310        return Err(FixtureError::Invalid(
311            "exact_url must be explicit-port HTTP on 127.0.0.1 without credentials, query, or fragment".into(),
312        ));
313    }
314    if url.path() != raw_path {
315        return Err(FixtureError::Invalid(
316            "exact_url path was normalized during parsing".into(),
317        ));
318    }
319    Ok(url)
320}
321
322pub(crate) fn explicit_fixture_port(value: &str) -> Result<u16, FixtureError> {
323    let remainder = value
324        .strip_prefix("http://")
325        .ok_or_else(|| FixtureError::Invalid("exact_url must use lowercase http://".into()))?;
326    let authority = remainder.split(['/', '?', '#']).next().unwrap_or_default();
327    let port = authority
328        .strip_prefix("127.0.0.1:")
329        .ok_or_else(|| FixtureError::Invalid("exact_url must name 127.0.0.1 with a port".into()))?;
330    if port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit()) {
331        return Err(FixtureError::Invalid(
332            "exact_url must contain an explicit numeric port".into(),
333        ));
334    }
335    let parsed = port
336        .parse::<u16>()
337        .map_err(|_| FixtureError::Invalid("exact_url port is outside the valid range".into()))?;
338    if parsed == 0 {
339        return Err(FixtureError::Invalid(
340            "exact_url port must be nonzero".into(),
341        ));
342    }
343    Ok(parsed)
344}
345
346fn validate_files(files: &[FixtureFile]) -> Result<(), FixtureError> {
347    if files.is_empty() || files.len() > MAX_FIXTURE_FILES {
348        return Err(FixtureError::Invalid(
349            "fixture file count is outside allowed bounds".into(),
350        ));
351    }
352    let mut paths = BTreeSet::new();
353    let mut total = 0usize;
354    for file in files {
355        validate_fixture_path(&file.path)?;
356        if !paths.insert(file.path.as_str()) {
357            return Err(FixtureError::Invalid("duplicate fixture path".into()));
358        }
359        validate_text("content_type", &file.content_type)?;
360        if file
361            .content_type
362            .chars()
363            .any(|character| matches!(character, '\r' | '\n'))
364            || !file.content_type.is_ascii()
365        {
366            return Err(FixtureError::Invalid("invalid fixture content type".into()));
367        }
368        total = total
369            .checked_add(file.body.len())
370            .ok_or_else(|| FixtureError::Invalid("fixture byte count overflow".into()))?;
371    }
372    if total > MAX_FIXTURE_BYTES {
373        return Err(FixtureError::Invalid(
374            "fixture exceeds total byte limit".into(),
375        ));
376    }
377    Ok(())
378}
379
380fn validate_actions(actions: &[FixtureAction]) -> Result<(), FixtureError> {
381    if actions.is_empty() {
382        return Err(FixtureError::Invalid(
383            "fixture actions must contain at least one action".into(),
384        ));
385    }
386    for action in actions {
387        match action {
388            FixtureAction::Click { selector } | FixtureAction::AssertVisible { selector, .. } => {
389                validate_text("selector", selector)?;
390            }
391            FixtureAction::Type { text } => validate_text("text", text)?,
392            FixtureAction::Press { .. } => {}
393            FixtureAction::AssertText { selector, text } => {
394                validate_text("selector", selector)?;
395                validate_text("text", text)?;
396            }
397        }
398        if let FixtureAction::AssertVisible {
399            timeout: Some(timeout),
400            ..
401        } = action
402        {
403            if !(1..=5000).contains(timeout) {
404                return Err(FixtureError::Invalid(
405                    "assertVisible timeout must be between 1 and 5000".into(),
406                ));
407            }
408        }
409    }
410    Ok(())
411}
412
413fn validate_id(name: &str, value: &str) -> Result<(), FixtureError> {
414    if value.is_empty()
415        || value.len() > 128
416        || !value
417            .bytes()
418            .all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte))
419    {
420        return Err(FixtureError::Invalid(format!(
421            "{name} must be 1..128 ASCII identifier bytes"
422        )));
423    }
424    Ok(())
425}
426
427fn validate_digest(name: &str, value: &str) -> Result<(), FixtureError> {
428    let Some(hex_value) = value.strip_prefix("sha256:") else {
429        return Err(FixtureError::Invalid(format!(
430            "{name} must be a sha256 digest"
431        )));
432    };
433    if hex_value.len() != 64
434        || !hex_value
435            .bytes()
436            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
437    {
438        return Err(FixtureError::Invalid(format!(
439            "{name} must use lowercase SHA-256 hex"
440        )));
441    }
442    Ok(())
443}
444
445fn validate_text(name: &str, value: &str) -> Result<(), FixtureError> {
446    if value.trim().is_empty() || value.len() > MAX_STRING_BYTES {
447        return Err(FixtureError::Invalid(format!(
448            "{name} must be nonempty and at most 2048 bytes"
449        )));
450    }
451    Ok(())
452}
453
454fn hex(bytes: &[u8]) -> String {
455    const HEX: &[u8; 16] = b"0123456789abcdef";
456    let mut output = String::with_capacity(bytes.len() * 2);
457    for byte in bytes {
458        output.push(HEX[(byte >> 4) as usize] as char);
459        output.push(HEX[(byte & 0x0f) as usize] as char);
460    }
461    output
462}
463
464#[cfg(test)]
465mod tests {
466    use super::{actions_digest, canonical_json_bytes, FixtureAction, FixtureBundle, FixtureFile};
467    use serde_json::{json, Map, Value};
468    use sha2::{Digest, Sha256};
469
470    #[test]
471    fn canonical_json_recursively_sorts_object_keys() {
472        let mut nested = Map::new();
473        nested.insert("b".into(), json!(1));
474        nested.insert("a".into(), json!(2));
475        let mut object = Map::new();
476        object.insert("z".into(), Value::Object(nested));
477        object.insert("a".into(), json!(0));
478
479        let bytes = canonical_json_bytes(Value::Object(object)).unwrap();
480        assert_eq!(bytes, br#"{"a":0,"z":{"a":2,"b":1}}"#);
481    }
482
483    #[test]
484    fn action_digest_matches_known_canonical_bytes_without_null_timeout() {
485        let action = FixtureAction::AssertVisible {
486            selector: "#ready".into(),
487            timeout: None,
488        };
489        let value = serde_json::to_value([action.clone()]).unwrap();
490        let bytes = canonical_json_bytes(value).unwrap();
491        let expected_bytes = br##"[{"selector":"#ready","type":"assertVisible"}]"##;
492        assert_eq!(bytes, expected_bytes);
493        let expected_digest = format!("sha256:{}", super::hex(&Sha256::digest(expected_bytes)));
494        assert_eq!(actions_digest(&[action]).unwrap(), expected_digest);
495    }
496
497    #[test]
498    fn source_digest_matches_known_canonical_bytes() {
499        let files = [FixtureFile {
500            path: "/index.html".into(),
501            content_type: "text/html".into(),
502            body: vec![1, 2],
503        }];
504        let expected_bytes =
505            br#"{"files":[{"body":[1,2],"contentType":"text/html","path":"/index.html"}]}"#;
506        let expected_digest = format!("sha256:{}", super::hex(&Sha256::digest(expected_bytes)));
507        assert_eq!(
508            FixtureBundle::source_digest(&files).unwrap(),
509            expected_digest
510        );
511    }
512
513    #[test]
514    fn empty_actions_are_rejected() {
515        assert!(actions_digest(&[]).is_err());
516    }
517
518    #[test]
519    fn fixture_error_uses_stable_code_and_message_fields() {
520        let value = serde_json::to_value(super::FixtureError::Expired("deadline".into()))
521            .expect("fixture error should serialize");
522        assert_eq!(value["code"], "expired");
523        assert_eq!(value["message"], "deadline");
524        let decoded: super::FixtureError =
525            serde_json::from_value(value).expect("fixture error should deserialize");
526        assert!(matches!(decoded, super::FixtureError::Expired(message) if message == "deadline"));
527    }
528}