swadhinbiswas 📦 v2.0.8: security fixes, documentation, testing improvements · 7/28/2026
3e270a0
199 lines · 6.4 KB
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
use arc_swap::ArcSwap;
use hyper::Method;
use notify::{Config, Event, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::{error, info, warn};

use crate::router::Router;

use crate::middleware::{Middleware, Next};
use crate::ResponseBody;
use async_trait::async_trait;
use http_body_util::BodyExt;
use hyper::{Request, Response};

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct GatewayRoute {
    pub upstream: String,
    pub rate_limit_capacity: Option<u64>,
    pub rate_limit_replenish_rate: Option<u64>,
    pub wasm_plugin: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct GatewayConfigData {
    pub routes: HashMap<String, HashMap<String, GatewayRoute>>, // path -> { method -> route }
    pub global_rate_limit: Option<u64>,
}

#[derive(Clone)]
pub struct GatewayRouter {
    pub inner: Router<GatewayRoute>,
}

pub struct GatewayState {
    pub config: ArcSwap<GatewayConfigData>,
    pub router: ArcSwap<GatewayRouter>,
    config_path: PathBuf,
}

impl GatewayState {
    pub fn new(path: impl AsRef<Path>) -> Arc<Self> {
        let path = path.as_ref().to_path_buf();
        let (config, router) = Self::load_config(&path).unwrap_or_else(|e| {
            warn!("Failed to load gateway config from {:?}: {}", path, e);
            (GatewayConfigData::default(), GatewayRouter { inner: Router::new() })
        });

        Arc::new(Self {
            config: ArcSwap::from_pointee(config),
            router: ArcSwap::from_pointee(router),
            config_path: path,
        })
    }

    fn load_config(path: &Path) -> anyhow::Result<(GatewayConfigData, GatewayRouter)> {
        // Security: check file permissions before reading
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(meta) = std::fs::metadata(path) {
                let mode = meta.permissions().mode();
                // Check if "other" has write permission (bit 1 of mode)
                if mode & 0o002 != 0 {
                    warn!(
                        path = %path.display(),
                        "Gateway config file is world-writable (mode {:o}). \
                         This is a security risk — an attacker could redirect traffic. \
                         Consider restricting permissions to 0600.",
                        mode
                    );
                }
            }
        }

        let data = std::fs::read_to_string(path)?;
        let config: GatewayConfigData = serde_json::from_str(&data)?;

        let mut router = Router::new();
        for (path_pattern, methods) in &config.routes {
            for (method_str, route) in methods {
                let method = match method_str.to_uppercase().as_str() {
                    "GET" => Method::GET,
                    "POST" => Method::POST,
                    "PUT" => Method::PUT,
                    "DELETE" => Method::DELETE,
                    "PATCH" => Method::PATCH,
                    "OPTIONS" => Method::OPTIONS,
                    _ => continue,
                };
                let _ = router.insert(method, path_pattern, route.clone());
            }
        }

        Ok((config, GatewayRouter { inner: router }))
    }

    pub fn watch(self: Arc<Self>) -> anyhow::Result<()> {
        let (tx, mut rx) = mpsc::channel(10);

        let mut watcher = notify::RecommendedWatcher::new(
            move |res: Result<Event, notify::Error>| {
                if let Ok(event) = res {
                    if event.kind.is_modify() || event.kind.is_create() {
                        let _ = tx.blocking_send(());
                    }
                }
            },
            Config::default(),
        )?;

        watcher.watch(&self.config_path, RecursiveMode::NonRecursive)?;

        tokio::spawn(async move {
            // Keep watcher alive by moving it into this task
            let _watcher = watcher;

            while rx.recv().await.is_some() {
                // Debounce
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                info!("Gateway configuration file changed, reloading...");
                match Self::load_config(&self.config_path) {
                    Ok((config, router)) => {
                        self.config.store(Arc::new(config));
                        self.router.store(Arc::new(router));
                        info!("Gateway configuration reloaded successfully.");
                    }
                    Err(e) => {
                        error!("Failed to reload gateway configuration: {}", e);
                    }
                }
            }
        });

        Ok(())
    }

    pub fn get_route(
        &self,
        method: &Method,
        path: &str,
    ) -> Option<crate::router::RouteResolution<GatewayRoute>> {
        let router_guard = self.router.load();
        router_guard.inner.resolve(method, path).ok()
    }
}

pub struct GatewayMiddleware {
    state: Arc<GatewayState>,
}

impl GatewayMiddleware {
    pub fn new(state: Arc<GatewayState>) -> Self {
        Self { state }
    }
}

#[async_trait]
impl<B: Send + 'static> Middleware<B> for GatewayMiddleware {
    async fn handle(
        &self,
        req: Request<B>,
        next: Next<'_, B>,
    ) -> anyhow::Result<Response<ResponseBody>> {
        let path = req.uri().path().to_string();
        let method = req.method().clone();

        // Acquire RCU read guard (wait-free, extremely fast)
        let router_guard = self.state.router.load();

        // Check if Gateway routing handles this
        if let Ok(matched) = router_guard.inner.at(&method, &path) {
            let route = matched.handler;
            info!("Gateway intercepted route to upstream: {}", route.upstream);

            // Example proxy logic here. For now, just return a mock response showing hot-reloaded proxy!
            use http_body_util::Full;
            use hyper::body::Bytes;

            let body = Full::new(Bytes::from(format!("Proxied to: {}", route.upstream)))
                .map_err(|never| match never {})
                .boxed_unsync();

            return Ok(Response::builder()
                .status(200)
                .header("x-justapi-gateway", "hot-reloaded")
                .body(body)
                .unwrap());
        }

        // Fallback to next (e.g. Python app)
        next.run(req).await
    }
}