witmproxy 0.0.2-alpha

A WASM-in-the-middle proxy
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
use bytes::Bytes;
use cel_cxx::Opaque;
use chrono::Datelike;
use hyper::{Request, Response};
use salvo::http::uri::Scheme;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::str::FromStr;
use wasmtime_wasi_http::p3::{Request as WasiRequest, Response as WasiResponse};

use crate::{
    events::content::InboundContent, wasm::bindgen::witmproxy::plugin::capabilities::RequestContext,
};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Opaque)]
#[cel_cxx(display)]
pub struct CelConnect {
    pub host: String,
    pub port: u16,
}

impl CelConnect {
    pub fn host(&self) -> &str {
        &self.host
    }

    pub fn port(&self) -> u16 {
        self.port
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Opaque)]
#[cel_cxx(display)]
pub struct CelRequest {
    pub scheme: String,
    pub host: String,
    pub path: String,
    pub query: HashMap<String, Vec<String>>,
    pub method: String,
    pub headers: HashMap<String, Vec<String>>,
}

impl CelRequest {
    pub fn scheme(&self) -> &str {
        &self.scheme
    }

    pub fn host(&self) -> &str {
        &self.host
    }

    pub fn path(&self) -> &str {
        &self.path
    }

    pub fn query(&self) -> &HashMap<String, Vec<String>> {
        &self.query
    }

    pub fn method(&self) -> &str {
        &self.method
    }

    pub fn headers(&self) -> &HashMap<String, Vec<String>> {
        &self.headers
    }
}

impl From<CelRequest> for RequestContext {
    fn from(val: CelRequest) -> Self {
        let query = val
            .query
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        let headers = val
            .headers
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();

        RequestContext {
            scheme: val.scheme,
            host: val.host,
            path: val.path,
            query,
            method: val.method,
            headers,
        }
    }
}

impl From<&RequestContext> for CelRequest {
    fn from(ctx: &RequestContext) -> Self {
        let query = ctx
            .query
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        let headers = ctx
            .headers
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();

        CelRequest {
            scheme: ctx.scheme.clone(),
            host: ctx.host.clone(),
            path: ctx.path.clone(),
            query,
            method: ctx.method.clone(),
            headers,
        }
    }
}

impl From<&WasiRequest> for CelRequest {
    fn from(req: &WasiRequest) -> Self {
        let mut headers = HashMap::new();

        for (name, value) in req.headers.iter() {
            let entry = headers
                .entry(name.as_str().to_string())
                .or_insert_with(Vec::new);
            if let Ok(val_str) = value.to_str() {
                entry.push(val_str.to_string());
            }
        }

        let host = if let Some(authority) = &req.authority {
            authority.to_string()
        } else {
            "".to_string()
        };
        let mut query = HashMap::new();
        let mut path = "".to_string();
        let scheme = req.scheme.clone().unwrap_or(Scheme::HTTPS).to_string();
        let method = req.method.to_string();

        if let Some(path_and_query) = &req.path_with_query {
            path = path_and_query.path().to_string();

            if let Some(query_str) = path_and_query.query() {
                for (key, value) in url::form_urlencoded::parse(query_str.as_bytes()) {
                    let entry = query.entry(key.to_string()).or_insert_with(Vec::new);
                    entry.push(value.to_string());
                }
            }
        }

        CelRequest {
            scheme,
            host,
            path,
            query,
            method,
            headers,
        }
    }
}

impl<B> From<&Request<B>> for CelRequest
where
    B: http_body::Body<Data = Bytes> + Send + 'static,
{
    fn from(req: &Request<B>) -> Self {
        let mut headers = HashMap::new();

        for (name, value) in req.headers().iter() {
            let entry = headers
                .entry(name.as_str().to_string())
                .or_insert_with(Vec::new);
            if let Ok(val_str) = value.to_str() {
                entry.push(val_str.to_string());
            }
        }

        let host = if let Some(authority) = req.uri().authority() {
            authority.to_string()
        } else {
            "".to_string()
        };
        let mut query = HashMap::new();
        let mut path = "".to_string();
        let scheme = req.uri().scheme_str().unwrap_or("https").to_string();
        let method = req.method().clone().to_string();

        if let Some(path_and_query) = req.uri().path_and_query() {
            path = path_and_query.path().to_string();

            if let Some(query_str) = path_and_query.query() {
                for (key, value) in url::form_urlencoded::parse(query_str.as_bytes()) {
                    let entry = query.entry(key.to_string()).or_insert_with(Vec::new);
                    entry.push(value.to_string());
                }
            }
        }

        CelRequest {
            scheme,
            host,
            path,
            query,
            method,
            headers,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Opaque)]
#[cel_cxx(display)]
pub struct CelResponse {
    pub status: u16,
    pub headers: HashMap<String, Vec<String>>,
}

impl CelResponse {
    pub fn status(&self) -> u16 {
        self.status
    }

    pub fn headers(&self) -> &HashMap<String, Vec<String>> {
        &self.headers
    }
}

impl<B> From<&Response<B>> for CelResponse
where
    B: http_body::Body<Data = Bytes> + Send + 'static,
{
    fn from(res: &Response<B>) -> Self {
        let mut headers = HashMap::new();

        for (name, value) in res.headers().iter() {
            let entry = headers
                .entry(name.as_str().to_string())
                .or_insert_with(Vec::new);
            if let Ok(val_str) = value.to_str() {
                entry.push(val_str.to_string());
            }
        }

        CelResponse {
            status: res.status().as_u16(),
            headers,
        }
    }
}

impl From<&WasiResponse> for CelResponse {
    fn from(res: &WasiResponse) -> Self {
        let mut headers = HashMap::new();

        for (name, value) in res.headers.iter() {
            let entry = headers
                .entry(name.as_str().to_string())
                .or_insert_with(Vec::new);
            if let Ok(val_str) = value.to_str() {
                entry.push(val_str.to_string());
            }
        }

        CelResponse {
            status: res.status.as_u16(),
            headers,
        }
    }
}

impl From<&reqwest::Request> for CelRequest {
    fn from(req: &reqwest::Request) -> Self {
        let mut headers = HashMap::new();

        for (name, value) in req.headers().iter() {
            let entry = headers
                .entry(name.as_str().to_string())
                .or_insert_with(Vec::new);
            if let Ok(val_str) = value.to_str() {
                entry.push(val_str.to_string());
            }
        }

        let url = req.url();
        let host = url.host_str().unwrap_or("").to_string();
        let path = url.path().to_string();
        let scheme = url.scheme().to_string();
        let method = req.method().to_string();

        let mut query = HashMap::new();
        for (key, value) in url.query_pairs() {
            let entry = query.entry(key.to_string()).or_insert_with(Vec::new);
            entry.push(value.to_string());
        }

        CelRequest {
            scheme,
            host,
            path,
            query,
            method,
            headers,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Opaque)]
#[cel_cxx(display)]
pub struct CelContent {
    content_type: String,
}

impl CelContent {
    pub fn content_type(&self) -> &str {
        &self.content_type
    }
}

impl From<&InboundContent> for CelContent {
    fn from(content: &InboundContent) -> Self {
        CelContent {
            content_type: content.content_type(),
        }
    }
}

impl<B> From<&Response<B>> for CelContent
where
    B: http_body::Body<Data = Bytes> + Send + 'static,
{
    fn from(res: &Response<B>) -> Self {
        let content_type = if let Some(values) = res.headers().get("content-type") {
            if let Ok(val_str) = values.to_str() {
                val_str.to_string()
            } else {
                "unknown".to_string()
            }
        } else {
            "unknown".to_string()
        };

        CelContent { content_type }
    }
}

/// A CEL context object providing time-based convenience methods for controlling
/// when a plugin should run, without leaking detailed host information to the plugin.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Opaque)]
#[cel_cxx(display)]
pub struct CelTime {
    /// Current hour (0-23)
    hour: u32,
    /// Current day of week (0=Sunday, 6=Saturday)
    day_of_week: u32,
    /// For cron matching, we store the current UTC time
    now_utc: chrono::DateTime<chrono::Utc>,
}

impl CelTime {
    /// Create a new CelTime from the current system time
    pub fn now() -> Self {
        let now_utc = chrono::Utc::now();
        let hour = now_utc.hour();
        // chrono: Mon=0 .. Sun=6; we want Sun=0 .. Sat=6
        let day_of_week = match now_utc.weekday() {
            chrono::Weekday::Sun => 0,
            chrono::Weekday::Mon => 1,
            chrono::Weekday::Tue => 2,
            chrono::Weekday::Wed => 3,
            chrono::Weekday::Thu => 4,
            chrono::Weekday::Fri => 5,
            chrono::Weekday::Sat => 6,
        };
        Self {
            hour,
            day_of_week,
            now_utc,
        }
    }

    /// Returns whether the given CRON expression matches the current system time.
    ///
    /// Example CEL: `time.matches_cron("0 9-17 * * MON-FRI")`
    pub fn matches_cron(&self, cron_str: &str) -> bool {
        match cron::Schedule::from_str(cron_str) {
            Ok(schedule) => schedule.upcoming(chrono::Utc).take(1).any(|next| {
                // Check if the next occurrence is within 60 seconds of now
                let diff = next.signed_duration_since(self.now_utc);
                diff.num_seconds().abs() < 60
            }),
            Err(_) => false,
        }
    }

    /// Returns whether the current day matches the given weekday integer.
    /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
    ///
    /// Example CEL: `time.is_day_of_week(1)` (true on Mondays)
    pub fn is_day_of_week(&self, weekday: i64) -> bool {
        (0..=6).contains(&weekday) && self.day_of_week == weekday as u32
    }

    /// Returns whether the current hour is between `hour_start` and `hour_end` (inclusive).
    /// Both values must be in range [0, 23].
    ///
    /// Example CEL: `time.is_between_hours(9, 17)` (true from 9:00 to 17:59)
    pub fn is_between_hours(&self, hour_start: i64, hour_end: i64) -> bool {
        if !(0..=23).contains(&hour_start) || !(0..=23).contains(&hour_end) {
            return false;
        }
        let h = self.hour as i64;
        if hour_start <= hour_end {
            h >= hour_start && h <= hour_end
        } else {
            // Wraps around midnight (e.g., 22 to 6)
            h >= hour_start || h <= hour_end
        }
    }

    /// Register the `time` variable and its methods with the CEL environment
    pub fn register_cel_env(
        env: cel_cxx::EnvBuilder<'_>,
    ) -> anyhow::Result<cel_cxx::EnvBuilder<'_>> {
        let env = env
            .declare_variable::<CelTime>("time")?
            .register_member_function("matches_cron", CelTime::matches_cron)?
            .register_member_function("is_day_of_week", CelTime::is_day_of_week)?
            .register_member_function("is_between_hours", CelTime::is_between_hours)?;
        Ok(env)
    }
}

use chrono::Timelike;