Skip to main content

snip_sync/
premade.rs

1use serde::Deserialize;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5const MAX_PREMADE_COMMAND_LENGTH: usize = 1024;
6const MAX_PREMADE_DESCRIPTION_LENGTH: usize = 1024;
7use tonic::Status;
8
9use crate::toml_escapes::fix_invalid_toml_escapes;
10
11#[derive(Debug, Clone)]
12pub struct PremadeLibrary {
13    pub name: String,
14    pub filename: String,
15    pub description: String,
16    pub snippet_count: i32,
17    pub tags: Vec<String>,
18}
19
20#[derive(Debug, Deserialize)]
21struct Snippet {
22    #[serde(rename = "command", alias = "Command", default)]
23    command: Option<String>,
24    #[serde(rename = "Description", default)]
25    description: Option<String>,
26    #[serde(rename = "Tag", default)]
27    tags: Vec<String>,
28    #[serde(flatten, default)]
29    _extra: std::collections::HashMap<String, serde_json::Value>,
30}
31
32#[derive(Debug, Deserialize)]
33struct SnippetFile {
34    #[serde(rename = "Description", default)]
35    description: Option<String>,
36    #[serde(rename = "Snippets", default)]
37    snippets: Vec<Snippet>,
38}
39
40#[derive(Debug, Clone)]
41pub struct PremadeManager {
42    dir: PathBuf,
43    libraries: Vec<PremadeLibrary>,
44}
45
46impl PremadeManager {
47    pub fn new(dir: PathBuf) -> Self {
48        if !dir.exists() {
49            if let Err(e) = fs::create_dir_all(&dir) {
50                tracing::warn!(
51                    "Failed to create premade libraries directory {}: {}",
52                    dir.display(),
53                    e
54                );
55            } else {
56                tracing::info!("Created premade libraries directory: {}", dir.display());
57            }
58        }
59
60        let libraries = Self::scan_directory(&dir);
61        Self { dir, libraries }
62    }
63
64    fn scan_directory(dir: &Path) -> Vec<PremadeLibrary> {
65        if !dir.exists() {
66            tracing::warn!(
67                "Premade libraries directory does not exist: {}",
68                dir.display()
69            );
70            return Vec::new();
71        }
72
73        let mut libraries = Vec::new();
74
75        let entries = match fs::read_dir(dir) {
76            Ok(entries) => entries,
77            Err(e) => {
78                tracing::error!("Failed to read premade libraries directory: {}", e);
79                return Vec::new();
80            }
81        };
82
83        for entry in entries.flatten() {
84            let path = entry.path();
85            if path.extension().and_then(|s| s.to_str()) != Some("toml") {
86                continue;
87            }
88
89            let filename = match path.file_stem().and_then(|s| s.to_str()) {
90                Some(name) => name.to_string(),
91                None => continue,
92            };
93
94            let content = match fs::read_to_string(&path) {
95                Ok(c) => c,
96                Err(e) => {
97                    tracing::warn!("Failed to read premade library {}: {}", filename, e);
98                    continue;
99                }
100            };
101
102            let content = fix_invalid_toml_escapes(&content);
103
104            let snippet_file: SnippetFile = match toml::from_str(&content) {
105                Ok(sf) => sf,
106                Err(e) => {
107                    tracing::warn!("Failed to parse premade library {}: {}", filename, e);
108                    continue;
109                }
110            };
111
112            if snippet_file.snippets.is_empty() {
113                tracing::warn!("Premade library '{}' has no snippets, skipping", filename);
114                continue;
115            }
116
117            let valid_snippets: Vec<_> = snippet_file
118                .snippets
119                .into_iter()
120                .filter(|s| {
121                    let cmd = s.command.as_deref().unwrap_or("");
122                    if cmd.is_empty() {
123                        tracing::warn!(
124                            "Premade library '{}': skipping snippet with empty command",
125                            filename
126                        );
127                        return false;
128                    }
129                    if cmd.len() > MAX_PREMADE_COMMAND_LENGTH {
130                        tracing::warn!(
131                            "Premade library '{}': skipping snippet with command exceeding {} bytes",
132                            filename,
133                            MAX_PREMADE_COMMAND_LENGTH
134                        );
135                        return false;
136                    }
137                    if let Some(ref desc) = s.description
138                        && desc.len() > MAX_PREMADE_DESCRIPTION_LENGTH
139                    {
140                        tracing::warn!(
141                            "Premade library '{}': skipping snippet with description exceeding {} bytes",
142                            filename,
143                            MAX_PREMADE_DESCRIPTION_LENGTH
144                        );
145                        return false;
146                    }
147                    true
148                })
149                .collect();
150
151            if valid_snippets.is_empty() {
152                tracing::warn!(
153                    "Premade library '{}' has no valid snippets, skipping",
154                    filename
155                );
156                continue;
157            }
158
159            let snippet_count = valid_snippets.len() as i32;
160
161            let description = snippet_file.description.unwrap_or_else(|| filename.clone());
162
163            let mut all_tags: Vec<String> = Vec::new();
164            for s in &valid_snippets {
165                for tag in &s.tags {
166                    if !all_tags.contains(tag) {
167                        all_tags.push(tag.clone());
168                    }
169                }
170            }
171
172            libraries.push(PremadeLibrary {
173                name: filename.clone(),
174                filename,
175                description,
176                snippet_count,
177                tags: all_tags,
178            });
179        }
180
181        libraries.sort_by(|a, b| a.filename.cmp(&b.filename));
182        tracing::info!("Loaded {} premade libraries", libraries.len());
183        libraries
184    }
185
186    pub fn list(&self) -> Vec<PremadeLibrary> {
187        self.libraries.clone()
188    }
189
190    /// Search premade libraries by query string.
191    /// Matches against library name, description, and tags.
192    pub fn search(&self, query: &str) -> Vec<PremadeLibrary> {
193        let q = query.to_lowercase();
194        self.libraries
195            .iter()
196            .filter(|lib| {
197                lib.name.to_lowercase().contains(&q)
198                    || lib.description.to_lowercase().contains(&q)
199                    || lib.tags.iter().any(|t| t.to_lowercase().contains(&q))
200            })
201            .cloned()
202            .collect()
203    }
204
205    pub fn get(&self, filename: &str) -> Result<String, Status> {
206        let path = self.dir.join(format!("{}.toml", filename));
207
208        let canonical_dir = self
209            .dir
210            .canonicalize()
211            .map_err(|_| Status::internal("failed to canonicalize premade directory"))?;
212        let canonical_path = path
213            .canonicalize()
214            .map_err(|_| Status::invalid_argument("Invalid filename: cannot canonicalize path"))?;
215
216        if !canonical_path.starts_with(&canonical_dir) {
217            return Err(Status::invalid_argument(
218                "Invalid filename: path traversal detected",
219            ));
220        }
221
222        fs::read_to_string(&canonical_path)
223            .map_err(|e| {
224                if e.kind() == std::io::ErrorKind::NotFound {
225                    Status::not_found(format!("Premade library '{}' not found", filename))
226                } else {
227                    tracing::error!("Failed to read premade library: {}", e);
228                    Status::internal("Internal error")
229                }
230            })
231            .map(|content| fix_invalid_toml_escapes(&content))
232    }
233
234    pub fn is_empty(&self) -> bool {
235        self.libraries.is_empty()
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use tempfile::TempDir;
243
244    #[test]
245    fn test_get_valid_library() {
246        let dir = TempDir::new().unwrap();
247        let toml_content = r#"
248Description = "Test library"
249
250[[Snippets]]
251Command = "echo hello"
252Description = "Say hello"
253"#;
254        fs::write(dir.path().join("test.toml"), toml_content).unwrap();
255        let manager = PremadeManager::new(dir.path().to_path_buf());
256        let result = manager.get("test");
257        assert!(result.is_ok());
258        assert!(result.unwrap().contains("echo hello"));
259    }
260
261    /// Directory holding the premade libraries that ship with the server.
262    fn shipped_premade_dir() -> std::path::PathBuf {
263        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("premade-libraries")
264    }
265
266    #[test]
267    fn test_every_shipped_premade_library_is_valid_toml() {
268        let dir = shipped_premade_dir();
269        let mut entries: Vec<_> = fs::read_dir(&dir)
270            .unwrap_or_else(|e| panic!("read {}: {e}", dir.display()))
271            .flatten()
272            .collect();
273        entries.sort_by_key(|e| e.path());
274
275        let mut checked = 0usize;
276        for entry in entries {
277            let path = entry.path();
278            if path.extension().and_then(|s| s.to_str()) != Some("toml") {
279                continue;
280            }
281            let raw = fs::read_to_string(&path).unwrap();
282            // Parse the SHIPPED bytes verbatim — no escape fixing, no
283            // rewriting. A shipped file must already be valid TOML.
284            let parsed: SnippetFile = toml::from_str(&raw).unwrap_or_else(|e| {
285                panic!(
286                    "shipped premade library {} is not valid TOML: {e}",
287                    path.display()
288                )
289            });
290            assert!(
291                !parsed.snippets.is_empty(),
292                "shipped premade library {} has no snippets",
293                path.display()
294            );
295            for snippet in &parsed.snippets {
296                let cmd = snippet.command.as_deref().unwrap_or("");
297                assert!(
298                    !cmd.is_empty(),
299                    "snippet in {} has no command — the server deserializer \
300                     and the shipped key casing disagree",
301                    path.display()
302                );
303            }
304            checked += 1;
305        }
306        assert!(
307            checked > 0,
308            "no shipped premade libraries found in {}",
309            dir.display()
310        );
311    }
312
313    #[test]
314    fn test_premade_manager_lists_all_shipped_libraries() {
315        let manager = PremadeManager::new(shipped_premade_dir());
316        let libs = manager.list();
317        let names: Vec<&str> = libs.iter().map(|l| l.name.as_str()).collect();
318        assert!(
319            names.contains(&"bash-scripts"),
320            "bash-scripts missing from shipped premade libraries: {names:?}"
321        );
322        for lib in &libs {
323            assert!(
324                lib.snippet_count > 0,
325                "library {} reported {} snippets",
326                lib.name,
327                lib.snippet_count
328            );
329        }
330    }
331
332    #[test]
333    fn test_bash_scripts_topcmds_command_parses() {
334        let path = shipped_premade_dir().join("bash-scripts.toml");
335        let raw = fs::read_to_string(&path).unwrap();
336        let parsed: SnippetFile = toml::from_str(&raw).unwrap();
337        let cmd = parsed
338            .snippets
339            .iter()
340            .find(|s| s.command.as_deref().unwrap_or("").contains("topcmds"))
341            .and_then(|s| s.command.clone())
342            .expect("topcmds snippet");
343        // The awk program must reference field 2 (`$2`), never an invalid
344        // TOML escape.
345        assert!(cmd.contains("{print $2}"), "unexpected command: {cmd}");
346    }
347
348    #[test]
349    fn test_get_nonexistent_library() {
350        let dir = TempDir::new().unwrap();
351        let manager = PremadeManager::new(dir.path().to_path_buf());
352        let result = manager.get("nonexistent");
353        assert!(result.is_err());
354    }
355
356    #[test]
357    fn test_get_path_traversal_rejected() {
358        let dir = TempDir::new().unwrap();
359        let manager = PremadeManager::new(dir.path().to_path_buf());
360        let result = manager.get("../../etc/passwd");
361        assert!(result.is_err());
362        let err = result.unwrap_err();
363        // When canonicalize fails, we reject for safety (can't verify path is safe)
364        assert!(err.message().contains("cannot canonicalize"));
365    }
366
367    #[test]
368    fn test_get_dot_dot_slash_rejected() {
369        let dir = TempDir::new().unwrap();
370        let manager = PremadeManager::new(dir.path().to_path_buf());
371        let result = manager.get("../escape");
372        assert!(result.is_err());
373    }
374
375    #[test]
376    fn test_fix_invalid_toml_escapes_backslash_angle() {
377        let input = r#"command = "echo \<hello\>""#;
378        let output = fix_invalid_toml_escapes(input);
379        assert!(output.contains("'echo \\<hello\\>'"));
380    }
381
382    #[test]
383    fn test_fix_invalid_toml_escapes_no_fix_needed() {
384        let input = r#"command = "echo normal""#;
385        let output = fix_invalid_toml_escapes(input);
386        assert_eq!(output, input);
387    }
388
389    #[test]
390    fn test_scan_directory_empty() {
391        let dir = TempDir::new().unwrap();
392        let manager = PremadeManager::new(dir.path().to_path_buf());
393        assert!(manager.is_empty());
394    }
395
396    #[test]
397    fn test_scan_directory_with_valid_library() {
398        let dir = TempDir::new().unwrap();
399        let toml_content = r#"
400Description = "Docker snippets"
401
402[[Snippets]]
403Command = "docker ps"
404Description = "List containers"
405"#;
406        fs::write(dir.path().join("docker.toml"), toml_content).unwrap();
407        let manager = PremadeManager::new(dir.path().to_path_buf());
408        assert_eq!(manager.list().len(), 1);
409        assert_eq!(manager.list()[0].name, "docker");
410    }
411
412    #[test]
413    fn test_scan_directory_skips_non_toml() {
414        let dir = TempDir::new().unwrap();
415        fs::write(dir.path().join("readme.txt"), "not a toml").unwrap();
416        let manager = PremadeManager::new(dir.path().to_path_buf());
417        assert!(manager.is_empty());
418    }
419
420    #[test]
421    fn test_scan_directory_skips_empty_snippets() {
422        let dir = TempDir::new().unwrap();
423        let toml_content = r#"
424Description = "Empty library"
425
426[[Snippets]]
427Command = ""
428Description = "Empty command"
429"#;
430        fs::write(dir.path().join("empty.toml"), toml_content).unwrap();
431        let manager = PremadeManager::new(dir.path().to_path_buf());
432        assert!(manager.is_empty());
433    }
434
435    #[test]
436    fn test_search_by_name() {
437        let dir = TempDir::new().unwrap();
438        let toml1 = r#"
439Description = "Docker containers"
440
441[[Snippets]]
442Command = "docker ps"
443Description = "List containers"
444Tag = ["docker"]
445"#;
446        let toml2 = r#"
447Description = "Git commands"
448
449[[Snippets]]
450Command = "git status"
451Description = "Check status"
452Tag = ["git"]
453"#;
454        fs::write(dir.path().join("docker.toml"), toml1).unwrap();
455        fs::write(dir.path().join("git.toml"), toml2).unwrap();
456        let manager = PremadeManager::new(dir.path().to_path_buf());
457        let results = manager.search("docker");
458        assert_eq!(results.len(), 1);
459        assert_eq!(results[0].name, "docker");
460    }
461
462    #[test]
463    fn test_search_by_description() {
464        let dir = TempDir::new().unwrap();
465        let toml1 = r#"
466Description = "Container orchestration"
467
468[[Snippets]]
469Command = "docker compose up"
470Description = "Start services"
471Tag = ["docker"]
472"#;
473        fs::write(dir.path().join("docker.toml"), toml1).unwrap();
474        let manager = PremadeManager::new(dir.path().to_path_buf());
475        let results = manager.search("container");
476        assert_eq!(results.len(), 1);
477        assert_eq!(results[0].name, "docker");
478    }
479
480    #[test]
481    fn test_search_by_tag() {
482        let dir = TempDir::new().unwrap();
483        let toml1 = r#"
484Description = "Docker basics"
485
486[[Snippets]]
487Command = "docker ps"
488Description = "List"
489Tag = ["docker", "containers"]
490"#;
491        fs::write(dir.path().join("docker.toml"), toml1).unwrap();
492        let manager = PremadeManager::new(dir.path().to_path_buf());
493        let results = manager.search("containers");
494        assert_eq!(results.len(), 1);
495        assert_eq!(results[0].name, "docker");
496        assert!(results[0].tags.contains(&"docker".to_string()));
497        assert!(results[0].tags.contains(&"containers".to_string()));
498    }
499
500    #[test]
501    fn test_search_case_insensitive() {
502        let dir = TempDir::new().unwrap();
503        let toml1 = r#"
504Description = "Docker commands"
505
506[[Snippets]]
507Command = "docker ps"
508Description = "List"
509Tag = ["docker"]
510"#;
511        fs::write(dir.path().join("docker.toml"), toml1).unwrap();
512        let manager = PremadeManager::new(dir.path().to_path_buf());
513        let results = manager.search("DOCKER");
514        assert_eq!(results.len(), 1);
515    }
516
517    #[test]
518    fn test_search_no_results() {
519        let dir = TempDir::new().unwrap();
520        let toml1 = r#"
521Description = "Docker commands"
522
523[[Snippets]]
524Command = "docker ps"
525Description = "List"
526Tag = ["docker"]
527"#;
528        fs::write(dir.path().join("docker.toml"), toml1).unwrap();
529        let manager = PremadeManager::new(dir.path().to_path_buf());
530        let results = manager.search("nonexistent");
531        assert!(results.is_empty());
532    }
533
534    #[test]
535    fn test_scan_collects_tags() {
536        let dir = TempDir::new().unwrap();
537        let toml_content = r#"
538Description = "Multi-tag library"
539
540[[Snippets]]
541Command = "docker ps"
542Description = "List"
543Tag = ["docker", "containers"]
544
545[[Snippets]]
546Command = "docker images"
547Description = "Images"
548Tag = ["docker", "images"]
549"#;
550        fs::write(dir.path().join("multi.toml"), toml_content).unwrap();
551        let manager = PremadeManager::new(dir.path().to_path_buf());
552        let libs = manager.list();
553        assert_eq!(libs.len(), 1);
554        assert!(libs[0].tags.contains(&"docker".to_string()));
555        assert!(libs[0].tags.contains(&"containers".to_string()));
556        assert!(libs[0].tags.contains(&"images".to_string()));
557        assert_eq!(libs[0].snippet_count, 2);
558    }
559}