index-headless 1.0.0

Headless snapshot fallback abstractions for Index.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Headless snapshot fallback abstractions.
//!
//! This crate does not embed a browser. It defines the deterministic boundary
//! that a future browser-backed implementation must satisfy.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{Display, Formatter};
use std::time::Duration;

use index_core::{IndexUrl, Origin};

/// Request sent to a headless backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessRequest {
    /// Target URL.
    pub url: IndexUrl,
    /// Static HTML already fetched by Index.
    pub static_html: String,
    /// Rendering configuration.
    pub config: HeadlessConfig,
}

impl HeadlessRequest {
    /// Creates a request with default fallback policy.
    #[must_use]
    pub fn new(url: IndexUrl, static_html: impl Into<String>) -> Self {
        Self {
            url,
            static_html: static_html.into(),
            config: HeadlessConfig::default(),
        }
    }
}

/// Headless fallback configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessConfig {
    /// Maximum time allowed for rendering.
    pub timeout: TimeoutPolicy,
    /// Script execution policy.
    pub scripts: ScriptPolicy,
    /// Network expansion policy.
    pub network: NetworkPolicy,
    /// Sandbox policy.
    pub sandbox: SandboxPolicy,
}

impl Default for HeadlessConfig {
    fn default() -> Self {
        Self {
            timeout: TimeoutPolicy::default(),
            scripts: ScriptPolicy::Enabled,
            network: NetworkPolicy::DenyExternal,
            sandbox: SandboxPolicy::default(),
        }
    }
}

/// Timeout policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeoutPolicy {
    /// Maximum render duration.
    pub max_render_time: Duration,
}

impl TimeoutPolicy {
    /// Creates a timeout policy from milliseconds.
    #[must_use]
    pub const fn from_millis(milliseconds: u64) -> Self {
        Self {
            max_render_time: Duration::from_millis(milliseconds),
        }
    }
}

impl Default for TimeoutPolicy {
    fn default() -> Self {
        Self::from_millis(5_000)
    }
}

/// Script execution policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptPolicy {
    /// Do not execute page scripts.
    Disabled,
    /// Execute scripts inside the sandbox.
    Enabled,
}

/// Network permission policy for rendered pages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkPolicy {
    /// No network access while rendering.
    DenyAll,
    /// Allow only same-origin requests.
    DenyExternal,
    /// Allow all network requests.
    AllowAll,
}

/// Sandbox policy for headless execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxPolicy {
    /// Whether sandboxing is required.
    pub enabled: bool,
    /// Whether local filesystem writes are denied.
    pub read_only_filesystem: bool,
    /// Whether credentials are withheld from the browser context.
    pub no_credentials: bool,
}

impl Default for SandboxPolicy {
    fn default() -> Self {
        Self {
            enabled: true,
            read_only_filesystem: true,
            no_credentials: true,
        }
    }
}

/// Rendered snapshot emitted by a headless backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessSnapshot {
    /// Final URL for the snapshot.
    pub final_url: IndexUrl,
    /// Rendered DOM HTML.
    pub dom_html: String,
    /// Accessibility tree when available.
    pub accessibility: Option<AccessibilitySnapshot>,
}

/// Accessibility snapshot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessibilitySnapshot {
    /// Root accessibility nodes.
    pub nodes: Vec<AccessibilityNode>,
}

impl AccessibilitySnapshot {
    /// Extracts readable text in deterministic tree order.
    #[must_use]
    pub fn text_content(&self) -> String {
        let mut parts = Vec::new();
        for node in &self.nodes {
            collect_accessibility_text(node, &mut parts);
        }
        parts.join(" ")
    }
}

/// Accessibility tree node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessibilityNode {
    /// Role such as heading, link, or button.
    pub role: String,
    /// Accessible name.
    pub name: String,
    /// Child nodes.
    pub children: Vec<AccessibilityNode>,
}

impl AccessibilityNode {
    /// Creates a leaf accessibility node.
    #[must_use]
    pub fn leaf(role: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            role: role.into(),
            name: name.into(),
            children: Vec::new(),
        }
    }
}

/// Headless backend abstraction.
pub trait HeadlessBackend {
    /// Renders a deterministic snapshot.
    fn snapshot(&self, request: &HeadlessRequest) -> Result<HeadlessSnapshot, HeadlessError>;
}

/// Headless fallback errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeadlessError {
    /// Rendering exceeded the configured timeout.
    TimedOut {
        /// Timeout in milliseconds.
        timeout_ms: u128,
    },
    /// A requested origin was denied by policy.
    PermissionDenied {
        /// Denied origin.
        origin: Origin,
        /// Policy that denied the request.
        policy: NetworkPolicy,
    },
    /// Sandbox policy was not strong enough.
    SandboxRequired,
    /// The backend could not produce a snapshot.
    SnapshotFailed(String),
}

impl Display for HeadlessError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TimedOut { timeout_ms } => {
                write!(f, "headless rendering timed out after {timeout_ms}ms")
            }
            Self::PermissionDenied { origin, policy } => {
                write!(
                    f,
                    "headless network request denied for {origin} by {policy:?}"
                )
            }
            Self::SandboxRequired => f.write_str("headless rendering requires sandboxing"),
            Self::SnapshotFailed(reason) => write!(f, "headless snapshot failed: {reason}"),
        }
    }
}

impl std::error::Error for HeadlessError {}

/// Deterministic fixture backend for tests and future harnesses.
#[derive(Debug, Clone, Default)]
pub struct FixtureHeadlessBackend {
    rendered: BTreeMap<String, FixtureSnapshot>,
    denied_origins: BTreeSet<Origin>,
}

impl FixtureHeadlessBackend {
    /// Creates an empty fixture backend.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a rendered DOM snapshot.
    pub fn insert(&mut self, url: IndexUrl, snapshot: FixtureSnapshot) {
        self.rendered.insert(url.as_str().to_owned(), snapshot);
    }

    /// Denies an origin.
    pub fn deny_origin(&mut self, origin: Origin) {
        self.denied_origins.insert(origin);
    }
}

impl HeadlessBackend for FixtureHeadlessBackend {
    fn snapshot(&self, request: &HeadlessRequest) -> Result<HeadlessSnapshot, HeadlessError> {
        enforce_sandbox(&request.config.sandbox)?;

        let fixture = self
            .rendered
            .get(request.url.as_str())
            .ok_or_else(|| HeadlessError::SnapshotFailed("no rendered fixture".to_owned()))?;
        enforce_network_permissions(request, fixture, &self.denied_origins)?;
        if fixture.render_time > request.config.timeout.max_render_time {
            return Err(HeadlessError::TimedOut {
                timeout_ms: request.config.timeout.max_render_time.as_millis(),
            });
        }

        Ok(HeadlessSnapshot {
            final_url: fixture.final_url.clone(),
            dom_html: fixture.dom_html.clone(),
            accessibility: fixture.accessibility.clone(),
        })
    }
}

/// Fixture snapshot used by the deterministic backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FixtureSnapshot {
    /// Final URL.
    pub final_url: IndexUrl,
    /// Rendered DOM HTML.
    pub dom_html: String,
    /// Accessibility tree.
    pub accessibility: Option<AccessibilitySnapshot>,
    /// Simulated render duration.
    pub render_time: Duration,
    /// Origins requested while rendering.
    pub requested_origins: Vec<Origin>,
}

impl FixtureSnapshot {
    /// Creates a fast DOM snapshot fixture.
    #[must_use]
    pub fn rendered(final_url: IndexUrl, dom_html: impl Into<String>) -> Self {
        Self {
            final_url,
            dom_html: dom_html.into(),
            accessibility: None,
            render_time: Duration::from_millis(1),
            requested_origins: Vec::new(),
        }
    }
}

fn enforce_sandbox(policy: &SandboxPolicy) -> Result<(), HeadlessError> {
    if policy.enabled && policy.read_only_filesystem && policy.no_credentials {
        Ok(())
    } else {
        Err(HeadlessError::SandboxRequired)
    }
}

fn enforce_network_permissions(
    request: &HeadlessRequest,
    fixture: &FixtureSnapshot,
    denied_origins: &BTreeSet<Origin>,
) -> Result<(), HeadlessError> {
    let request_origin = request.url.origin();
    for origin in &fixture.requested_origins {
        let denied_by_policy = match request.config.network {
            NetworkPolicy::DenyAll => true,
            NetworkPolicy::DenyExternal => request_origin.as_ref() != Some(origin),
            NetworkPolicy::AllowAll => false,
        };
        let denied_explicitly = denied_origins.contains(origin);
        if denied_by_policy || denied_explicitly {
            return Err(HeadlessError::PermissionDenied {
                origin: origin.clone(),
                policy: request.config.network,
            });
        }
    }

    if let Some(origin) = request_origin.filter(|origin| denied_origins.contains(origin)) {
        return Err(HeadlessError::PermissionDenied {
            origin,
            policy: request.config.network,
        });
    }
    Ok(())
}

fn collect_accessibility_text(node: &AccessibilityNode, parts: &mut Vec<String>) {
    if !node.name.is_empty() {
        parts.push(format!("{}: {}", node.role, node.name));
    }
    for child in &node.children {
        collect_accessibility_text(child, parts);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        AccessibilityNode, AccessibilitySnapshot, FixtureHeadlessBackend, FixtureSnapshot,
        HeadlessBackend, HeadlessConfig, HeadlessError, HeadlessRequest, NetworkPolicy,
        SandboxPolicy, TimeoutPolicy,
    };
    use index_core::{IndexUrl, Origin};

    #[test]
    fn delayed_render_fixture_returns_rendered_dom() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/app")?;
        let mut backend = FixtureHeadlessBackend::new();
        backend.insert(
            url.clone(),
            FixtureSnapshot::rendered(
                url.clone(),
                "<main><h1>Loaded</h1><p>Rendered after delay.</p></main>",
            ),
        );

        let snapshot = backend.snapshot(&HeadlessRequest::new(url, "<main id=\"app\"></main>"))?;

        assert!(snapshot.dom_html.contains("Rendered after delay."));
        Ok(())
    }

    #[test]
    fn spa_fixture_can_include_accessibility_tree() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/spa")?;
        let mut backend = FixtureHeadlessBackend::new();
        let mut fixture = FixtureSnapshot::rendered(
            url.clone(),
            "<main><button>Search</button><a href=\"/docs\">Docs</a></main>",
        );
        fixture.accessibility = Some(AccessibilitySnapshot {
            nodes: vec![AccessibilityNode {
                role: "main".to_owned(),
                name: "Application".to_owned(),
                children: vec![
                    AccessibilityNode::leaf("button", "Search"),
                    AccessibilityNode::leaf("link", "Docs"),
                ],
            }],
        });
        backend.insert(url.clone(), fixture);

        let snapshot = backend.snapshot(&HeadlessRequest::new(url, "<div id=\"root\"></div>"))?;

        assert_eq!(
            snapshot.accessibility.map(|tree| tree.text_content()),
            Some("main: Application button: Search link: Docs".to_owned())
        );
        Ok(())
    }

    #[test]
    fn timeout_errors_are_deterministic() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/slow")?;
        let mut backend = FixtureHeadlessBackend::new();
        let mut fixture = FixtureSnapshot::rendered(url.clone(), "<main>Slow</main>");
        fixture.render_time = std::time::Duration::from_millis(50);
        backend.insert(url.clone(), fixture);
        let mut request = HeadlessRequest::new(url, "<main></main>");
        request.config.timeout = TimeoutPolicy::from_millis(10);

        assert_eq!(
            backend.snapshot(&request),
            Err(HeadlessError::TimedOut { timeout_ms: 10 })
        );
        Ok(())
    }

    #[test]
    fn denied_origin_returns_permission_error() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/app")?;
        let mut backend = FixtureHeadlessBackend::new();
        backend.insert(
            url.clone(),
            FixtureSnapshot::rendered(url.clone(), "<main>Denied</main>"),
        );
        backend.deny_origin(Origin::from_stored("https://example.com"));
        let mut request = HeadlessRequest::new(url, "<main></main>");
        request.config.network = NetworkPolicy::DenyExternal;

        assert_eq!(
            backend.snapshot(&request),
            Err(HeadlessError::PermissionDenied {
                origin: Origin::from_stored("https://example.com"),
                policy: NetworkPolicy::DenyExternal
            })
        );
        Ok(())
    }

    #[test]
    fn sandbox_policy_must_remain_strict() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/app")?;
        let backend = FixtureHeadlessBackend::new();
        let mut request = HeadlessRequest::new(url, "<main></main>");
        request.config = HeadlessConfig {
            sandbox: SandboxPolicy {
                enabled: false,
                read_only_filesystem: true,
                no_credentials: true,
            },
            ..HeadlessConfig::default()
        };

        assert_eq!(
            backend.snapshot(&request),
            Err(HeadlessError::SandboxRequired)
        );
        Ok(())
    }

    #[test]
    fn network_policy_variants_enforce_expected_origin_rules()
    -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/app")?;
        let external_origin = Origin::from_stored("https://cdn.example.net");
        let mut backend = FixtureHeadlessBackend::new();
        let mut fixture = FixtureSnapshot::rendered(url.clone(), "<main>Network</main>");
        fixture.requested_origins = vec![external_origin.clone()];
        backend.insert(url.clone(), fixture);

        let mut deny_all = HeadlessRequest::new(url.clone(), "<main></main>");
        deny_all.config.network = NetworkPolicy::DenyAll;
        assert_eq!(
            backend.snapshot(&deny_all),
            Err(HeadlessError::PermissionDenied {
                origin: external_origin.clone(),
                policy: NetworkPolicy::DenyAll,
            })
        );

        let mut deny_external = HeadlessRequest::new(url.clone(), "<main></main>");
        deny_external.config.network = NetworkPolicy::DenyExternal;
        assert_eq!(
            backend.snapshot(&deny_external),
            Err(HeadlessError::PermissionDenied {
                origin: external_origin.clone(),
                policy: NetworkPolicy::DenyExternal,
            })
        );

        let mut allow_all = HeadlessRequest::new(url, "<main></main>");
        allow_all.config.network = NetworkPolicy::AllowAll;
        let snapshot = backend.snapshot(&allow_all)?;
        assert!(snapshot.dom_html.contains("Network"));
        Ok(())
    }

    #[test]
    fn explicit_deny_origin_blocks_allow_all_policy() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/app")?;
        let denied_origin = Origin::from_stored("https://cdn.example.net");
        let mut backend = FixtureHeadlessBackend::new();
        let mut fixture = FixtureSnapshot::rendered(url.clone(), "<main>Denied</main>");
        fixture.requested_origins = vec![denied_origin.clone()];
        backend.insert(url.clone(), fixture);
        backend.deny_origin(denied_origin.clone());

        let mut request = HeadlessRequest::new(url, "<main></main>");
        request.config.network = NetworkPolicy::AllowAll;
        assert_eq!(
            backend.snapshot(&request),
            Err(HeadlessError::PermissionDenied {
                origin: denied_origin,
                policy: NetworkPolicy::AllowAll,
            })
        );
        Ok(())
    }

    #[test]
    fn missing_fixture_returns_snapshot_failed() -> Result<(), Box<dyn std::error::Error>> {
        let request = HeadlessRequest::new(IndexUrl::parse("https://example.com/missing")?, "");
        let backend = FixtureHeadlessBackend::new();
        let result = backend.snapshot(&request);
        assert!(matches!(
            result,
            Err(HeadlessError::SnapshotFailed(reason)) if reason.contains("no rendered fixture")
        ));
        Ok(())
    }

    #[test]
    fn headless_error_display_variants_are_actionable() {
        let timed_out = HeadlessError::TimedOut { timeout_ms: 250 }.to_string();
        assert!(timed_out.contains("timed out"));
        assert!(timed_out.contains("250ms"));

        let denied = HeadlessError::PermissionDenied {
            origin: Origin::from_stored("https://example.com"),
            policy: NetworkPolicy::DenyAll,
        }
        .to_string();
        assert!(denied.contains("denied"));
        assert!(denied.contains("DenyAll"));

        let sandbox = HeadlessError::SandboxRequired.to_string();
        assert!(sandbox.contains("requires sandboxing"));

        let failed = HeadlessError::SnapshotFailed("boom".to_owned()).to_string();
        assert!(failed.contains("boom"));
    }
}