Skip to main content

systemprompt_extension/registry/
validation.rs

1use super::ExtensionRegistry;
2use crate::Extension;
3use crate::error::LoaderError;
4use std::collections::HashMap;
5use std::sync::Arc;
6
7pub const RESERVED_PATHS: &[&str] = &[
8    "/api/v1/oauth",
9    "/api/v1/users",
10    "/api/v1/agents",
11    "/api/v1/mcp",
12    "/api/v1/stream",
13    "/api/v1/content",
14    "/api/v1/files",
15    "/api/v1/analytics",
16    "/api/v1/scheduler",
17    "/api/v1/core",
18    "/api/v1/admin",
19    "/.well-known",
20];
21
22impl ExtensionRegistry {
23    pub fn validate_dependencies(&self) -> Result<(), LoaderError> {
24        for ext in self.extensions.values() {
25            for dep_id in ext.dependencies() {
26                if !self.extensions.contains_key(dep_id) {
27                    return Err(LoaderError::MissingDependency {
28                        extension: ext.id().to_string(),
29                        dependency: dep_id.to_string(),
30                    });
31                }
32            }
33        }
34
35        detect_cycles(&self.extensions)
36    }
37
38    pub fn validate_api_paths(&self, ctx: &dyn crate::ExtensionContext) -> Result<(), LoaderError> {
39        for ext in self.extensions.values() {
40            if let Some(router_config) = ext.router(ctx) {
41                let base_path = router_config.base_path;
42
43                if !base_path.starts_with("/api/") {
44                    return Err(LoaderError::InvalidBasePath {
45                        extension: ext.id().to_string(),
46                        path: base_path.to_string(),
47                    });
48                }
49
50                for reserved in RESERVED_PATHS {
51                    if base_path.starts_with(reserved) {
52                        return Err(LoaderError::ReservedPathCollision {
53                            extension: ext.id().to_string(),
54                            path: base_path.to_string(),
55                        });
56                    }
57                }
58            }
59        }
60        Ok(())
61    }
62}
63
64fn detect_cycles(extensions: &HashMap<String, Arc<dyn Extension>>) -> Result<(), LoaderError> {
65    const WHITE: u8 = 0;
66    const GRAY: u8 = 1;
67    const BLACK: u8 = 2;
68
69    fn dfs<'a>(
70        node: &'a str,
71        extensions: &'a HashMap<String, Arc<dyn Extension>>,
72        color: &mut HashMap<&'a str, u8>,
73        path: &mut Vec<&'a str>,
74    ) -> Result<(), Vec<&'a str>> {
75        color.insert(node, GRAY);
76        path.push(node);
77
78        if let Some(ext) = extensions.get(node) {
79            for dep_id in ext.dependencies() {
80                match color.get(dep_id) {
81                    Some(&GRAY) => {
82                        path.push(dep_id);
83                        return Err(path.clone());
84                    },
85                    Some(&WHITE) | None => {
86                        dfs(dep_id, extensions, color, path)?;
87                    },
88                    _ => {},
89                }
90            }
91        }
92
93        path.pop();
94        color.insert(node, BLACK);
95        Ok(())
96    }
97
98    let mut color: HashMap<&str, u8> = extensions.keys().map(|id| (id.as_str(), WHITE)).collect();
99
100    let mut path = Vec::new();
101    for id in extensions.keys() {
102        if color.get(id.as_str()) == Some(&WHITE) {
103            if let Err(cycle_path) = dfs(id.as_str(), extensions, &mut color, &mut path) {
104                let Some(&cycle_start) = cycle_path.last() else {
105                    return Err(LoaderError::CircularDependency {
106                        chain: "unknown cycle".to_string(),
107                    });
108                };
109                let cycle_start_idx = cycle_path
110                    .iter()
111                    .position(|&x| x == cycle_start)
112                    .unwrap_or(0);
113                let cycle: Vec<_> = cycle_path[cycle_start_idx..].to_vec();
114
115                return Err(LoaderError::CircularDependency {
116                    chain: cycle.join(" -> "),
117                });
118            }
119        }
120    }
121
122    Ok(())
123}