ctb_io_webui/controllers/
v86.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Controller for the v86 x86 browser VM emulator route.
21
22use axum::{
23    body::Body,
24    extract::{Path, Query, State},
25    http::header,
26    response::Response,
27};
28use serde::Deserialize;
29
30use crate::extractors::request_state::RequestState;
31use crate::json_value;
32use crate::session_auth::AuthenticatedUser;
33use crate::{AppState, respond_page};
34
35#[derive(Debug, Deserialize)]
36pub struct V86Query {
37    pub profile: Option<String>,
38}
39
40pub async fn get_v86(
41    State(state): State<AppState>,
42    Query(query): Query<V86Query>,
43    req: RequestState,
44    _user: AuthenticatedUser,
45) -> Response {
46    // Reason for fallback: query parameter profile missing defaults to "guix" profile
47    let profile = query.profile.unwrap_or_else(|| "guix".to_string());
48    render_v86_profile(&state, req, &profile)
49}
50
51pub async fn get_v86_profile(
52    State(state): State<AppState>,
53    Path(profile): Path<String>,
54    req: RequestState,
55    _user: AuthenticatedUser,
56) -> Response {
57    render_v86_profile(&state, req, &profile)
58}
59
60/// Controller action serving `/vendor/v86/v86.css` with font, color, and body background
61/// declarations filtered out to preserve high contrast and site layout aesthetics.
62pub async fn get_v86_css() -> Response {
63    let raw_bytes = ctb_storage::get_asset("web/vendor/v86/v86.css");
64
65    let Some(raw_bytes) = raw_bytes else {
66        return Response::builder()
67            .status(404)
68            .body(Body::empty())
69            // Reason for fallback: response builder failure falls back to default empty Response
70            .unwrap_or_else(|_| Response::default());
71    };
72
73    let raw_css = String::from_utf8_lossy(&raw_bytes);
74    let filtered_css = filter_v86_css(&raw_css);
75
76    Response::builder()
77        .header(header::CONTENT_TYPE, "text/css")
78        .body(Body::from(filtered_css))
79        // Reason for fallback: response builder failure falls back to default empty Response
80        .unwrap_or_else(|_| Response::default())
81}
82
83/// Filters CSS content to remove `font-size`, `font-family`, non-transparent `color`,
84/// and `body` background color declarations that interfere with app theme rendering.
85pub fn filter_v86_css(css: &str) -> String {
86    let mut out = String::with_capacity(css.len());
87    let mut in_body_block = false;
88
89    for line in css.lines() {
90        let trimmed = line.trim();
91
92        if trimmed.starts_with("body") && trimmed.contains('{') {
93            in_body_block = true;
94        }
95
96        if trimmed.starts_with("font-size:")
97            || trimmed.starts_with("font-family:")
98        {
99            continue;
100        }
101
102        if trimmed.starts_with("color:") && !trimmed.contains("transparent") {
103            continue;
104        }
105
106        if in_body_block && trimmed.starts_with("background-color:") {
107            continue;
108        }
109
110        if trimmed.contains('}') {
111            in_body_block = false;
112        }
113
114        out.push_str(line);
115        out.push('\n');
116    }
117
118    out
119}
120
121fn render_v86_profile(
122    state: &AppState,
123    req: RequestState,
124    profile: &str,
125) -> Response {
126    let active_profile = match profile {
127        "alpine" => "alpine",
128        "arch" | "archlinux" => "arch",
129        _ => "guix",
130    };
131
132    let title = match active_profile {
133        "alpine" => "Alpine Linux i386 (GUI)",
134        "arch" => "Arch Linux 32 (GUI)",
135        _ => "Guix System i686 (GUI)",
136    };
137
138    respond_page(
139        state,
140        req,
141        "v86",
142        &json_value!({
143            "profile" => active_profile.to_string(),
144            "title" => title.to_string(),
145        }),
146    )
147}
148
149#[cfg(test)]
150#[allow(
151    clippy::panic,
152    clippy::expect_used,
153    clippy::unwrap_used,
154    clippy::unwrap_in_result,
155    clippy::panic_in_result_fn,
156    clippy::indexing_slicing,
157    clippy::arithmetic_side_effects,
158    reason = "Standard repository test boilerplate"
159)]
160mod tests {
161    use crate::test_helpers::{
162        assert_eq_or_print_body, test_get_no_login, test_get_status_no_login,
163        test_get_with_login,
164    };
165
166    #[crate::ctb_test("tokio")]
167    async fn unauthenticated_v86_returns_401() {
168        let (status, body) = test_get_no_login("/v86").await;
169        assert_eq!(status, 401);
170        assert!(body.contains("401") || body.contains("Unauthorized"));
171    }
172
173    #[crate::ctb_test("tokio")]
174    async fn test_v86_route_loads() {
175        let Ok((status, body, _lock)) =
176            test_get_with_login("/v86", None, function_name!()).await
177        else {
178            panic!("Failed to perform test_get_with_login");
179        };
180        assert_eq_or_print_body(status, 200, &body);
181        assert!(body.contains("v86") || body.contains("Guix"));
182    }
183
184    #[crate::ctb_test("tokio")]
185    async fn test_v86_profile_route_loads() {
186        let Ok((status, body, _lock)) =
187            test_get_with_login("/v86/arch", None, function_name!()).await
188        else {
189            panic!("Failed to perform test_get_with_login");
190        };
191        assert_eq_or_print_body(status, 200, &body);
192        assert!(body.contains("Arch Linux"));
193    }
194
195    #[crate::ctb_test("tokio")]
196    async fn test_v86_css_filtered() {
197        let (status, body) = test_get_no_login("/vendor/v86/v86.css").await;
198        assert_eq!(status, 200);
199        assert!(
200            !body.contains("font-family: sans-serif"),
201            "v86.css contained font-family: sans-serif"
202        );
203        assert!(
204            !body.contains("color: #fff"),
205            "v86.css contained color: #fff"
206        );
207        assert!(
208            !body.contains("font-size: 13px"),
209            "v86.css contained font-size: 13px"
210        );
211        assert!(
212            !body.contains("background-color: #111"),
213            "v86.css contained background-color: #111"
214        );
215        assert!(
216            body.contains("color: transparent"),
217            "v86.css should preserve color: transparent"
218        );
219    }
220
221    #[crate::ctb_test("tokio")]
222    async fn test_v86_initrd_asset_serves() {
223        let status = test_get_status_no_login(
224            "/vendor/v86_images/guix/guix_posix_initrd.cpio.gz",
225        )
226        .await;
227        assert_ne!(
228            status, 404,
229            "Initrd asset URL /vendor/v86_images/guix/guix_posix_initrd.cpio.gz returned 404!"
230        );
231    }
232
233    #[crate::ctb_test("tokio")]
234    async fn test_v86_fs_json_asset_serves() {
235        let status =
236            test_get_status_no_login("/vendor/v86_images/guix/guix-fs.json")
237                .await;
238        assert_ne!(
239            status, 404,
240            "Guix fs.json asset URL /vendor/v86_images/guix/guix-fs.json returned 404!"
241        );
242    }
243
244    #[crate::ctb_test("tokio")]
245    async fn test_v86_asset_rejects_parent_traversal() {
246        let status =
247            test_get_status_no_login("/vendor/v86_images/../Cargo.toml").await;
248        assert_ne!(
249            status, 200,
250            "Traversal URL /vendor/v86_images/../Cargo.toml must not serve disk files"
251        );
252    }
253}