portail 2.1.0

Unified proxy/gateway: AI Gateway + MCP Gateway + CDN cache
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::IpAddr;
use std::str::FromStr;
use std::sync::Arc;

pub mod reliability;
pub mod resolver;

// ── DNS Configuration ────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DnsConfig {
    pub enabled: bool,
    pub listen: String,
    pub upstream: Vec<String>,
    pub doh_enabled: bool,
    pub doh_endpoints: Vec<String>,
    pub unbound_enabled: bool,
    pub unbound_config: Option<String>,
    pub blocklists: Vec<String>,
    pub allowlists: Vec<String>,
    pub hooks: Vec<DnsHook>,
}

impl Default for DnsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            listen: "127.0.0.1:53".into(),
            upstream: vec!["1.1.1.1".into(), "8.8.8.8".into()],
            doh_enabled: true,
            doh_endpoints: vec![
                "https://cloudflare-dns.com/dns-query".into(),
                "https://dns.google/dns-query".into(),
            ],
            unbound_enabled: false,
            unbound_config: None,
            blocklists: Vec::new(),
            allowlists: Vec::new(),
            hooks: Vec::new(),
        }
    }
}

// ── DNS Hooks ────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DnsHook {
    pub id: String,
    pub name: String,
    pub pattern: String,
    pub action: DnsHookAction,
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DnsHookAction {
    Block,
    Allow,
    Redirect(String),
    Log,
    Rewrite(String),
}

// ── DNS Record Types ─────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DnsQuery {
    pub name: String,
    pub record_type: DnsRecordType,
    pub source: IpAddr,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DnsRecordType {
    A,
    AAAA,
    CNAME,
    MX,
    TXT,
    NS,
    SOA,
}

impl FromStr for DnsRecordType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_uppercase().as_str() {
            "A" => Ok(Self::A),
            "AAAA" => Ok(Self::AAAA),
            "CNAME" => Ok(Self::CNAME),
            "MX" => Ok(Self::MX),
            "TXT" => Ok(Self::TXT),
            "NS" => Ok(Self::NS),
            "SOA" => Ok(Self::SOA),
            _ => Err(format!("Unknown record type: {}", s)),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DnsResponse {
    pub answers: Vec<DnsAnswer>,
    pub ttl: u32,
    pub authoritative: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DnsAnswer {
    pub name: String,
    pub record_type: DnsRecordType,
    pub data: String,
    pub ttl: u32,
}

// ── DNS Store (in-memory) ────────────────────────────────────────

pub struct DnsStore {
    records: std::sync::RwLock<HashMap<String, Vec<DnsAnswer>>>,
    hooks: std::sync::RwLock<Vec<DnsHook>>,
}

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

impl DnsStore {
    pub fn new() -> Self {
        Self {
            records: std::sync::RwLock::new(HashMap::new()),
            hooks: std::sync::RwLock::new(Vec::new()),
        }
    }

    pub fn add_record(&self, name: String, answer: DnsAnswer) {
        let mut records = self.records.write().unwrap();
        records.entry(name).or_default().push(answer);
    }

    pub fn query(&self, name: &str, record_type: DnsRecordType) -> Vec<DnsAnswer> {
        let records = self.records.read().unwrap();
        records
            .get(name)
            .map(|answers| {
                answers
                    .iter()
                    .filter(|a| {
                        std::mem::discriminant(&a.record_type)
                            == std::mem::discriminant(&record_type)
                    })
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    pub fn add_hook(&self, hook: DnsHook) {
        self.hooks.write().unwrap().push(hook);
    }

    pub fn remove_hook(&self, id: &str) -> bool {
        let mut hooks = self.hooks.write().unwrap();
        let pos = hooks.iter().position(|h| h.id == id);
        if let Some(p) = pos {
            hooks.remove(p);
            true
        } else {
            false
        }
    }

    pub fn apply_hooks(&self, query: &DnsQuery) -> Option<DnsHookAction> {
        let hooks = self.hooks.read().unwrap();
        for hook in hooks.iter().filter(|h| h.enabled) {
            if query.name.contains(&hook.pattern) || hook.pattern == "*" {
                return Some(hook.action.clone());
            }
        }
        None
    }
}

// ── DoH Client ───────────────────────────────────────────────────

pub struct DohClient {
    endpoints: Vec<String>,
    client: reqwest::Client,
}

impl DohClient {
    pub fn new(endpoints: Vec<String>) -> Self {
        Self {
            endpoints,
            client: reqwest::Client::new(),
        }
    }

    pub async fn query(
        &self,
        name: &str,
        record_type: DnsRecordType,
    ) -> Result<DnsResponse, String> {
        let qtype = match record_type {
            DnsRecordType::A => 1,
            DnsRecordType::AAAA => 28,
            DnsRecordType::CNAME => 5,
            DnsRecordType::MX => 15,
            DnsRecordType::TXT => 16,
            DnsRecordType::NS => 2,
            DnsRecordType::SOA => 6,
        };

        let url = format!(
            "{}?name={}&type={}",
            self.endpoints
                .first()
                .unwrap_or(&"https://cloudflare-dns.com/dns-query".into()),
            name,
            qtype
        );

        let response = self
            .client
            .get(&url)
            .header("Accept", "application/dns-json")
            .send()
            .await
            .map_err(|e| e.to_string())?;

        let json: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;

        let answers = json["Answer"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(|a| DnsAnswer {
                        name: a["name"].as_str().unwrap_or("").to_string(),
                        record_type: DnsRecordType::from_str(
                            &a["type"].as_u64().unwrap_or(1).to_string(),
                        )
                        .unwrap_or(DnsRecordType::A),
                        data: a["data"].as_str().unwrap_or("").to_string(),
                        ttl: a["TTL"].as_u64().unwrap_or(300) as u32,
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(DnsResponse {
            answers,
            ttl: 300,
            authoritative: false,
        })
    }
}

// ── Network Isolation ────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NetworkIsolation {
    pub enabled: bool,
    pub allowed_domains: Vec<String>,
    pub blocked_domains: Vec<String>,
    pub allowed_ips: Vec<IpAddr>,
    pub blocked_ips: Vec<IpAddr>,
    pub dns_only: bool,
}

impl Default for NetworkIsolation {
    fn default() -> Self {
        Self {
            enabled: false,
            allowed_domains: Vec::new(),
            blocked_domains: Vec::new(),
            allowed_ips: Vec::new(),
            blocked_ips: Vec::new(),
            dns_only: true,
        }
    }
}

impl NetworkIsolation {
    pub fn is_allowed(&self, domain: &str, ip: Option<IpAddr>) -> bool {
        if !self.enabled {
            return true;
        }

        // Check blocked domains
        if self
            .blocked_domains
            .iter()
            .any(|d| domain.contains(d.as_str()))
        {
            return false;
        }

        // Check blocked IPs
        if let Some(ip) = ip {
            if self.blocked_ips.contains(&ip) {
                return false;
            }
        }

        // If allowlists are set, only allow listed items
        if !self.allowed_domains.is_empty() {
            return self
                .allowed_domains
                .iter()
                .any(|d| domain.contains(d.as_str()));
        }

        if !self.allowed_ips.is_empty() {
            if let Some(ip) = ip {
                return self.allowed_ips.contains(&ip);
            }
            return false;
        }

        true
    }
}

// ── HTTP Handlers ────────────────────────────────────────────────

pub async fn handle_dns_query(
    axum::extract::State(state): axum::extract::State<Arc<crate::AppState>>,
    axum::Json(query): axum::Json<DnsQuery>,
) -> axum::Json<DnsResponse> {
    // Apply hooks
    if let Some(action) = state.dns_store.apply_hooks(&query) {
        match action {
            DnsHookAction::Block => {
                return axum::Json(DnsResponse {
                    answers: vec![],
                    ttl: 0,
                    authoritative: false,
                });
            }
            DnsHookAction::Redirect(target) => {
                return axum::Json(DnsResponse {
                    answers: vec![DnsAnswer {
                        name: query.name.clone(),
                        record_type: DnsRecordType::A,
                        data: target,
                        ttl: 300,
                    }],
                    ttl: 300,
                    authoritative: false,
                });
            }
            _ => {}
        }
    }

    // Query local store first
    let answers = state
        .dns_store
        .query(&query.name, query.record_type.clone());
    if !answers.is_empty() {
        return axum::Json(DnsResponse {
            answers,
            ttl: 300,
            authoritative: false,
        });
    }

    // Forward to DoH if enabled
    if let Some(ref doh) = state.doh_client {
        if let Ok(response) = doh.query(&query.name, query.record_type).await {
            return axum::Json(response);
        }
    }

    axum::Json(DnsResponse {
        answers: vec![],
        ttl: 0,
        authoritative: false,
    })
}

// ── Module-level router ──────────────────────────────────────────

pub fn router() -> axum::Router<Arc<crate::AppState>> {
    axum::Router::new().route("/dns/query", axum::routing::post(handle_dns_query))
}

// ── Tests ────────────────────────────────────────────────────────

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

    #[test]
    fn dns_store_add_query() {
        let store = DnsStore::new();
        store.add_record(
            "example.com".into(),
            DnsAnswer {
                name: "example.com".into(),
                record_type: DnsRecordType::A,
                data: "1.2.3.4".into(),
                ttl: 300,
            },
        );

        let answers = store.query("example.com", DnsRecordType::A);
        assert_eq!(answers.len(), 1);
        assert_eq!(answers[0].data, "1.2.3.4");
    }

    #[test]
    fn dns_store_hooks() {
        let store = DnsStore::new();
        store.add_hook(DnsHook {
            id: "h1".into(),
            name: "block ads".into(),
            pattern: "ads.example.com".into(),
            action: DnsHookAction::Block,
            enabled: true,
        });

        let query = DnsQuery {
            name: "ads.example.com".into(),
            record_type: DnsRecordType::A,
            source: "127.0.0.1".parse().unwrap(),
        };

        let action = store.apply_hooks(&query);
        assert!(matches!(action, Some(DnsHookAction::Block)));
    }

    #[test]
    fn network_isolation() {
        let iso = NetworkIsolation {
            enabled: true,
            allowed_domains: vec!["example.com".into()],
            blocked_domains: vec!["evil.com".into()],
            ..Default::default()
        };

        assert!(iso.is_allowed("api.example.com", None));
        assert!(!iso.is_allowed("evil.com", None));
        assert!(!iso.is_allowed("unknown.com", None));
    }
}