kernex-skills 0.4.0

Skills.sh-compatible skill loader and trigger matcher for Kernex
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
//! Permission model for skills security.
//!
//! Skills declare permissions in their frontmatter, users approve them at install time,
//! and the runtime enforces them via sandbox profiles.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

/// Permission categories that a skill can request.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Permissions {
    /// File system paths the skill can access.
    /// Format: "read:path" or "write:path" or "!path" (deny).
    #[serde(default)]
    pub files: Vec<String>,

    /// Network hosts the skill can contact.
    /// Supports wildcards: "*.example.com", "api.github.com".
    #[serde(default)]
    pub network: Vec<String>,

    /// Environment variables the skill can read.
    #[serde(default)]
    pub env: Vec<String>,

    /// Commands/binaries the skill can execute.
    #[serde(default)]
    pub commands: Vec<String>,
}

impl Permissions {
    /// Check if the skill has any permissions declared.
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
            && self.network.is_empty()
            && self.env.is_empty()
            && self.commands.is_empty()
    }

    /// Get all read paths.
    pub fn read_paths(&self) -> Vec<&str> {
        self.files
            .iter()
            .filter_map(|p| p.strip_prefix("read:"))
            .collect()
    }

    /// Get all write paths.
    pub fn write_paths(&self) -> Vec<&str> {
        self.files
            .iter()
            .filter_map(|p| p.strip_prefix("write:"))
            .collect()
    }

    /// Get all denied paths.
    pub fn denied_paths(&self) -> Vec<&str> {
        self.files
            .iter()
            .filter_map(|p| p.strip_prefix('!'))
            .collect()
    }
}

/// Trust level assigned to a skill based on its source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum TrustLevel {
    /// Official organizations (anthropics, kernex-dev, modelcontextprotocol).
    /// Permissions are shown but can be auto-approved.
    Verified,

    /// Listed on skills.sh but from community authors.
    /// Requires explicit user approval.
    Community,

    /// User-created skills in local directory.
    /// Full trust, no approval needed.
    Local,

    /// Unknown source, unverified author.
    /// Requires explicit approval with high-risk warnings.
    #[default]
    Untrusted,
}

impl TrustLevel {
    /// Whether this trust level requires explicit user approval.
    pub fn requires_approval(&self) -> bool {
        !matches!(self, Self::Local)
    }

    /// Whether high-risk permission warnings should be shown.
    pub fn show_high_risk_warnings(&self) -> bool {
        matches!(self, Self::Untrusted | Self::Community)
    }
}

/// High-risk permission patterns that trigger warnings.
pub struct RiskDetector {
    sensitive_paths: Vec<&'static str>,
    sensitive_env_patterns: Vec<&'static str>,
}

impl Default for RiskDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl RiskDetector {
    /// Create a new risk detector with default patterns.
    pub fn new() -> Self {
        Self {
            sensitive_paths: vec![
                "~/.ssh",
                "~/.gnupg",
                "~/.aws",
                "~/.azure",
                "~/.config/gcloud",
                "~/.kube",
                "~/.docker",
                "/etc/passwd",
                "/etc/shadow",
            ],
            sensitive_env_patterns: vec![
                "TOKEN",
                "SECRET",
                "KEY",
                "PASSWORD",
                "CREDENTIAL",
                "PRIVATE",
            ],
        }
    }

    /// Detect high-risk file permissions.
    pub fn detect_risky_paths(&self, permissions: &Permissions) -> Vec<RiskWarning> {
        let mut warnings = Vec::new();

        for path in &permissions.files {
            let clean_path = path
                .strip_prefix("read:")
                .or_else(|| path.strip_prefix("write:"))
                .unwrap_or(path);

            for sensitive in &self.sensitive_paths {
                if clean_path.contains(sensitive) || path_matches_pattern(clean_path, sensitive) {
                    warnings.push(RiskWarning {
                        category: RiskCategory::SensitiveFile,
                        description: format!("Access to {}", sensitive),
                        pattern: path.clone(),
                    });
                    break;
                }
            }

            // Check for hidden files access
            if clean_path.contains("/.*") || clean_path.ends_with("/.*") {
                warnings.push(RiskWarning {
                    category: RiskCategory::HiddenFiles,
                    description: "Access to hidden files/directories".into(),
                    pattern: path.clone(),
                });
            }
        }

        warnings
    }

    /// Detect high-risk environment variable permissions.
    pub fn detect_risky_env(&self, permissions: &Permissions) -> Vec<RiskWarning> {
        let mut warnings = Vec::new();

        for env_var in &permissions.env {
            let upper = env_var.to_uppercase();
            for pattern in &self.sensitive_env_patterns {
                if upper.contains(pattern) {
                    warnings.push(RiskWarning {
                        category: RiskCategory::SensitiveEnv,
                        description: format!("Access to {} environment variable", env_var),
                        pattern: env_var.clone(),
                    });
                    break;
                }
            }
        }

        warnings
    }

    /// Detect unrestricted network access.
    pub fn detect_risky_network(&self, permissions: &Permissions) -> Vec<RiskWarning> {
        let mut warnings = Vec::new();

        for host in &permissions.network {
            if host == "*" {
                warnings.push(RiskWarning {
                    category: RiskCategory::UnrestrictedNetwork,
                    description: "Unrestricted network access to any host".into(),
                    pattern: host.clone(),
                });
            }
        }

        warnings
    }

    /// Run all risk detection checks.
    pub fn detect_all_risks(&self, permissions: &Permissions) -> Vec<RiskWarning> {
        let mut warnings = Vec::new();
        warnings.extend(self.detect_risky_paths(permissions));
        warnings.extend(self.detect_risky_env(permissions));
        warnings.extend(self.detect_risky_network(permissions));
        warnings
    }

    /// Check if any high-risk permissions are present.
    pub fn has_high_risk(&self, permissions: &Permissions) -> bool {
        !self.detect_all_risks(permissions).is_empty()
    }
}

/// A warning about a risky permission.
#[derive(Debug, Clone)]
pub struct RiskWarning {
    pub category: RiskCategory,
    pub description: String,
    pub pattern: String,
}

/// Categories of permission risks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RiskCategory {
    /// Access to SSH keys, GPG keys, cloud credentials.
    SensitiveFile,
    /// Access to hidden files/directories.
    HiddenFiles,
    /// Access to environment variables containing secrets.
    SensitiveEnv,
    /// Unrestricted network access.
    UnrestrictedNetwork,
}

impl RiskCategory {
    /// Get a human-readable label for this risk category.
    pub fn label(&self) -> &'static str {
        match self {
            Self::SensitiveFile => "Sensitive Files",
            Self::HiddenFiles => "Hidden Files",
            Self::SensitiveEnv => "Sensitive Environment",
            Self::UnrestrictedNetwork => "Unrestricted Network",
        }
    }
}

/// Check if a path matches a pattern (simple glob support).
fn path_matches_pattern(path: &str, pattern: &str) -> bool {
    if pattern.contains('*') {
        // Simple wildcard matching
        let parts: Vec<&str> = pattern.split('*').collect();
        if parts.len() == 2 {
            let (prefix, suffix) = (parts[0], parts[1]);
            return path.starts_with(prefix) && path.ends_with(suffix);
        }
    }
    path.starts_with(pattern)
}

/// Trusted organizations whose skills can be auto-approved.
pub const DEFAULT_TRUSTED_ORGS: &[&str] = &["anthropics", "kernex-dev", "modelcontextprotocol"];

/// Determine trust level based on skill source.
pub fn determine_trust_level(source: &str, trusted_orgs: &HashSet<String>) -> TrustLevel {
    // Local skills (no source URL)
    if source.is_empty() || source.starts_with('/') || source.starts_with('~') {
        return TrustLevel::Local;
    }

    // GitHub-style org/repo format
    if let Some(org) = source.split('/').next() {
        if trusted_orgs.contains(org) || DEFAULT_TRUSTED_ORGS.contains(&org) {
            return TrustLevel::Verified;
        }
    }

    // skills.sh source
    if source.contains("skills.sh") {
        return TrustLevel::Community;
    }

    TrustLevel::Untrusted
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_permissions_is_empty() {
        assert!(Permissions::default().is_empty());
        assert!(!Permissions {
            files: vec!["read:~/.config".into()],
            ..Default::default()
        }
        .is_empty());
    }

    #[test]
    fn test_permissions_path_helpers() {
        let perms = Permissions {
            files: vec![
                "read:~/.config/app".into(),
                "write:~/.data/app".into(),
                "!~/.ssh".into(),
            ],
            ..Default::default()
        };
        assert_eq!(perms.read_paths(), vec!["~/.config/app"]);
        assert_eq!(perms.write_paths(), vec!["~/.data/app"]);
        assert_eq!(perms.denied_paths(), vec!["~/.ssh"]);
    }

    #[test]
    fn test_trust_level_requires_approval() {
        assert!(!TrustLevel::Local.requires_approval());
        assert!(TrustLevel::Verified.requires_approval());
        assert!(TrustLevel::Community.requires_approval());
        assert!(TrustLevel::Untrusted.requires_approval());
    }

    #[test]
    fn test_determine_trust_level_local() {
        let trusted = HashSet::new();
        assert_eq!(determine_trust_level("", &trusted), TrustLevel::Local);
        assert_eq!(
            determine_trust_level("/home/user/.kx/skills/my-skill", &trusted),
            TrustLevel::Local
        );
        assert_eq!(
            determine_trust_level("~/.kx/skills/my-skill", &trusted),
            TrustLevel::Local
        );
    }

    #[test]
    fn test_determine_trust_level_verified() {
        let trusted = HashSet::new();
        assert_eq!(
            determine_trust_level("anthropics/skills", &trusted),
            TrustLevel::Verified
        );
        assert_eq!(
            determine_trust_level("kernex-dev/my-skill", &trusted),
            TrustLevel::Verified
        );
    }

    #[test]
    fn test_determine_trust_level_custom_trusted() {
        let mut trusted = HashSet::new();
        trusted.insert("my-org".into());
        assert_eq!(
            determine_trust_level("my-org/skill", &trusted),
            TrustLevel::Verified
        );
    }

    #[test]
    fn test_determine_trust_level_untrusted() {
        let trusted = HashSet::new();
        assert_eq!(
            determine_trust_level("random-user/skill", &trusted),
            TrustLevel::Untrusted
        );
    }

    #[test]
    fn test_risk_detector_sensitive_paths() {
        let detector = RiskDetector::new();
        let perms = Permissions {
            files: vec!["read:~/.ssh/id_rsa".into()],
            ..Default::default()
        };
        let risks = detector.detect_risky_paths(&perms);
        assert_eq!(risks.len(), 1);
        assert_eq!(risks[0].category, RiskCategory::SensitiveFile);
    }

    #[test]
    fn test_risk_detector_sensitive_env() {
        let detector = RiskDetector::new();
        let perms = Permissions {
            env: vec!["GITHUB_TOKEN".into(), "HOME".into()],
            ..Default::default()
        };
        let risks = detector.detect_risky_env(&perms);
        assert_eq!(risks.len(), 1);
        assert!(risks[0].description.contains("GITHUB_TOKEN"));
    }

    #[test]
    fn test_risk_detector_unrestricted_network() {
        let detector = RiskDetector::new();
        let perms = Permissions {
            network: vec!["*".into()],
            ..Default::default()
        };
        let risks = detector.detect_risky_network(&perms);
        assert_eq!(risks.len(), 1);
        assert_eq!(risks[0].category, RiskCategory::UnrestrictedNetwork);
    }

    #[test]
    fn test_risk_detector_no_risks() {
        let detector = RiskDetector::new();
        let perms = Permissions {
            files: vec!["read:~/.config/myapp".into()],
            network: vec!["api.github.com".into()],
            env: vec!["HOME".into()],
            commands: vec!["npx".into()],
        };
        assert!(!detector.has_high_risk(&perms));
    }

    #[test]
    fn test_path_matches_pattern() {
        // Exact prefix matching
        assert!(path_matches_pattern("~/.ssh/id_rsa", "~/.ssh"));
        assert!(path_matches_pattern("/etc/passwd", "/etc/passwd"));
        assert!(!path_matches_pattern("/home/user/.config", "~/.ssh"));
        // Wildcard matching
        assert!(path_matches_pattern("~/.config/app/data", "~/.config/*"));
        assert!(path_matches_pattern("logs.txt", "*.txt"));
    }
}