alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
//! Workspace-relative plugin path grants.

use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser::SerializeStruct};
use std::{
    borrow::Cow,
    fmt::{Debug, Formatter},
};

/// Borrowed workspace-relative path accepted by the plugin authorization boundary.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct WorkspacePathRef<'path>(&'path str);

impl<'path> WorkspacePathRef<'path> {
    /// Returns the normalized workspace-relative string.
    #[must_use]
    pub const fn as_str(self) -> &'path str {
        self.0
    }
}

impl<'path> TryFrom<&'path str> for WorkspacePathRef<'path> {
    type Error = WorkspacePathError;

    fn try_from(path: &'path str) -> Result<Self, Self::Error> {
        validate_workspace_relative_path(path)?;
        Ok(Self(path))
    }
}

impl Debug for WorkspacePathRef<'_> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WorkspacePathRef")
            .field("path_byte_len", &self.0.len())
            .finish()
    }
}

/// Owned workspace-relative path accepted by the plugin authorization boundary.
#[derive(Clone, Eq, PartialEq)]
pub struct WorkspacePath(String);

impl WorkspacePath {
    /// Creates an owned workspace path from untrusted input.
    ///
    /// # Errors
    ///
    /// Returns [`WorkspacePathError`] when `path` is not normalized workspace-relative plugin
    /// vocabulary.
    pub fn try_new(path: impl Into<String>) -> Result<Self, WorkspacePathError> {
        let path = path.into();
        validate_workspace_relative_path(&path)?;
        Ok(Self(path))
    }

    /// Owns an already validated borrowed path.
    #[must_use]
    pub fn from_ref(path: WorkspacePathRef<'_>) -> Self {
        Self(path.as_str().to_owned())
    }

    /// Borrows normalized plugin path vocabulary.
    #[must_use]
    pub const fn as_ref(&self) -> WorkspacePathRef<'_> {
        WorkspacePathRef(self.0.as_str())
    }

    /// Returns the normalized workspace-relative string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the proof into normalized path text.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl Debug for WorkspacePath {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WorkspacePath")
            .field("path_byte_len", &self.0.len())
            .finish()
    }
}

/// Owned workspace-relative prefix accepted in static plugin grants.
#[derive(Clone, Eq, PartialEq)]
struct WorkspacePathPrefix(String);

impl WorkspacePathPrefix {
    /// Creates a validated workspace-relative grant prefix.
    fn try_new(prefix: impl Into<String>) -> Result<Self, WorkspacePathError> {
        let prefix = prefix.into();
        validate_workspace_grant_prefix(&prefix)?;
        Ok(Self(prefix))
    }

    /// Returns the normalized workspace-relative grant prefix.
    fn as_str(&self) -> &str {
        &self.0
    }
}

impl Debug for WorkspacePathPrefix {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WorkspacePathPrefix")
            .field("prefix_byte_len", &self.0.len())
            .finish()
    }
}

/// Workspace path validation failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum WorkspacePathError {
    /// Empty grant prefixes must use the explicit whole-workspace constructor.
    EmptyGrantPrefix,
    /// Absolute paths are not accepted at the plugin boundary.
    Absolute,
    /// `.` or `..` components are not accepted.
    DotComponent,
    /// Empty path components are not accepted.
    EmptyComponent,
    /// Platform-specific separators are not accepted in plugin paths.
    PlatformSeparator,
    /// Windows drive prefixes are not accepted in plugin paths.
    WindowsDrivePrefix,
}

/// Workspace-relative path grant.
#[derive(Clone, Eq, PartialEq)]
pub struct WorkspacePathGrant {
    /// Explicit authority scope, avoiding an internal sentinel prefix.
    scope: WorkspacePathGrantScope,
}

/// Workspace authority scope.
#[derive(Clone, Debug, Eq, PartialEq)]
enum WorkspacePathGrantScope {
    /// Deliberate broad grant.
    AllWorkspace,
    /// Normalized workspace-relative subtree.
    Prefix(WorkspacePathPrefix),
}

impl WorkspacePathGrantScope {
    /// Returns the compatibility prefix spelling.
    fn as_str(&self) -> &str {
        match self {
            Self::AllWorkspace => "",
            Self::Prefix(prefix) => prefix.as_str(),
        }
    }

    /// Returns whether this is a broad grant.
    const fn is_all_workspace(&self) -> bool {
        matches!(self, Self::AllWorkspace)
    }

    /// Returns whether this scope covers a validated grant or path prefix.
    fn covers(&self, prefix: &str) -> bool {
        match self {
            Self::AllWorkspace => true,
            Self::Prefix(grant_prefix) => {
                let grant_prefix = grant_prefix.as_str();
                prefix == grant_prefix
                    || prefix
                        .strip_prefix(grant_prefix)
                        .is_some_and(|suffix| suffix.starts_with('/'))
            }
        }
    }
}

impl WorkspacePathGrant {
    /// Creates a workspace-relative path grant.
    ///
    /// # Panics
    ///
    /// Panics when `prefix` is not a normalized workspace-relative grant prefix. Use
    /// [`Self::try_new`] for untrusted input.
    #[must_use]
    pub fn new(prefix: impl Into<String>) -> Self {
        Self::try_new(prefix).expect("workspace path grant literals should be valid")
    }

    /// Creates an explicit whole-workspace path grant.
    ///
    /// Prefer narrow prefixes for third-party plugins. This constructor exists so broad authority
    /// is visible at call sites instead of being hidden behind `Default` or an empty string literal.
    #[must_use]
    pub const fn all_workspace() -> Self {
        Self {
            scope: WorkspacePathGrantScope::AllWorkspace,
        }
    }

    /// Creates a workspace-relative path grant from untrusted input.
    ///
    /// # Errors
    ///
    /// Returns [`WorkspacePathError`] when `prefix` is not a normalized workspace-relative prefix.
    pub fn try_new(prefix: impl Into<String>) -> Result<Self, WorkspacePathError> {
        let prefix = prefix.into();
        if prefix.is_empty() {
            return Err(WorkspacePathError::EmptyGrantPrefix);
        }
        let prefix = WorkspacePathPrefix::try_new(prefix)?;
        Ok(Self {
            scope: WorkspacePathGrantScope::Prefix(prefix),
        })
    }

    /// Returns whether this grant permits `workspace_relative_path`.
    #[must_use]
    pub fn allows(&self, workspace_relative_path: WorkspacePathRef<'_>) -> bool {
        self.covers(workspace_relative_path.as_str())
    }

    /// Returns the normalized workspace-relative grant prefix.
    ///
    /// An empty prefix means this grant deliberately covers the whole workspace, and can only be
    /// constructed through [`Self::all_workspace`] or explicit JSON with `all_workspace: true`.
    #[must_use]
    pub fn prefix(&self) -> &str {
        self.scope.as_str()
    }

    /// Returns whether this grant deliberately covers the whole workspace.
    #[must_use]
    pub const fn is_all_workspace(&self) -> bool {
        self.scope.is_all_workspace()
    }

    /// Returns whether this grant covers another validated grant prefix.
    #[must_use]
    pub(crate) fn covers(&self, prefix: &str) -> bool {
        self.scope.covers(prefix)
    }
}

impl Debug for WorkspacePathGrant {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WorkspacePathGrant")
            .field("all_workspace", &self.is_all_workspace())
            .field("prefix_byte_len", &self.prefix().len())
            .finish()
    }
}

impl<'de> Deserialize<'de> for WorkspacePathGrant {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct RawGrant {
            prefix: String,
            all_workspace: Option<bool>,
        }

        let raw = RawGrant::deserialize(deserializer)?;
        if raw.prefix.is_empty() {
            if raw.all_workspace == Some(true) {
                return Ok(Self::all_workspace());
            }
            return Err(de::Error::custom(WorkspacePathError::EmptyGrantPrefix));
        }
        if raw.all_workspace.unwrap_or(false) {
            return Err(de::Error::custom(
                "all_workspace may only be true for an empty prefix",
            ));
        }
        Self::try_new(raw.prefix).map_err(de::Error::custom)
    }
}

impl Serialize for WorkspacePathGrant {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if self.is_all_workspace() {
            let mut state = serializer.serialize_struct("WorkspacePathGrant", 2)?;
            state.serialize_field("prefix", &self.prefix())?;
            state.serialize_field("all_workspace", &true)?;
            state.end()
        } else {
            let mut state = serializer.serialize_struct("WorkspacePathGrant", 1)?;
            state.serialize_field("prefix", &self.prefix())?;
            state.end()
        }
    }
}

/// Intersects path grants by retaining the narrowest prefix covered by both sides.
pub(super) fn intersect_path_grants(
    configured: &[WorkspacePathGrant],
    requested: &[WorkspacePathGrant],
) -> Vec<WorkspacePathGrant> {
    let mut grants = Vec::new();
    for configured in configured {
        for requested in requested {
            let intersection = if configured.covers(requested.prefix()) {
                Some(requested.clone())
            } else if requested.covers(configured.prefix()) {
                Some(configured.clone())
            } else {
                None
            };
            if let Some(intersection) = intersection {
                push_unique_grant(&mut grants, intersection);
            }
        }
    }
    grants
}

/// Appends a grant once while preserving deterministic discovery order.
fn push_unique_grant(grants: &mut Vec<WorkspacePathGrant>, grant: WorkspacePathGrant) {
    if !grants.contains(&grant) {
        grants.push(grant);
    }
}

/// Validates a configured workspace-relative grant prefix.
fn validate_workspace_grant_prefix(prefix: &str) -> Result<(), WorkspacePathError> {
    validate_workspace_relative_path(prefix)
}

/// Validates a workspace-relative path without resolving it as a filesystem path.
fn validate_workspace_relative_path(path: &str) -> Result<(), WorkspacePathError> {
    if path.starts_with('/') {
        return Err(WorkspacePathError::Absolute);
    }
    if path.as_bytes().get(1) == Some(&b':') {
        return Err(WorkspacePathError::WindowsDrivePrefix);
    }
    if path.contains('\\') {
        return Err(WorkspacePathError::PlatformSeparator);
    }

    for component in path.split('/') {
        if component.is_empty() {
            return Err(WorkspacePathError::EmptyComponent);
        }
        if matches!(component, "." | "..") {
            return Err(WorkspacePathError::DotComponent);
        }
    }

    Ok(())
}

impl std::fmt::Display for WorkspacePathError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyGrantPrefix => formatter
                .write_str("whole-workspace plugin grants must use explicit all-workspace grant"),
            Self::Absolute => formatter.write_str("workspace plugin paths must be relative"),
            Self::DotComponent => {
                formatter.write_str("workspace plugin paths must not contain . or .. components")
            }
            Self::EmptyComponent => {
                formatter.write_str("workspace plugin paths must not contain empty components")
            }
            Self::PlatformSeparator => {
                formatter.write_str("workspace plugin paths must use / separators")
            }
            Self::WindowsDrivePrefix => {
                formatter.write_str("workspace plugin paths must not use Windows drive prefixes")
            }
        }
    }
}

impl JsonSchema for WorkspacePathGrant {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("WorkspacePathGrant")
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        #[derive(JsonSchema)]
        #[schemars(deny_unknown_fields)]
        #[allow(dead_code)]
        struct WorkspacePathGrantSchema {
            /// Workspace-relative prefix. Empty requires `all_workspace: true`.
            prefix: String,
            /// Explicit marker for a whole-workspace grant.
            #[schemars(default)]
            all_workspace: Option<bool>,
        }

        WorkspacePathGrantSchema::json_schema(generator)
    }
}

#[cfg(test)]
/// Property-test helpers for workspace path grants.
pub mod tests {
    use super::{WorkspacePath, WorkspacePathError, WorkspacePathGrant, WorkspacePathRef};
    use crate::plugin::PluginCapabilityRef;
    use proptest::prelude::*;
    use serde_json::json;

    /// Generates valid workspace path grants, including the explicit whole-workspace grant.
    pub fn path_grant_strategy() -> impl Strategy<Value = WorkspacePathGrant> {
        prop::option::of("[a-z]{1,8}(/[a-z]{1,8}){0,3}").prop_map(|prefix| {
            prefix.map_or_else(WorkspacePathGrant::all_workspace, WorkspacePathGrant::new)
        })
    }

    /// Generates invalid workspace path strings.
    pub fn invalid_workspace_path_strategy() -> impl Strategy<Value = String> {
        prop_oneof![
            "[a-z]{1,8}/\\.\\.?(/[a-z]{1,8}){0,2}",
            "/[a-z]{1,8}(/[a-z]{1,8}){0,2}",
            "[a-z]{1,8}//[a-z]{1,8}",
            "[a-z]{1,8}\\\\[a-z]{1,8}",
            "[A-Z]:/[a-z]{1,8}",
            Just(String::new()),
        ]
    }

    /// Returns representative paths that should be covered by `grant`.
    #[must_use]
    pub fn grant_witness_paths(grant: &WorkspacePathGrant) -> [String; 2] {
        if grant.is_all_workspace() {
            [String::from("a"), String::from("a/b")]
        } else {
            [grant.prefix().to_owned(), format!("{}/a", grant.prefix())]
        }
    }

    #[test]
    fn workspace_path_grants_reject_traversal_and_non_normal_paths() {
        let invalid_paths = [
            "/docs/arch.md",
            "docs/../secrets",
            "docs/./arch.md",
            "docs//arch.md",
            "docs\\arch.md",
            "C:/docs/arch.md",
            "",
        ];

        for path in invalid_paths {
            assert!(
                PluginCapabilityRef::workspace_observe(path).is_err(),
                "{path:?} should not form an authorization request"
            );
        }

        for prefix in [
            "",
            "/docs",
            "docs/..",
            "docs/.",
            "docs//generated",
            "docs\\generated",
            "C:/docs",
        ] {
            assert!(
                WorkspacePathGrant::try_new(prefix).is_err(),
                "{prefix:?} should not form a grant"
            );
        }
    }

    #[test]
    fn whole_workspace_grants_are_explicit() {
        let grant = WorkspacePathGrant::all_workspace();
        let read = PluginCapabilityRef::workspace_observe("docs/arch.md")
            .expect("workspace path should be valid");

        assert_eq!(grant.prefix(), "");
        assert!(grant.is_all_workspace());
        assert!(grant.allows(match read {
            PluginCapabilityRef::WorkspaceObserve(path) => path,
            _ => unreachable!("workspace_observe should create read capability"),
        }));
        assert_eq!(
            WorkspacePathGrant::try_new(""),
            Err(WorkspacePathError::EmptyGrantPrefix)
        );
    }

    #[test]
    fn workspace_path_debug_redacts_normalized_paths() {
        let path = "docs/secret-workspace-path.txt";
        let borrowed = WorkspacePathRef::try_from(path).expect("path should validate");
        let owned = WorkspacePath::from_ref(borrowed);
        let grant = WorkspacePathGrant::new(path);

        for debug in [
            format!("{borrowed:?}"),
            format!("{owned:?}"),
            format!("{grant:?}"),
        ] {
            assert!(debug.contains("byte_len"));
            assert!(!debug.contains(path));
            assert!(!debug.contains("secret-workspace-path"));
        }
    }

    #[test]
    fn whole_workspace_grant_json_requires_explicit_marker() {
        let value = serde_json::to_value(WorkspacePathGrant::all_workspace())
            .expect("grant should serialize");

        assert_eq!(value, json!({"prefix": "", "all_workspace": true}));
        assert_eq!(
            serde_json::from_value::<WorkspacePathGrant>(value)
                .expect("explicit whole-workspace grant should deserialize"),
            WorkspacePathGrant::all_workspace()
        );
    }

    proptest! {
        #[test]
        fn owned_workspace_paths_round_trip_valid_path_vocabulary(path in "[a-z]{1,8}(/[a-z]{1,8}){0,3}") {
            let owned = WorkspacePath::try_new(path.clone()).expect("path should validate");

            prop_assert_eq!(owned.as_str(), path.as_str());
            prop_assert_eq!(owned.as_ref().as_str(), path.as_str());
            prop_assert_eq!(WorkspacePath::from_ref(owned.as_ref()), owned);
        }

        #[test]
        fn workspace_grant_construction_is_idempotent(prefix in prop::option::of("[a-z]{1,8}(/[a-z]{1,8}){0,3}")) {
            let first = prefix.map_or_else(WorkspacePathGrant::all_workspace, WorkspacePathGrant::new);
            let second = if first.is_all_workspace() {
                WorkspacePathGrant::all_workspace()
            } else {
                WorkspacePathGrant::new(first.prefix())
            };

            prop_assert_eq!(first, second);
        }

        #[test]
        fn workspace_grants_cover_only_their_normalized_subtree(
            prefix in "[a-z]{1,8}(/[a-z]{1,8}){0,3}",
            child in "[a-z]{1,8}",
        ) {
            let grant = WorkspacePathGrant::new(prefix.clone());
            let exact = WorkspacePath::try_new(prefix.clone()).expect("prefix should validate");
            let descendant = WorkspacePath::try_new(format!("{prefix}/{child}"))
                .expect("descendant should validate");
            let sibling = WorkspacePath::try_new(format!("{prefix}x"))
                .expect("sibling should validate");

            prop_assert!(grant.allows(exact.as_ref()));
            prop_assert!(grant.allows(descendant.as_ref()));
            prop_assert!(!grant.allows(sibling.as_ref()));
        }

        #[test]
        fn invalid_workspace_paths_cannot_form_authorization_refs(path in invalid_workspace_path_strategy()) {
            prop_assert!(WorkspacePath::try_new(path.clone()).is_err());
            prop_assert!(PluginCapabilityRef::workspace_observe(&path).is_err());
            prop_assert!(PluginCapabilityRef::workspace_artifact_write(&path).is_err());
        }
    }
}