index-core 1.0.0

Core document model and semantic types 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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Authentication, cookie, and redaction primitives.

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

use crate::{Form, FormSubmitError, IndexUrl, Origin, SessionId};

/// Authentication errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthError {
    /// URL had no origin.
    MissingOrigin,
    /// Requested origin is outside the session scope.
    OriginDenied(Origin),
    /// Secure cookies require HTTPS origins.
    InsecureCookieOrigin(Origin),
    /// Secure storage operation failed.
    Storage(String),
    /// Login form submission failed.
    Form(FormSubmitError),
}

impl Display for AuthError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingOrigin => f.write_str("authentication requires a URL origin"),
            Self::OriginDenied(origin) => {
                write!(f, "origin is outside auth session scope: {origin}")
            }
            Self::InsecureCookieOrigin(origin) => {
                write!(
                    f,
                    "secure cookie cannot be stored for insecure origin: {origin}"
                )
            }
            Self::Storage(reason) => write!(f, "secure storage failed: {reason}"),
            Self::Form(error) => write!(f, "login form submission failed: {error}"),
        }
    }
}

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

/// Cookie value scoped to an origin.
#[derive(Clone, PartialEq, Eq)]
pub struct Cookie {
    /// Cookie name.
    pub name: String,
    value: String,
    /// Whether the cookie should be withheld from scripts.
    pub http_only: bool,
    /// Whether the cookie requires HTTPS.
    pub secure: bool,
}

impl Cookie {
    /// Creates a cookie.
    #[must_use]
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            http_only: true,
            secure: true,
        }
    }

    /// Returns the cookie value for transport code.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    fn serialized(&self) -> String {
        format!(
            "{}={}; HttpOnly={}; Secure={}",
            escape_field(&self.name),
            escape_field(&self.value),
            self.http_only,
            self.secure
        )
    }
}

impl Debug for Cookie {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Cookie")
            .field("name", &self.name)
            .field("value", &"[REDACTED]")
            .field("http_only", &self.http_only)
            .field("secure", &self.secure)
            .finish()
    }
}

/// Cookie jar isolated by origin.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CookieJar {
    cookies: BTreeMap<Origin, BTreeMap<String, Cookie>>,
}

impl CookieJar {
    /// Creates an empty cookie jar.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Stores a cookie for a URL origin.
    pub fn set(&mut self, url: &IndexUrl, cookie: Cookie) -> Result<(), AuthError> {
        let origin = url.origin().ok_or(AuthError::MissingOrigin)?;
        if cookie.secure && !origin.as_str().starts_with("https://") {
            return Err(AuthError::InsecureCookieOrigin(origin));
        }
        self.cookies
            .entry(origin)
            .or_default()
            .insert(cookie.name.clone(), cookie);
        Ok(())
    }

    /// Returns a cookie by URL origin and name.
    #[must_use]
    pub fn get(&self, url: &IndexUrl, name: &str) -> Option<&Cookie> {
        self.cookies.get(&url.origin()?)?.get(name)
    }

    /// Builds a Cookie header for a URL.
    #[must_use]
    pub fn header_for(&self, url: &IndexUrl) -> Option<String> {
        let origin = url.origin()?;
        let cookies = self.cookies.get(&origin)?;
        let header = cookies
            .values()
            .map(|cookie| format!("{}={}", cookie.name, cookie.value()))
            .collect::<Vec<_>>()
            .join("; ");
        (!header.is_empty()).then_some(header)
    }

    /// Clears all cookies for one origin.
    pub fn clear_origin(&mut self, origin: &Origin) {
        self.cookies.remove(origin);
    }

    /// Clears all cookies.
    pub fn clear(&mut self) {
        self.cookies.clear();
    }

    /// Persists cookies through secure storage.
    pub fn save(&self, storage: &mut dyn SecureStorage, key: &str) -> Result<(), AuthError> {
        storage
            .store(key, self.serialize().as_bytes())
            .map_err(AuthError::Storage)
    }

    /// Loads cookies from secure storage.
    pub fn load(storage: &dyn SecureStorage, key: &str) -> Result<Self, AuthError> {
        let Some(bytes) = storage.load(key).map_err(AuthError::Storage)? else {
            return Ok(Self::new());
        };
        let contents =
            String::from_utf8(bytes).map_err(|error| AuthError::Storage(error.to_string()))?;
        Self::deserialize(&contents)
    }

    fn serialize(&self) -> String {
        let mut lines = vec!["index-cookies-v1".to_owned()];
        for (origin, cookies) in &self.cookies {
            for cookie in cookies.values() {
                lines.push(format!(
                    "{}\t{}",
                    escape_field(origin.as_str()),
                    cookie.serialized()
                ));
            }
        }
        lines.join("\n")
    }

    fn deserialize(contents: &str) -> Result<Self, AuthError> {
        let mut lines = contents.lines();
        if lines.next() != Some("index-cookies-v1") {
            return Err(AuthError::Storage("missing cookie jar header".to_owned()));
        }
        let mut jar = Self::new();
        for line in lines {
            let fields = line.split('\t').collect::<Vec<_>>();
            if fields.len() != 2 {
                return Err(AuthError::Storage("invalid cookie record".to_owned()));
            }
            let origin = Origin::from_stored(unescape_field(fields[0])?);
            let cookie = parse_cookie(fields[1])?;
            jar.cookies
                .entry(origin)
                .or_default()
                .insert(cookie.name.clone(), cookie);
        }
        Ok(jar)
    }
}

/// Secure storage abstraction for sensitive values.
pub trait SecureStorage {
    /// Stores bytes under a key.
    fn store(&mut self, key: &str, value: &[u8]) -> Result<(), String>;
    /// Loads bytes by key.
    fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String>;
    /// Deletes a key.
    fn delete(&mut self, key: &str) -> Result<(), String>;
}

/// In-memory secure storage for tests and local prototypes.
#[derive(Debug, Clone, Default)]
pub struct MemorySecureStorage {
    values: BTreeMap<String, Vec<u8>>,
}

impl MemorySecureStorage {
    /// Creates empty memory storage.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl SecureStorage for MemorySecureStorage {
    fn store(&mut self, key: &str, value: &[u8]) -> Result<(), String> {
        self.values.insert(key.to_owned(), value.to_vec());
        Ok(())
    }

    fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
        Ok(self.values.get(key).cloned())
    }

    fn delete(&mut self, key: &str) -> Result<(), String> {
        self.values.remove(key);
        Ok(())
    }
}

/// Auth session scope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionScope {
    /// Session may access exactly one origin.
    Origin(Origin),
    /// Session may access listed origins.
    Origins(BTreeSet<Origin>),
}

impl SessionScope {
    /// Returns whether this scope allows an origin.
    #[must_use]
    pub fn allows(&self, origin: &Origin) -> bool {
        match self {
            Self::Origin(allowed) => allowed == origin,
            Self::Origins(origins) => origins.contains(origin),
        }
    }
}

/// Authenticated session with scoped cookies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthSession {
    /// Session identifier.
    pub id: SessionId,
    /// Scope for this session.
    pub scope: SessionScope,
    /// Session cookies.
    pub cookies: CookieJar,
}

impl AuthSession {
    /// Creates a scoped auth session.
    #[must_use]
    pub fn new(id: SessionId, scope: SessionScope) -> Self {
        Self {
            id,
            scope,
            cookies: CookieJar::new(),
        }
    }

    /// Stores a cookie if the target URL is inside scope.
    pub fn set_cookie(&mut self, url: &IndexUrl, cookie: Cookie) -> Result<(), AuthError> {
        let origin = url.origin().ok_or(AuthError::MissingOrigin)?;
        if !self.scope.allows(&origin) {
            return Err(AuthError::OriginDenied(origin));
        }
        self.cookies.set(url, cookie)
    }

    /// Clears session state for logout.
    pub fn logout(&mut self) {
        self.cookies.clear();
    }
}

/// Origin policy for authenticated flows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OriginPolicy {
    allowed: BTreeSet<Origin>,
}

impl OriginPolicy {
    /// Creates an origin policy.
    #[must_use]
    pub fn new(allowed: impl IntoIterator<Item = Origin>) -> Self {
        Self {
            allowed: allowed.into_iter().collect(),
        }
    }

    /// Verifies a URL is allowed.
    pub fn check(&self, url: &IndexUrl) -> Result<(), AuthError> {
        let origin = url.origin().ok_or(AuthError::MissingOrigin)?;
        if self.allowed.contains(&origin) {
            Ok(())
        } else {
            Err(AuthError::OriginDenied(origin))
        }
    }
}

/// Login flow request abstraction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginFlow {
    /// Login form.
    pub form: Form,
    /// Base URL used for relative actions.
    pub base_url: IndexUrl,
}

impl LoginFlow {
    /// Submits login form values after applying origin policy.
    pub fn submit(
        &self,
        policy: &OriginPolicy,
        values: &[(&str, &str)],
    ) -> Result<crate::FormSubmission, AuthError> {
        policy.check(&self.base_url)?;
        let submission = self
            .form
            .submit(Some(&self.base_url), values)
            .map_err(AuthError::Form)?;
        policy.check(&submission.action)?;
        Ok(submission)
    }
}

/// Redacts sensitive values from diagnostics.
#[derive(Debug, Clone, Default)]
pub struct Redactor {
    secrets: Vec<String>,
}

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

    /// Adds a secret to redact.
    pub fn add_secret(&mut self, secret: impl Into<String>) {
        let secret = secret.into();
        if !secret.is_empty() {
            self.secrets.push(secret);
        }
    }

    /// Redacts known secrets and common credential fields.
    #[must_use]
    pub fn redact(&self, input: &str) -> String {
        let mut output = redact_known_fields(input);
        for secret in &self.secrets {
            output = output.replace(secret, "[REDACTED]");
        }
        output
    }
}

fn parse_cookie(input: &str) -> Result<Cookie, AuthError> {
    let mut parts = input.split("; ");
    let Some(pair) = parts.next() else {
        return Err(AuthError::Storage("missing cookie pair".to_owned()));
    };
    let Some((name, value)) = pair.split_once('=') else {
        return Err(AuthError::Storage("invalid cookie pair".to_owned()));
    };
    let mut cookie = Cookie::new(unescape_field(name)?, unescape_field(value)?);
    for part in parts {
        if let Some(value) = part.strip_prefix("HttpOnly=") {
            cookie.http_only = value == "true";
        } else if let Some(value) = part.strip_prefix("Secure=") {
            cookie.secure = value == "true";
        }
    }
    Ok(cookie)
}

fn redact_known_fields(input: &str) -> String {
    let mut output = Vec::new();
    let mut redact_next = false;

    for part in input.split_whitespace() {
        let lower = part.to_ascii_lowercase();
        if redact_next {
            output.push("[REDACTED]".to_owned());
            redact_next = lower == "bearer" || lower == "basic";
            continue;
        }

        if lower.starts_with("authorization:")
            || lower.starts_with("cookie:")
            || lower.starts_with("set-cookie:")
        {
            output.push("[REDACTED]".to_owned());
            redact_next = true;
        } else if lower.starts_with("token=") || lower.starts_with("password=") {
            output.push("[REDACTED]".to_owned());
        } else {
            output.push(part.to_owned());
        }
    }

    output.join(" ")
}

fn escape_field(input: &str) -> String {
    input
        .replace('\\', "\\\\")
        .replace('\t', "\\t")
        .replace('\n', "\\n")
}

fn unescape_field(input: &str) -> Result<String, AuthError> {
    let mut out = String::new();
    let mut chars = input.chars();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }
        let Some(next) = chars.next() else {
            return Err(AuthError::Storage("dangling escape".to_owned()));
        };
        match next {
            '\\' => out.push('\\'),
            't' => out.push('\t'),
            'n' => out.push('\n'),
            other => return Err(AuthError::Storage(format!("unknown escape: {other}"))),
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::{
        AuthError, AuthSession, Cookie, CookieJar, LoginFlow, MemorySecureStorage, OriginPolicy,
        Redactor, SecureStorage, SessionScope,
    };
    use crate::{Form, IndexUrl, Input, Origin, SessionId};

    #[test]
    fn cookies_persist_through_secure_storage() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/account")?;
        let mut jar = CookieJar::new();
        jar.set(&url, Cookie::new("sid", "secret"))?;
        let mut storage = MemorySecureStorage::new();

        jar.save(&mut storage, "cookies")?;
        let restored = CookieJar::load(&storage, "cookies")?;

        assert_eq!(restored.header_for(&url).as_deref(), Some("sid=secret"));
        Ok(())
    }

    #[test]
    fn cookies_are_isolated_by_origin() -> Result<(), Box<dyn std::error::Error>> {
        let first = IndexUrl::parse("https://example.com/account")?;
        let second = IndexUrl::parse("https://other.example/account")?;
        let mut jar = CookieJar::new();
        jar.set(&first, Cookie::new("sid", "secret"))?;

        assert_eq!(jar.header_for(&first).as_deref(), Some("sid=secret"));
        assert_eq!(jar.header_for(&second), None);
        Ok(())
    }

    #[test]
    fn logout_clears_session_cookies() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://example.com/account")?;
        let scope = SessionScope::Origin(Origin::from_stored("https://example.com"));
        let mut session = AuthSession::new(SessionId::new("auth"), scope);
        session.set_cookie(&url, Cookie::new("sid", "secret"))?;

        session.logout();

        assert_eq!(session.cookies.header_for(&url), None);
        Ok(())
    }

    #[test]
    fn auth_session_rejects_out_of_scope_cookie() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("https://other.example/account")?;
        let scope = SessionScope::Origin(Origin::from_stored("https://example.com"));
        let mut session = AuthSession::new(SessionId::new("auth"), scope);

        assert_eq!(
            session.set_cookie(&url, Cookie::new("sid", "secret")),
            Err(AuthError::OriginDenied(Origin::from_stored(
                "https://other.example"
            )))
        );
        Ok(())
    }

    #[test]
    fn secure_cookies_require_https() -> Result<(), Box<dyn std::error::Error>> {
        let url = IndexUrl::parse("http://example.com/account")?;
        let mut jar = CookieJar::new();

        assert_eq!(
            jar.set(&url, Cookie::new("sid", "secret")),
            Err(AuthError::InsecureCookieOrigin(Origin::from_stored(
                "http://example.com"
            )))
        );
        Ok(())
    }

    #[test]
    fn login_flow_resolves_form_inside_origin_policy() -> Result<(), Box<dyn std::error::Error>> {
        let flow = LoginFlow {
            base_url: IndexUrl::parse("https://example.com/login")?,
            form: Form {
                name: "login".to_owned(),
                method: "POST".to_owned(),
                action: "/session".to_owned(),
                inputs: vec![Input {
                    name: "user".to_owned(),
                    kind: "text".to_owned(),
                    value: None,
                    required: true,
                }],
                buttons: Vec::new(),
            },
        };
        let policy = OriginPolicy::new([Origin::from_stored("https://example.com")]);

        let submission = flow.submit(&policy, &[("user", "ada")])?;

        assert_eq!(submission.action.as_str(), "https://example.com/session");
        assert_eq!(submission.body.as_deref(), Some("user=ada"));
        Ok(())
    }

    #[test]
    fn login_flow_rejects_cross_origin_action() -> Result<(), Box<dyn std::error::Error>> {
        let flow = LoginFlow {
            base_url: IndexUrl::parse("https://example.com/login")?,
            form: Form {
                name: "login".to_owned(),
                method: "POST".to_owned(),
                action: "https://evil.example/session".to_owned(),
                inputs: Vec::new(),
                buttons: Vec::new(),
            },
        };
        let policy = OriginPolicy::new([Origin::from_stored("https://example.com")]);

        assert_eq!(
            flow.submit(&policy, &[]),
            Err(AuthError::OriginDenied(Origin::from_stored(
                "https://evil.example"
            )))
        );
        Ok(())
    }

    #[test]
    fn redactor_removes_cookie_tokens_and_known_secrets() {
        let mut redactor = Redactor::new();
        redactor.add_secret("abc123");

        let output =
            redactor.redact("Authorization: Bearer abc123 token=abc123 Cookie: sid=abc123");

        assert!(!output.contains("abc123"));
        assert!(!output.contains("Bearer"));
        assert!(output.contains("[REDACTED]"));
    }

    #[test]
    fn cookie_debug_does_not_leak_secret_value() {
        let cookie = Cookie::new("sid", "abc123");
        let rendered = format!("{cookie:?}");

        assert!(rendered.contains("sid"));
        assert!(!rendered.contains("abc123"));
    }

    #[test]
    fn secure_storage_delete_removes_value() -> Result<(), Box<dyn std::error::Error>> {
        let mut storage = MemorySecureStorage::new();
        storage.store("key", b"value")?;
        storage.delete("key")?;

        assert_eq!(storage.load("key")?, None);
        Ok(())
    }
}