iocaine 2.2.0

The deadliest poison known to AI
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
// SPDX-FileCopyrightText: 2025 Gergely Nagy
// SPDX-FileContributor: Gergely Nagy
//
// SPDX-License-Identifier: MIT

use anyhow::Result;
use axum::{
    Router,
    extract::{Json, Path, Query, Request, State},
    http::{HeaderMap, StatusCode, header},
    response::{IntoResponse, Response},
    routing::{any, post},
};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};
use tokio::task::JoinSet;

use crate::{
    assembled_statistical_sequences::AssembledStatisticalSequences,
    config::Config,
    means_of_production::{self, MeansOfProduction, Outcome},
    tenx_programmer::{TenXProgrammer, TenXProgrammerCounters},
};

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Debug, Clone)]
pub struct IocaineStateSnapshot {
    pub config: Config,
    pub counters: Option<TenXProgrammerCounters>,
    pub template: Arc<AssembledStatisticalSequences>,
    pub request_handler: Option<Arc<MeansOfProduction>>,
}

pub type IocaineState = Arc<RwLock<IocaineStateSnapshot>>;

#[derive(Debug)]
pub struct Iocaine {
    pub config: Config,
}

impl Iocaine {
    pub fn new(config: Config) -> Result<Self> {
        Ok(Self { config })
    }

    pub fn make_state(
        config: &Config,
        counters: Option<TenXProgrammerCounters>,
    ) -> Result<IocaineState> {
        let request_handler = if let Some(path) = &config.server.request_handler.path {
            Some(Arc::new(MeansOfProduction::new(path)?))
        } else {
            None
        };

        let state = IocaineStateSnapshot {
            config: config.clone(),
            counters,
            template: Arc::new(AssembledStatisticalSequences::new(config)),
            request_handler,
        };

        Ok(Arc::new(RwLock::new(state)))
    }

    fn main_app(state: IocaineState) -> Router {
        Router::new()
            .route("/", any(handler))
            .route("/{*path}", any(handler))
            .layer(tower_http::trace::TraceLayer::new_for_http())
            .with_state(state)
    }

    fn control_app(state: IocaineState) -> Router {
        Router::new()
            .route("/config/load", post(control_config_load))
            .layer(tower_http::trace::TraceLayer::new_for_http())
            .with_state(state)
    }

    async fn start_server(self) -> Result<()> {
        let bind = &self.config.server.bind.clone();
        let metrics_bind = &self.config.metrics.bind.clone();
        let mut opts = tokio_listener::UserOptions::default();
        opts.unix_listen_unlink = true;
        opts.unix_listen_chmod = self.config.server.unix_listen_access;

        let metrics = TenXProgrammer::new(&self.config.metrics)?;
        let state = Self::make_state(&self.config, metrics.as_ref().map(|v| v.counters.clone()))?;
        let app = Self::main_app(state.clone());

        let listener =
            tokio_listener::Listener::bind(bind, &tokio_listener::SystemOptions::default(), &opts)
                .await?;

        let mut servers = JoinSet::new();

        servers.spawn(async move {
            axum::serve(listener, app)
                .with_graceful_shutdown(shutdown_signal())
                .await
        });

        if let Some(metrics) = metrics {
            let metrics_listener = tokio_listener::Listener::bind(
                metrics_bind,
                &tokio_listener::SystemOptions::default(),
                &opts,
            )
            .await?;
            let metrics_app = metrics.app();

            servers.spawn(async move {
                axum::serve(metrics_listener, metrics_app)
                    .with_graceful_shutdown(shutdown_signal())
                    .await
            });
        }

        if let Some(control) = &self.config.server.control {
            let mut opts = tokio_listener::UserOptions::default();
            opts.unix_listen_unlink = true;
            opts.unix_listen_chmod = control.unix_listen_access;

            let listener = tokio_listener::Listener::bind(
                &control.bind,
                &tokio_listener::SystemOptions::default(),
                &opts,
            )
            .await?;

            let control_app = Self::control_app(state);

            servers.spawn(async move {
                axum::serve(listener, control_app)
                    .with_graceful_shutdown(shutdown_signal())
                    .await
            });
        }

        let _ = servers.join_all().await;
        Ok(())
    }

    pub async fn run(self) -> Result<()> {
        self.start_server().await
    }
}

pub async fn shutdown_signal() {
    let ctrl_c = async {
        tokio::signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    let terminate = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    tokio::select! {
        () = ctrl_c => {},
        () = terminate => {},
    }
}

#[must_use]
pub fn handle_request(
    headers: &HeaderMap,
    state: &IocaineStateSnapshot,
    method: &str,
    path: Option<Path<String>>,
    params: &BTreeMap<String, String>,
) -> impl IntoResponse + use<> {
    if let Some(ref request_handler) = state.request_handler {
        let p = path.as_ref().map(|p| p.0.clone());

        request_handler
            .decide(headers.clone(), p, method)
            .map_or_else(
                |variant| misdirect(headers, state, variant).into_response(),
                |variant| match variant {
                    Outcome::Garbage => {
                        poison(headers, state, path, params, variant).into_response()
                    }
                    Outcome::Challenge => {
                        challenge(headers, state, path, params, variant).into_response()
                    }
                    Outcome::NotForUs => server_error().into_response(),
                },
            )
    } else {
        poison(headers, state, path, params, Outcome::Garbage).into_response()
    }
}

async fn handler(
    headers: HeaderMap,
    State(state): State<IocaineState>,
    path: Option<Path<String>>,
    Query(params): Query<BTreeMap<String, String>>,
    request: Request,
) -> impl IntoResponse {
    let method = request.method().to_string();
    handle_request(&headers, &state.read().unwrap(), &method, path, &params)
}

#[derive(Debug, Deserialize)]
struct ControlConfigLoad {
    pub path: String,
}

async fn control_config_load(
    State(state): State<IocaineState>,
    Json(payload): Json<ControlConfigLoad>,
) -> Result<impl IntoResponse, AppError> {
    let Ok(config) = Config::load(&payload.path) else {
        return Ok((StatusCode::UNPROCESSABLE_ENTITY, ""));
    };

    if !state.read().unwrap().config.is_compatible(&config) {
        return Ok((StatusCode::CONFLICT, ""));
    }

    let request_handler = if let Some(path) = &config.server.request_handler.path {
        match MeansOfProduction::new(path) {
            Ok(v) => Some(Arc::new(v)),
            Err(e) => {
                tracing::error!(
                    { config_file = payload.path },
                    "Failed to load request handler: {e}"
                );
                return Ok((StatusCode::UNPROCESSABLE_ENTITY, ""));
            }
        }
    } else {
        None
    };

    if let Ok(mut new_state) = state.write() {
        new_state.config = config.clone();
        new_state.request_handler = request_handler;
        new_state.template = Arc::new(AssembledStatisticalSequences::new(&config));
    } else {
        tracing::error!("Failed to lock state for writing");
        return Ok((StatusCode::INTERNAL_SERVER_ERROR, ""));
    }

    Ok((StatusCode::ACCEPTED, ""))
}

fn misdirect(
    headers: &axum::http::HeaderMap,
    state: &IocaineStateSnapshot,
    outcome: Outcome,
) -> impl IntoResponse {
    if let Some(ref counters) = state.counters {
        let verdict = format!("reject::{outcome}");
        let labels =
            TenXProgrammer::build_label_values(&state.template.config.metrics, headers, &verdict);
        counters.request_counter.with_label_values(&labels).inc();
    }

    (StatusCode::MISDIRECTED_REQUEST, "")
}

fn server_error() -> impl IntoResponse {
    (StatusCode::INTERNAL_SERVER_ERROR, "")
}

fn challenge(
    headers: &axum::http::HeaderMap,
    state: &IocaineStateSnapshot,
    path: Option<Path<String>>,
    params: &BTreeMap<String, String>,
    outcome: Outcome,
) -> std::result::Result<impl IntoResponse, AppError> {
    let default_host = axum::http::HeaderValue::from_static("<unknown>");
    let host = headers.get("host").unwrap_or(&default_host).to_str()?;
    let path = path.unwrap_or(Path(String::new()));

    let (content_type, challenge) =
        state
            .template
            .generate(host, &path, params, "challenge.jinja")?;

    if let Some(ref counters) = state.counters {
        let verdict = format!("accept::{outcome}");
        let labels =
            TenXProgrammer::build_label_values(&state.template.config.metrics, headers, &verdict);

        counters.request_counter.with_label_values(&labels).inc();
        counters.challenge_counter.with_label_values(&labels).inc();
    }

    let mut headers = HeaderMap::new();
    headers.insert(header::CONTENT_TYPE, content_type.parse()?);

    if state.config.templates.minify.enable
        && (content_type.starts_with("text/html") || content_type.starts_with("text/css"))
    {
        let config = &state.config.templates.minify;
        let cfg = minify_html::Cfg {
            minify_css: config.minify_css,
            minify_js: false,
            minify_doctype: false,
            ..Default::default()
        };
        let minified = minify_html::minify(challenge.as_bytes(), &cfg);
        Ok((headers, minified))
    } else {
        Ok((headers, challenge.into()))
    }
}

fn poison(
    headers: &axum::http::HeaderMap,
    state: &IocaineStateSnapshot,
    path: Option<Path<String>>,
    params: &BTreeMap<String, String>,
    outcome: Outcome,
) -> std::result::Result<impl IntoResponse, AppError> {
    let default_host = axum::http::HeaderValue::from_static("<unknown>");
    let host = headers.get("host").unwrap_or(&default_host).to_str()?;
    let path = path.unwrap_or(Path(String::new()));

    let (content_type, garbage) = state.template.generate(host, &path, params, "main.jinja")?;

    if let Some(ref counters) = state.counters {
        let verdict = format!("accept::{outcome}");
        let labels =
            TenXProgrammer::build_label_values(&state.template.config.metrics, headers, &verdict);

        counters.request_counter.with_label_values(&labels).inc();
        counters
            .garbage_served_counter
            .with_label_values(&labels)
            .inc_by(garbage.len() as u64);

        let depth = path.chars().filter(|c| *c == '/').count() as u64;
        let maze_depth_counter = counters.maze_depth.with_label_values(&labels);
        let maze_depth = maze_depth_counter.get();
        if depth > maze_depth {
            maze_depth_counter.inc_by(depth - maze_depth);
        }
    }

    let mut headers = HeaderMap::new();
    headers.insert(header::CONTENT_TYPE, content_type.parse()?);

    if state.config.templates.minify.enable
        && (content_type.starts_with("text/html") || content_type.starts_with("text/css"))
    {
        let config = &state.config.templates.minify;
        let cfg = minify_html::Cfg {
            minify_css: config.minify_css,
            minify_js: false,
            minify_doctype: false,
            ..Default::default()
        };
        let minified = minify_html::minify(garbage.as_bytes(), &cfg);
        Ok((headers, minified))
    } else {
        Ok((headers, garbage.into()))
    }
}

pub struct AppError(anyhow::Error);

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        tracing::error!("Internal server error: {}", self.0);
        (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
    }
}

impl From<axum::http::header::ToStrError> for AppError {
    fn from(e: axum::http::header::ToStrError) -> Self {
        Self(e.into())
    }
}

impl From<anyhow::Error> for AppError {
    fn from(e: anyhow::Error) -> Self {
        Self(e)
    }
}

impl From<std::io::Error> for AppError {
    fn from(e: std::io::Error) -> Self {
        Self(e.into())
    }
}

impl From<std::string::FromUtf8Error> for AppError {
    fn from(e: std::string::FromUtf8Error) -> Self {
        Self(e.into())
    }
}

impl From<axum::http::header::InvalidHeaderValue> for AppError {
    fn from(e: axum::http::header::InvalidHeaderValue) -> Self {
        Self(e.into())
    }
}

impl From<means_of_production::Error> for AppError {
    fn from(e: means_of_production::Error) -> Self {
        Self(e.into())
    }
}