ctb_io_webui/controllers/
base.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 static assets and other routes shared between the app and the
21//! general web site.
22use crate::utilities::*;
23
24use anyhow::anyhow;
25use axum::{
26    body::Body,
27    extract::{Path, State},
28    http::{HeaderMap, HeaderValue, StatusCode, Uri, header},
29    response::{IntoResponse, Response},
30};
31use mime_guess;
32use std::borrow::Cow;
33use std::path::PathBuf;
34
35use crate::respond_markdown_unsafe;
36use crate::{AppState, RequestState, error_400, error_404, render_view};
37use ctb_build_info::build_info;
38use ctb_installer::chunking::{
39    compute_sha256_hex, read_chunk_from_directory_compressed,
40};
41use ctb_installer::manifest::{FileEntry, ReleaseManifest};
42use ctb_storage::get_asset;
43
44fn add_redirect_headers(resp: &mut Response) {
45    resp.headers_mut().insert(
46        header::CACHE_CONTROL,
47        HeaderValue::from_static("no-store, no-cache, must-revalidate"),
48    );
49    resp.headers_mut().insert(
50        header::VARY,
51        HeaderValue::from_static("X-CollectiveToolbox-IsJsRequest"),
52    );
53}
54
55/// Build a JSON redirect response with X-CollectiveToolbox-IsJsRedirect header.
56fn json_redirect_response(location: &str) -> Response {
57    let mut resp = Response::new(Body::from(
58        serde_json::json!({ "url": location }).to_string(),
59    ));
60    resp.headers_mut().insert(
61        "X-CollectiveToolbox-IsJsRedirect",
62        HeaderValue::from_static("true"),
63    );
64    resp.headers_mut().insert(
65        header::CONTENT_TYPE,
66        HeaderValue::from_static("application/json"),
67    );
68    *resp.status_mut() = axum::http::StatusCode::OK;
69    add_redirect_headers(&mut resp);
70    resp
71}
72
73/// Redirect helper for 307 (Temporary Redirect, preserves method).
74/// If X-CollectiveToolbox-IsJsRequest header is present, returns JSON with
75/// target URL and X-CollectiveToolbox-IsJsRedirect response header.
76pub fn redirect_temporary_preserve_method(
77    is_js_req: bool,
78    location: &str,
79) -> Response {
80    let mut resp = if is_js_req {
81        json_redirect_response(location)
82    } else {
83        axum::response::Redirect::temporary(location).into_response()
84    };
85    add_redirect_headers(&mut resp);
86    resp
87}
88
89/// Redirect helper for 303 (See Other, changes POST to GET).
90/// If X-CollectiveToolbox-IsJsRequest header is present, returns JSON with
91/// target URL and X-CollectiveToolbox-IsJsRedirect response header.
92pub fn redirect_temporary(is_js_req: bool, location: &str) -> Response {
93    let mut resp = if is_js_req {
94        json_redirect_response(location)
95    } else {
96        axum::response::Redirect::to(location).into_response()
97    };
98    add_redirect_headers(&mut resp);
99    resp
100}
101
102/// Redirect helper for 308 (Permanent Redirect, preserves method).
103/// If X-CollectiveToolbox-IsJsRequest header is present, returns JSON with
104/// target URL and X-CollectiveToolbox-IsJsRedirect response header.
105pub fn redirect_permanent(is_js_req: bool, location: &str) -> Response {
106    let mut resp = if is_js_req {
107        json_redirect_response(location)
108    } else {
109        axum::response::Redirect::permanent(location).into_response()
110    };
111    add_redirect_headers(&mut resp);
112    resp
113}
114
115pub async fn get_app_css(
116    State(state): State<AppState>,
117    req: RequestState,
118) -> Response {
119    match render_view(
120        &state.hbs,
121        "encre_css".to_string(),
122        &req,
123        &json_value!({}),
124    ) {
125        Ok(css) => {
126            let mut resp = Response::new(Body::from(css));
127            resp.headers_mut().insert(
128                header::CONTENT_TYPE,
129                HeaderValue::from_static("text/css"),
130            );
131            resp
132        }
133        Err(e) => error_400(&state, &req, e),
134    }
135}
136
137pub async fn get_installer_linux_x64(
138    State(state): State<AppState>,
139    req: RequestState,
140    headers: HeaderMap,
141) -> Response {
142    serve_latest_installer_release(&state, &req, &headers, "linux-x64").await
143}
144
145pub async fn get_installer_linux_x86(
146    State(state): State<AppState>,
147    req: RequestState,
148    headers: HeaderMap,
149) -> Response {
150    serve_latest_installer_release(&state, &req, &headers, "linux-x86").await
151}
152
153pub async fn get_installer_windows_x64(
154    State(state): State<AppState>,
155    req: RequestState,
156    headers: HeaderMap,
157) -> Response {
158    serve_latest_installer_release(&state, &req, &headers, "windows-x64").await
159}
160
161pub async fn get_installer_freebsd_x64(
162    State(state): State<AppState>,
163    req: RequestState,
164    headers: HeaderMap,
165) -> Response {
166    serve_latest_installer_release(&state, &req, &headers, "freebsd-x64").await
167}
168
169fn get_releases_dir(storage_dir_override: &Option<PathBuf>) -> Result<PathBuf> {
170    let base = if let Some(path) = storage_dir_override {
171        path.clone()
172    } else {
173        ctb_utilities::storage::get_storage_dir()?
174    };
175    Ok(base.join("releases"))
176}
177
178fn get_release_chunks_dir(
179    storage_dir_override: &Option<PathBuf>,
180) -> Result<PathBuf> {
181    Ok(get_releases_dir(storage_dir_override)?.join("bh"))
182}
183
184fn load_latest_release_manifest(
185    storage_dir_override: &Option<PathBuf>,
186    platform: &str,
187) -> Result<ReleaseManifest> {
188    let manifest_path = get_releases_dir(storage_dir_override)?
189        .join(format!("ctb-{platform}-latest.json"));
190    let manifest_text =
191        std::fs::read_to_string(&manifest_path).with_context(|| {
192            format!(
193                "Failed to read release manifest {}",
194                manifest_path.display()
195            )
196        })?;
197    serde_json::from_str(&manifest_text).with_context(|| {
198        format!(
199            "Failed to parse release manifest {}",
200            manifest_path.display()
201        )
202    })
203}
204
205fn find_release_file<'a>(
206    manifest: &'a ReleaseManifest,
207    install_path: &str,
208) -> Result<&'a FileEntry> {
209    manifest
210        .files
211        .iter()
212        .find(|entry| entry.path == install_path)
213        .ok_or_else(|| {
214            anyhow!("Release file not found in manifest: {install_path}")
215        })
216}
217
218fn stream_gzip_release_entry_to_file(
219    storage_dir_override: &Option<PathBuf>,
220    entry: &FileEntry,
221    output_path: &std::path::Path,
222) -> Result<()> {
223    use flate2::Compression;
224    use flate2::GzBuilder;
225    use std::io::{BufWriter, Write};
226
227    let chunks_dir = get_release_chunks_dir(storage_dir_override)?;
228    let mut sorted_chunks = entry.chunks.clone();
229    sorted_chunks.sort_by_key(|c| c.offset);
230
231    let file = std::fs::File::create(output_path)?;
232    let mut encoder = GzBuilder::new()
233        .mtime(0)
234        .write(BufWriter::new(file), Compression::best());
235    let mut expected_offset = 0u64;
236
237    for info in &sorted_chunks {
238        ensure!(
239            info.offset == expected_offset,
240            "Non-contiguous chunk offset for {}: expected {expected_offset}, got {}",
241            entry.path,
242            info.offset
243        );
244        let chunk = read_chunk_from_directory_compressed(
245            &info.hash,
246            &chunks_dir,
247            info.offset,
248        )?;
249        let expected_len = usize::try_from(info.length)
250            .context("Chunk length exceeds usize range")?;
251        ensure!(
252            chunk.data.len() == expected_len,
253            "Chunk length mismatch for {}: expected {}, got {}",
254            info.hash,
255            info.length,
256            chunk.data.len()
257        );
258        encoder.write_all(&chunk.data)?;
259        expected_offset = expected_offset
260            .checked_add(info.length)
261            .context("Chunk range overflow while streaming gzip archive")?;
262    }
263
264    ensure!(
265        expected_offset == entry.file_size,
266        "Assembled size mismatch for {}: expected {}, got {expected_offset}",
267        entry.path,
268        entry.file_size
269    );
270
271    let mut writer = encoder.finish()?;
272    writer.flush()?;
273    Ok(())
274}
275
276fn prune_superseded_source_cache_files(
277    cache_dir: &std::path::Path,
278    active_filename: &str,
279) {
280    let prefix = if active_filename.starts_with("ctoolbox-src-") {
281        Some("ctoolbox-src-")
282    } else if active_filename.starts_with("ctoolbox-dependencies-") {
283        Some("ctoolbox-dependencies-")
284    } else {
285        None
286    };
287    let Some(prefix) = prefix else {
288        return;
289    };
290    let Ok(entries) = std::fs::read_dir(cache_dir) else {
291        return;
292    };
293    for dir_entry in entries.flatten() {
294        let path = dir_entry.path();
295        if !path.is_file() {
296            continue;
297        }
298        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
299            continue;
300        };
301        if name.starts_with(prefix)
302            && name.ends_with(".tar.gz")
303            && name != active_filename
304        {
305            let _ = std::fs::remove_file(&path);
306        }
307    }
308}
309
310async fn serve_manifest_file(
311    state: &AppState,
312    req: &RequestState,
313    headers: &HeaderMap,
314    platform: &str,
315    file_name: &str,
316    download_file_name: &str,
317    download_mime_type: &str,
318    fallback_url: &str,
319    archive_gzip: bool,
320) -> Response {
321    use futures::SinkExt;
322    use tokio::io::{AsyncReadExt, AsyncSeekExt};
323    use tokio_util::io::ReaderStream;
324
325    let platform_owned = platform.to_string();
326    let filename_owned = file_name.to_string();
327    let storage_override = state.storage_dir_override.clone();
328
329    if !archive_gzip {
330        // Stream raw manifest files (such as /installer-*) directly from bh/
331        // chunks without writing duplicate copies into downloads_cache.
332        let lookup_storage = storage_override.clone();
333        let lookup_platform = platform_owned.clone();
334        let lookup_filename = filename_owned.clone();
335
336        let entry_res = tokio::task::spawn_blocking(
337            move || -> Result<(FileEntry, PathBuf)> {
338                let manifest = load_latest_release_manifest(
339                    &lookup_storage,
340                    &lookup_platform,
341                )?;
342                let entry = find_release_file(&manifest, &lookup_filename)
343                    .or_else(|_| {
344                        if lookup_filename == "ctoolbox-installer.exe" {
345                            find_release_file(&manifest, "ctoolbox-installer")
346                        } else {
347                            bail!(
348                                "Release file not found in manifest: {lookup_filename}"
349                            )
350                        }
351                    })?
352                    .clone();
353                let chunks_dir = get_release_chunks_dir(&lookup_storage)?;
354                Ok((entry, chunks_dir))
355            },
356        )
357        .await;
358
359        let (entry, chunks_dir) = match entry_res {
360            Ok(Ok(pair)) => pair,
361            Ok(Err(error)) => {
362                return if environment::is_official_public_website() {
363                    error_404(state, req, error)
364                } else {
365                    redirect_temporary(req.is_js_request, fallback_url)
366                };
367            }
368            Err(error) => return error_400(state, req, anyhow!(error)),
369        };
370
371        let total_size = entry.file_size;
372        let range = crate::controllers::releases::parse_range_header(
373            headers, total_size,
374        );
375        // Reason for fallback: full download without Range header streams [0, total_size)
376        let (stream_start, stream_end) = range.unwrap_or((0, total_size));
377        let content_length = stream_end.saturating_sub(stream_start);
378
379        let (mut tx, rx) =
380            futures::channel::mpsc::channel::<std::io::Result<bytes::Bytes>>(4);
381        tokio::task::spawn_blocking(move || {
382            let mut sorted_chunks = entry.chunks;
383            sorted_chunks.sort_by_key(|c| c.offset);
384
385            for info in &sorted_chunks {
386                let chunk_start = info.offset;
387                let chunk_end = chunk_start.saturating_add(info.length);
388                if chunk_end <= stream_start {
389                    continue;
390                }
391                if chunk_start >= stream_end {
392                    break;
393                }
394
395                match read_chunk_from_directory_compressed(
396                    &info.hash,
397                    &chunks_dir,
398                    info.offset,
399                ) {
400                    Ok(chunk) => {
401                        let rel_start =
402                            stream_start.saturating_sub(chunk_start);
403                        let rel_end = stream_end
404                            .min(chunk_end)
405                            .saturating_sub(chunk_start);
406                        let Ok(s) = usize::try_from(rel_start) else {
407                            let _ = futures::executor::block_on(tx.send(Err(
408                                std::io::Error::other("Chunk slice overflow"),
409                            )));
410                            break;
411                        };
412                        let Ok(e) = usize::try_from(rel_end) else {
413                            let _ = futures::executor::block_on(tx.send(Err(
414                                std::io::Error::other("Chunk slice overflow"),
415                            )));
416                            break;
417                        };
418                        let Some(slice) = chunk.data.get(s..e) else {
419                            let _ = futures::executor::block_on(tx.send(Err(
420                                std::io::Error::other(
421                                    "Chunk data shorter than manifest length",
422                                ),
423                            )));
424                            break;
425                        };
426                        if futures::executor::block_on(
427                            tx.send(Ok(bytes::Bytes::copy_from_slice(slice))),
428                        )
429                        .is_err()
430                        {
431                            break;
432                        }
433                    }
434                    Err(err) => {
435                        let _ =
436                            futures::executor::block_on(tx.send(Err(
437                                std::io::Error::other(err.to_string()),
438                            )));
439                        break;
440                    }
441                }
442            }
443        });
444
445        let body = Body::new(SizedStreamBody {
446            stream: rx,
447            size: content_length,
448        });
449        let mut resp = Response::new(body);
450        if let Some((start, end)) = range {
451            *resp.status_mut() = StatusCode::PARTIAL_CONTENT;
452            let range_str =
453                format!("bytes {start}-{}/{total_size}", end.saturating_sub(1));
454            if let Ok(range_val) = HeaderValue::from_str(&range_str) {
455                resp.headers_mut().insert(header::CONTENT_RANGE, range_val);
456            }
457        }
458
459        let headers_mut = resp.headers_mut();
460        headers_mut.insert(
461            header::CONTENT_TYPE,
462            // Reason for fallback: invalid MIME type header string defaults to application/octet-stream
463            HeaderValue::from_str(download_mime_type).unwrap_or_else(|_| {
464                HeaderValue::from_static("application/octet-stream")
465            }),
466        );
467        headers_mut
468            .insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
469        if let Ok(len_val) = HeaderValue::from_str(&content_length.to_string())
470        {
471            headers_mut.insert(header::CONTENT_LENGTH, len_val);
472        }
473        if let Ok(disposition) = HeaderValue::from_str(&format!(
474            "attachment; filename=\"{download_file_name}\""
475        )) {
476            headers_mut.insert(header::CONTENT_DISPOSITION, disposition);
477        }
478        headers_mut.insert(
479            header::SET_COOKIE,
480            HeaderValue::from_static(
481                "ctb_download_started=1; Path=/; SameSite=Lax",
482            ),
483        );
484        return resp;
485    }
486
487    // 1. Get cache file path for deterministic .tar.gz source archives
488    let releases_dir = match get_releases_dir(&storage_override) {
489        Ok(d) => d,
490        Err(e) => return error_400(state, req, e),
491    };
492    let cache_dir = if storage_override.is_some() {
493        releases_dir.join("downloads_cache")
494    } else {
495        match ctb_utilities::storage::get_cache_dir() {
496            Ok(d) => d.join("downloads_cache"),
497            Err(e) => return error_400(state, req, e),
498        }
499    };
500    let cached_file_path = cache_dir.join(download_file_name);
501
502    // 2. Coordinate concurrent generation
503    let filename_string = download_file_name.to_string();
504    let mut is_generator = false;
505
506    loop {
507        if cached_file_path.exists() {
508            break;
509        }
510
511        let mut generating = state.generating_downloads.lock().await;
512        if cached_file_path.exists() {
513            break;
514        }
515
516        if generating.contains(&filename_string) {
517            // Someone else is generating it, drop lock and wait
518            drop(generating);
519            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
520        } else {
521            // We are the generator!
522            generating.insert(filename_string.clone());
523            is_generator = true;
524            break;
525        }
526    }
527
528    if is_generator {
529        let storage_override = storage_override.clone();
530        let platform_owned = platform_owned.clone();
531        let filename_owned = filename_owned.clone();
532        let cached_file_path_clone = cached_file_path.clone();
533        let active_download_name = filename_string.clone();
534        let cache_dir_clone = cache_dir.clone();
535
536        let generate_res =
537            tokio::task::spawn_blocking(move || -> Result<()> {
538                let manifest = load_latest_release_manifest(
539                    &storage_override,
540                    &platform_owned,
541                )?;
542                let archive_entry =
543                    find_release_file(&manifest, &filename_owned)?;
544
545                let temp_file_path =
546                    cached_file_path_clone.with_extension("tmp");
547                if let Some(parent) = temp_file_path.parent() {
548                    std::fs::create_dir_all(parent)?;
549                }
550                stream_gzip_release_entry_to_file(
551                    &storage_override,
552                    archive_entry,
553                    &temp_file_path,
554                )?;
555                std::fs::rename(&temp_file_path, &cached_file_path_clone)?;
556                prune_superseded_source_cache_files(
557                    &cache_dir_clone,
558                    &active_download_name,
559                );
560                Ok(())
561            })
562            .await;
563
564        // Clean up from the generating set
565        let mut generating = state.generating_downloads.lock().await;
566        generating.remove(&filename_string);
567        drop(generating);
568
569        match generate_res {
570            Ok(Ok(())) => {}
571            Ok(Err(error)) => {
572                return if environment::is_official_public_website() {
573                    error_404(state, req, error)
574                } else {
575                    redirect_temporary(req.is_js_request, fallback_url)
576                };
577            }
578            Err(error) => return error_400(state, req, anyhow!(error)),
579        }
580    }
581
582    // 3. Serve the cached file
583    let file = match tokio::fs::File::open(&cached_file_path).await {
584        Ok(f) => f,
585        Err(e) => {
586            return error_400(
587                state,
588                req,
589                anyhow!("Failed to open cached download file: {e}"),
590            );
591        }
592    };
593    let metadata = match file.metadata().await {
594        Ok(m) => m,
595        Err(e) => {
596            return error_400(
597                state,
598                req,
599                anyhow!("Failed to read cached download metadata: {e}"),
600            );
601        }
602    };
603    let total_size = metadata.len();
604
605    let range =
606        crate::controllers::releases::parse_range_header(headers, total_size);
607
608    if let Some((start, end)) = range {
609        // Range request / Partial content
610        let mut file = file;
611        if let Err(e) = file.seek(std::io::SeekFrom::Start(start)).await {
612            return error_400(
613                state,
614                req,
615                anyhow!("Failed to seek cached file: {e}"),
616            );
617        }
618        let content_length = end.saturating_sub(start);
619        let stream = ReaderStream::new(file.take(content_length));
620        let body = Body::new(SizedStreamBody {
621            stream,
622            size: content_length,
623        });
624
625        let mut resp = Response::new(body);
626        *resp.status_mut() = StatusCode::PARTIAL_CONTENT;
627
628        let headers_mut = resp.headers_mut();
629        headers_mut.insert(
630            header::CONTENT_TYPE,
631            // Reason for fallback: invalid MIME type header string defaults to application/octet-stream
632            HeaderValue::from_str(download_mime_type).unwrap_or_else(|_| {
633                HeaderValue::from_static("application/octet-stream")
634            }),
635        );
636        headers_mut
637            .insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
638
639        if let Ok(len_val) = HeaderValue::from_str(&content_length.to_string())
640        {
641            headers_mut.insert(header::CONTENT_LENGTH, len_val);
642        }
643
644        let range_str =
645            format!("bytes {start}-{}/{total_size}", end.saturating_sub(1));
646        if let Ok(range_val) = HeaderValue::from_str(&range_str) {
647            headers_mut.insert(header::CONTENT_RANGE, range_val);
648        }
649
650        if let Ok(disposition) = HeaderValue::from_str(&format!(
651            "attachment; filename=\"{download_file_name}\""
652        )) {
653            headers_mut.insert(header::CONTENT_DISPOSITION, disposition);
654        }
655        headers_mut.insert(
656            header::SET_COOKIE,
657            HeaderValue::from_static(
658                "ctb_download_started=1; Path=/; SameSite=Lax",
659            ),
660        );
661        resp
662    } else {
663        // Full response (200 OK)
664        let stream = ReaderStream::new(file);
665        let body = Body::new(SizedStreamBody {
666            stream,
667            size: total_size,
668        });
669
670        let mut resp = Response::new(body);
671        let headers_mut = resp.headers_mut();
672        headers_mut.insert(
673            header::CONTENT_TYPE,
674            // Reason for fallback: invalid MIME type header string defaults to application/octet-stream
675            HeaderValue::from_str(download_mime_type).unwrap_or_else(|_| {
676                HeaderValue::from_static("application/octet-stream")
677            }),
678        );
679        headers_mut
680            .insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
681
682        if let Ok(len_val) = HeaderValue::from_str(&total_size.to_string()) {
683            headers_mut.insert(header::CONTENT_LENGTH, len_val);
684        }
685        if let Ok(disposition) = HeaderValue::from_str(&format!(
686            "attachment; filename=\"{download_file_name}\""
687        )) {
688            headers_mut.insert(header::CONTENT_DISPOSITION, disposition);
689        }
690        headers_mut.insert(
691            header::SET_COOKIE,
692            HeaderValue::from_static(
693                "ctb_download_started=1; Path=/; SameSite=Lax",
694            ),
695        );
696        resp
697    }
698}
699
700#[pin_project::pin_project]
701pub(crate) struct SizedStreamBody<S> {
702    #[pin]
703    pub(crate) stream: S,
704    pub(crate) size: u64,
705}
706
707impl<S, T, E> http_body::Body for SizedStreamBody<S>
708where
709    S: futures::Stream<Item = Result<T, E>>,
710    T: bytes::Buf,
711{
712    type Data = T;
713    type Error = E;
714
715    fn poll_frame(
716        self: std::pin::Pin<&mut Self>,
717        cx: &mut std::task::Context<'_>,
718    ) -> std::task::Poll<
719        Option<Result<http_body::Frame<Self::Data>, Self::Error>>,
720    > {
721        let this = self.project();
722        match this.stream.poll_next(cx) {
723            std::task::Poll::Ready(Some(Ok(buf))) => {
724                std::task::Poll::Ready(Some(Ok(http_body::Frame::data(buf))))
725            }
726            std::task::Poll::Ready(Some(Err(err))) => {
727                std::task::Poll::Ready(Some(Err(err)))
728            }
729            std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
730            std::task::Poll::Pending => std::task::Poll::Pending,
731        }
732    }
733
734    fn size_hint(&self) -> http_body::SizeHint {
735        http_body::SizeHint::with_exact(self.size)
736    }
737}
738
739async fn serve_latest_installer_release(
740    state: &AppState,
741    req: &RequestState,
742    headers: &HeaderMap,
743    platform: &str,
744) -> Response {
745    let fallback_url = format!("{}/installer-{platform}", default_url());
746    let (manifest_file_name, download_file_name, mime_type) =
747        if platform == "windows-x64" {
748            (
749                "ctoolbox-installer.exe",
750                format!("ctoolbox-installer-{platform}.exe"),
751                "application/vnd.microsoft.portable-executable",
752            )
753        } else {
754            (
755                "ctoolbox-installer",
756                format!("ctoolbox-installer-{platform}.bin"),
757                "application/x-executable",
758            )
759        };
760    serve_manifest_file(
761        state,
762        req,
763        headers,
764        platform,
765        manifest_file_name,
766        &download_file_name,
767        mime_type,
768        fallback_url.as_str(),
769        false, // archive_gzip
770    )
771    .await
772}
773
774pub async fn get_src_zip_redirect(
775    State(state): State<AppState>,
776    req: RequestState,
777) -> Response {
778    let _ = state;
779    redirect_permanent(req.is_js_request, "/src.tar.gz")
780}
781
782pub async fn get_dependencies_zip_redirect(
783    State(state): State<AppState>,
784    req: RequestState,
785) -> Response {
786    let _ = state;
787    redirect_permanent(req.is_js_request, "/dependencies.tar.gz")
788}
789
790pub async fn get_src_tar_gz(
791    State(state): State<AppState>,
792    req: RequestState,
793) -> Response {
794    let _ = state;
795    let build_info = build_info();
796    let version = build_info.version;
797    let commit = build_info.commit;
798
799    let target =
800        format!("/releases/src/ctoolbox-src-{version}-{commit}.tar.gz");
801    redirect_temporary(req.is_js_request, &target)
802}
803
804pub async fn get_dependencies_tar_gz(
805    State(state): State<AppState>,
806    req: RequestState,
807) -> Response {
808    let _ = state;
809    let build_info = build_info();
810    let version = build_info.version;
811    let commit = build_info.commit;
812
813    let target = format!(
814        "/releases/src/ctoolbox-dependencies-{version}-{commit}.tar.gz"
815    );
816    redirect_temporary(req.is_js_request, &target)
817}
818
819pub async fn get_versioned_release_source(
820    State(state): State<AppState>,
821    req: RequestState,
822    headers: HeaderMap,
823    Path(filename): Path<String>,
824) -> Response {
825    if !(filename.starts_with("ctoolbox-src-")
826        || filename.starts_with("ctoolbox-dependencies-"))
827        || !filename.ends_with(".tar.gz")
828    {
829        return error_400(&state, &req, anyhow!("Invalid filename format"));
830    }
831
832    if filename.contains("..")
833        || filename.contains('/')
834        || filename.contains('\\')
835    {
836        return error_400(&state, &req, anyhow!("Invalid path characters"));
837    }
838
839    let original_filename = match filename.strip_suffix(".gz") {
840        Some(s) => s.to_string(),
841        None => return error_400(&state, &req, anyhow!("Invalid extension")),
842    };
843
844    let fallback_url = format!("{}/releases/src/{filename}", default_url());
845
846    serve_manifest_file(
847        &state,
848        &req,
849        &headers,
850        "linux-x64",
851        &original_filename,
852        &filename,
853        "application/gzip",
854        &fallback_url,
855        true, // archive_gzip
856    )
857    .await
858}
859
860pub async fn get_doc_index(
861    State(_state): State<AppState>,
862    req: RequestState,
863) -> Response {
864    let target = if req.is_embedded {
865        "/docs/index.md?embed=1"
866    } else {
867        "/docs/index.md"
868    };
869    redirect_temporary(req.is_js_request, target)
870}
871
872pub async fn get_doc_page(
873    State(state): State<AppState>,
874    req: RequestState,
875    path: axum::extract::Path<String>,
876) -> Response {
877    let path = path.as_str().trim_start_matches('/');
878
879    if path == "lib" || path == "lib/" {
880        // Redirect /docs/lib to the library docs index.html
881        // No need for ?embed=1 on this one since it's generated documentation that doesn't go through the usual UI template.
882        let target = "/docs/lib/ctoolbox/index.html";
883        return redirect_temporary(req.is_js_request, target);
884    }
885
886    if path == "rust" || path.starts_with("rust/") {
887        // The API got reorganized, so just discard the path since they'd 404 anyway.
888        return redirect_permanent(req.is_js_request, "/docs/lib");
889    }
890
891    if path == "cli/commands.md" {
892        return respond_markdown_unsafe(
893            &state,
894            req,
895            "/docs/cli/commands.generated.md",
896        );
897    }
898
899    if path.ends_with(".md") && !path.starts_with("lib/") {
900        // For markdown docs, we can render them on the fly.
901        // Content embedded as assets should be safe
902        return respond_markdown_unsafe(
903            &state,
904            req,
905            format!("/docs/{path}").as_str(),
906        );
907    }
908
909    asset_or_404(&state, req, format!("/docs/{path}").as_str())
910}
911
912pub async fn static_or_404(
913    State(state): State<AppState>,
914    req: RequestState,
915    uri: Uri,
916) -> Response {
917    asset_or_404(&state, req, uri.path())
918}
919
920fn asset_or_404(state: &AppState, req: RequestState, path: &str) -> Response {
921    let path = path.trim_start_matches('/');
922
923    // Try serving conditionally branded asset
924    let asset_dir = if branding::is_branded_build() {
925        "web/official-branding"
926    } else {
927        "web/generic-branding"
928    };
929    let mut asset = get_asset(format!("{asset_dir}/{path}").as_str());
930
931    if asset.is_none() {
932        // Try serving embedded asset
933        asset = get_asset(path);
934        if asset.is_none() {
935            asset = get_asset(format!("web/{path}").as_str());
936        }
937        if asset.is_none() {
938            if let Some(tail) = path
939                .strip_prefix("vendor/v86_images/")
940                .or_else(|| path.strip_prefix("v86_images/"))
941            {
942                asset = get_asset(format!("images/{tail}").as_str());
943                #[cfg(test)]
944                if asset.is_none()
945                    && std::path::Path::new(tail)
946                        .components()
947                        .all(|c| matches!(c, std::path::Component::Normal(_)))
948                {
949                    // Reason for fallback: when v86_images.rsrc is omitted (e.g. in CI with CTB_SKIP_V86_RSRC=1 or test VMs),
950                    // fallback to loading vendor images from disk for testing only.
951                    let mut candidate_roots = vec![
952                        std::path::PathBuf::from("vendor/v86_images"),
953                        std::path::PathBuf::from("../../../vendor/v86_images"),
954                        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
955                            .join("../../../vendor/v86_images"),
956                    ];
957                    if let Ok(exe_path) = std::env::current_exe() {
958                        // Reason for fallback: if binary executable path cannot be canonicalized, inspect the raw current_exe path
959                        let exe_path = std::fs::canonicalize(&exe_path)
960                            .unwrap_or(exe_path);
961                        if let Some(ws_root) = ctb_utilities::workspace_path_resolution::workspace_root_for_cargo_target_exe(&exe_path) {
962                            candidate_roots.push(ws_root.join("vendor/v86_images"));
963                        }
964                    }
965                    if let Ok(root) = std::env::var("CTB_HOST_WORKSPACE_ROOT") {
966                        candidate_roots.push(
967                            std::path::PathBuf::from(root)
968                                .join("vendor/v86_images"),
969                        );
970                    }
971                    if let Ok(root) = std::env::var("CTB_WIN_TEST_ROOT") {
972                        candidate_roots.push(
973                            std::path::PathBuf::from(root)
974                                .join("vendor/v86_images"),
975                        );
976                    }
977                    candidate_roots.push(std::path::PathBuf::from(
978                        r"C:\workspaces\ctoolbox\vendor\v86_images",
979                    ));
980                    for root in candidate_roots {
981                        let candidate = root.join(tail);
982                        if let Ok(file) = std::fs::File::open(&candidate) {
983                            let tokio_file = tokio::fs::File::from_std(file);
984                            let stream =
985                                tokio_util::io::ReaderStream::new(tokio_file);
986                            let mime_guess =
987                                mime_guess::from_path(tail).first();
988                            let mime_guess_str: Cow<'static, str> =
989                                match mime_guess {
990                                    Some(mime) => Cow::Owned(
991                                        mime.essence_str().to_string(),
992                                    ),
993                                    None => Cow::Borrowed(
994                                        "application/octet-stream",
995                                    ),
996                                };
997
998                            let mut resp =
999                                Response::new(Body::from_stream(stream));
1000                            resp.headers_mut().insert(
1001                                header::CONTENT_TYPE,
1002                                // Reason for fallback: invalid MIME type header string defaults to application/octet-stream
1003                                HeaderValue::from_str(mime_guess_str.as_ref())
1004                                    .unwrap_or_else(|_| {
1005                                        HeaderValue::from_static(
1006                                            "application/octet-stream",
1007                                        )
1008                                    }),
1009                            );
1010                            return resp;
1011                        }
1012                    }
1013                }
1014            }
1015        }
1016    }
1017
1018    if let Some(bytes) = asset {
1019        let mime_guess = mime_guess::from_path(path).first();
1020        let mime_guess_str: Cow<'static, str> = match mime_guess {
1021            Some(mime) => Cow::Owned(mime.essence_str().to_string()),
1022            None => Cow::Borrowed("application/octet-stream"),
1023        };
1024
1025        let mut resp = Response::new(Body::from(bytes));
1026        resp.headers_mut().insert(
1027            header::CONTENT_TYPE,
1028            // Reason for fallback: invalid MIME type header string defaults to application/octet-stream
1029            HeaderValue::from_str(mime_guess_str.as_ref()).unwrap_or_else(
1030                |_| HeaderValue::from_static("application/octet-stream"),
1031            ),
1032        );
1033        return resp;
1034    }
1035
1036    // Otherwise render 404 page
1037    error_404(
1038        state,
1039        &req,
1040        format!("The requested URL '{path}' was not found."),
1041    )
1042}
1043
1044#[cfg(test)]
1045#[allow(
1046    clippy::panic,
1047    clippy::expect_used,
1048    clippy::unwrap_used,
1049    clippy::unwrap_in_result,
1050    clippy::panic_in_result_fn,
1051    clippy::indexing_slicing,
1052    clippy::arithmetic_side_effects,
1053    reason = "Standard repository test boilerplate"
1054)]
1055mod tests {
1056    use super::*;
1057
1058    use crate::test_helpers::{
1059        TestApp, body_to_text, test_get_no_login, test_get_no_login_json,
1060        test_get_redirect_no_login,
1061    };
1062    use crate::utilities::{
1063        assert_string_contains, assert_string_not_contains,
1064    };
1065    use axum::http::{Method, StatusCode, header};
1066
1067    #[crate::ctb_test("tokio")]
1068    async fn can_get_doc_index() {
1069        let (status, location) = test_get_redirect_no_login("/docs").await;
1070        assert_eq!(status, 303);
1071        assert_eq!(location, "/docs/index.md");
1072    }
1073
1074    #[crate::ctb_test("tokio")]
1075    async fn test_docs_redirect_headers() {
1076        let app = TestApp::default();
1077        let resp = app
1078            .request_get_response::<()>(
1079                Method::GET,
1080                "/docs",
1081                None,
1082                None,
1083                None,
1084                None,
1085            )
1086            .await;
1087
1088        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
1089        let headers = resp.headers();
1090        assert_eq!(
1091            headers
1092                .get(header::CACHE_CONTROL)
1093                .unwrap()
1094                .to_str()
1095                .unwrap(),
1096            "no-store, no-cache, must-revalidate"
1097        );
1098        assert_eq!(
1099            headers.get(header::VARY).unwrap().to_str().unwrap(),
1100            "X-CollectiveToolbox-IsJsRequest"
1101        );
1102    }
1103
1104    #[crate::ctb_test("tokio")]
1105    async fn test_docs_rust_redirect() {
1106        let (status, location) = test_get_redirect_no_login("/docs/rust").await;
1107        assert_eq!(status, 308);
1108        assert_eq!(location, "/docs/lib");
1109
1110        let (status, location) = test_get_redirect_no_login(
1111            "/docs/rust/ctoolbox/macro.unwrap_or_result_error.html",
1112        )
1113        .await;
1114        assert_eq!(status, 308);
1115        assert_eq!(location, "/docs/lib");
1116
1117        let (status, body) = test_get_no_login("/docs/cli/commands.md").await;
1118        assert_eq!(status, 200);
1119        assert!(body.contains("Collective Toolbox CLI Reference"));
1120    }
1121
1122    #[crate::ctb_test("tokio")]
1123    async fn can_get_library_docs_index() {
1124        let (status, location) = test_get_redirect_no_login("/docs/lib").await;
1125        assert_eq!(status, 303);
1126        assert_eq!(location, "/docs/lib/ctoolbox/index.html");
1127        let (status, body) =
1128            test_get_no_login("/docs/lib/ctoolbox/index.html").await;
1129        assert_eq!(status, 200);
1130        let contains_stub = body
1131            .contains(ctb_build_support::asset_packer::DEBUG_LIBRARY_DOCS_STUB);
1132        let contains_title = body.contains("<title>ctoolbox - Rust</title>");
1133        assert!(
1134            contains_stub || contains_title,
1135            "Body did not contain debug stub or library title. Body: {body}"
1136        );
1137    }
1138
1139    #[crate::ctb_test("tokio")]
1140    async fn can_get_css() {
1141        let (status, body) = test_get_no_login("/app.css").await;
1142        assert_eq!(status, 200);
1143        assert!(body.contains("Abstract-Polygon-Background")); // Check for app code
1144        assert!(body.contains("SFMono-Regular")); // Check for encrecss code
1145    }
1146
1147    #[crate::ctb_test("tokio")]
1148    async fn can_download_source() {
1149        let test_app = TestApp::new();
1150        let build_info = build_info();
1151        let version = build_info.version;
1152        let commit = build_info.commit;
1153
1154        let resp = test_app
1155            .request_get_response::<()>(
1156                Method::GET,
1157                "/src.tar.gz",
1158                None,
1159                None,
1160                None,
1161                None,
1162            )
1163            .await;
1164        let status = resp.status();
1165        let location_header = resp.headers().get(header::LOCATION).cloned();
1166
1167        assert_eq!(status, StatusCode::SEE_OTHER);
1168        assert_eq!(
1169            location_header,
1170            Some(
1171                format!("/releases/src/ctoolbox-src-{version}-{commit}.tar.gz")
1172                    .parse()
1173                    .unwrap()
1174            )
1175        );
1176
1177        // Test the versioned release source URL redirect
1178        let resp2 = test_app
1179            .request_get_response::<()>(
1180                Method::GET,
1181                &format!(
1182                    "/releases/src/ctoolbox-src-{version}-{commit}.tar.gz"
1183                ),
1184                None,
1185                None,
1186                None,
1187                None,
1188            )
1189            .await;
1190        assert_eq!(resp2.status(), StatusCode::SEE_OTHER);
1191        assert_eq!(
1192            resp2.headers().get(header::LOCATION).cloned(),
1193            Some(
1194                format!(
1195                    "{}/releases/src/ctoolbox-src-{version}-{commit}.tar.gz",
1196                    default_url()
1197                )
1198                .parse()
1199                .unwrap()
1200            )
1201        );
1202    }
1203
1204    #[crate::ctb_test("tokio")]
1205    async fn can_get_404() {
1206        let (status, body) = test_get_no_login("/nonexistent").await;
1207        assert_eq!(status, 404);
1208        assert_string_contains("was not found.</h1>", &body);
1209    }
1210
1211    #[crate::ctb_test("tokio")]
1212    async fn can_get_404_json() {
1213        let (status, body) = test_get_no_login_json("/nonexistent").await;
1214        assert_eq!(status, 404);
1215        assert_string_contains("was not found.", &body);
1216        assert_string_not_contains("was not found.</h1>", &body);
1217    }
1218
1219    #[crate::ctb_test("tokio")]
1220    async fn offline_bundle_404_redirect() {
1221        let test_app = TestApp::new();
1222        let resp = test_app
1223            .request_get_response::<()>(
1224                Method::GET,
1225                "/releases/linux-x64/latest.tar",
1226                None,
1227                None,
1228                None,
1229                None,
1230            )
1231            .await;
1232
1233        let status = resp.status();
1234        let location_header = resp.headers().get(header::LOCATION).cloned();
1235
1236        assert_eq!(status, StatusCode::SEE_OTHER);
1237        assert_eq!(
1238            location_header,
1239            Some(
1240                format!("{}/releases/linux-x64/latest.tar", default_url())
1241                    .parse()
1242                    .unwrap()
1243            )
1244        );
1245    }
1246
1247    #[crate::ctb_test("tokio")]
1248    async fn manifest_file_range_request() {
1249        //bypass-tempdir-lint
1250        let test_app = TestApp::new();
1251        let storage_dir = test_app
1252            .state
1253            .storage_dir_override
1254            .as_ref()
1255            .unwrap()
1256            .join("releases");
1257        std::fs::create_dir_all(&storage_dir).unwrap();
1258
1259        let chunks_dir = storage_dir.join("bh");
1260        std::fs::create_dir_all(&chunks_dir).unwrap();
1261
1262        // Write a mock manifest ctb-linux-x64-latest.json
1263        let manifest_content = r#"{
1264            "format_version": 1,
1265            "ctoolbox_version": "0.1.0",
1266            "platform": "linux-x64",
1267            "date": "2026-06-16T22:43:00Z",
1268            "revoked_key_ids": [],
1269            "files": [
1270                {
1271                    "path": "ctoolbox-installer",
1272                    "checksum": "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9",
1273                    "file_size": 11,
1274                    "gzip_after_install": false,
1275                    "feature_id": "core",
1276                    "feature_name": {},
1277                    "requires": [],
1278                    "required": true,
1279                    "unavailable": false,
1280                    "chunks": [
1281                        {
1282                            "hash": "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9",
1283                            "offset": 0,
1284                            "length": 11
1285                        }
1286                    ]
1287                }
1288            ]
1289        }"#;
1290
1291        std::fs::write(
1292            storage_dir.join("ctb-linux-x64-latest.json"),
1293            manifest_content,
1294        )
1295        .unwrap();
1296
1297        // Write a mock chunk file compressed with Brotli containing "hello world"
1298        // "hello world" is 11 bytes.
1299        let mut compressed_data = Vec::new();
1300        {
1301            let mut encoder = brotli::CompressorWriter::new(
1302                &mut compressed_data,
1303                4096,
1304                11,
1305                22,
1306            );
1307            use std::io::Write;
1308            encoder.write_all(b"hello world").unwrap();
1309            encoder.flush().unwrap();
1310        }
1311
1312        let chunk_hash =
1313            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
1314        let chunk_prefix1 = chunk_hash.get(0..2).unwrap_or("");
1315        let chunk_prefix2 = chunk_hash.get(2..4).unwrap_or("");
1316        let chunk_path_dir = chunks_dir.join(chunk_prefix1).join(chunk_prefix2);
1317        std::fs::create_dir_all(&chunk_path_dir).unwrap();
1318        std::fs::write(
1319            chunk_path_dir.join(format!("{chunk_hash}.br")),
1320            compressed_data,
1321        )
1322        .unwrap();
1323
1324        // 1. Request without range
1325        let resp = test_app
1326            .request_get_response::<()>(
1327                Method::GET,
1328                "/installer-linux-x64",
1329                None,
1330                None,
1331                None,
1332                None,
1333            )
1334            .await;
1335
1336        assert_eq!(resp.status(), StatusCode::OK);
1337        assert_eq!(
1338            resp.headers().get(header::ACCEPT_RANGES),
1339            Some(&HeaderValue::from_static("bytes"))
1340        );
1341        assert_eq!(
1342            resp.headers().get(header::CONTENT_LENGTH),
1343            Some(&HeaderValue::from_static("11"))
1344        );
1345        let body = body_to_text(resp).await;
1346        assert_eq!(body, "hello world");
1347
1348        // 2. Request with partial range (0-4)
1349        let mut headers = HeaderMap::new();
1350        headers.insert(header::RANGE, "bytes=0-4".parse().unwrap());
1351        let resp_range = test_app
1352            .request_get_response::<()>(
1353                Method::GET,
1354                "/installer-linux-x64",
1355                Some(headers),
1356                None,
1357                None,
1358                None,
1359            )
1360            .await;
1361
1362        assert_eq!(resp_range.status(), StatusCode::PARTIAL_CONTENT);
1363        assert_eq!(
1364            resp_range.headers().get(header::ACCEPT_RANGES),
1365            Some(&HeaderValue::from_static("bytes"))
1366        );
1367        assert_eq!(
1368            resp_range.headers().get(header::CONTENT_LENGTH),
1369            Some(&HeaderValue::from_static("5"))
1370        );
1371        assert_eq!(
1372            resp_range.headers().get(header::CONTENT_RANGE),
1373            Some(&HeaderValue::from_static("bytes 0-4/11"))
1374        );
1375        let body_range = body_to_text(resp_range).await;
1376        assert_eq!(body_range, "hello");
1377
1378        // Ensure serving /installer-* streams directly from bh/ without writing duplicate files to downloads_cache
1379        assert!(!storage_dir.join("downloads_cache").exists());
1380    }
1381}