ctb_io_webui/controllers/
releases.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 serving software release artifacts.
21//!
22//! Provides routes for the installer/updater to fetch:
23//! - Release manifests (latest or by version)
24//! - Offline installer tarballs (with Range request support)
25//! - Individual chunk data by hash (stored compressed, served decompressed)
26//! - Public key for signature verification
27
28use crate::utilities::*;
29
30use anyhow::anyhow;
31use axum::{
32    body::Body,
33    extract::{Path, State},
34    http::{HeaderMap, HeaderValue, StatusCode, header},
35    response::Response,
36};
37use base64::Engine;
38use ctb_formats_pem::ed25519_base64_to_pem;
39
40use serde::Serialize;
41use std::io::Read;
42use std::path::{Path as StdPath, PathBuf};
43use tokio::fs::File;
44use tokio_util::io::ReaderStream;
45
46use crate::utilities::pc_settings::{PcSettingStrKey, get_str_setting};
47use crate::utilities::storage::get_storage_dir;
48use crate::{AppState, RequestState, error_400, error_404};
49use ctb_installer::chunking::{
50    compute_sha256_hex, read_chunk_from_directory_compressed,
51};
52use ctb_installer::manifest::FileEntry;
53use ctb_installer::manifest::ReleaseManifest;
54use ctb_installer::signing::{KeyId, PUBLIC_KEY_LENGTH, SigningPublicKey};
55use ctb_installer::tarball::{StreamingTarball, TarballStream};
56
57/// GET /releases/{platform}/{*artifact}
58///
59/// Dispatcher used to support URLs like:
60/// - `/releases/{platform}/{version}.json`
61/// - `/releases/{platform}/{version}.tar`
62///
63/// Axum's router does not allow `{version}.json` style patterns because that
64/// puts both a parameter and a literal in the same path segment.
65pub async fn get_platform_dispatch(
66    State(state): State<AppState>,
67    req: RequestState,
68    headers: HeaderMap,
69    Path((platform, artifact)): Path<(String, String)>,
70) -> Response {
71    // The catch-all may include additional slashes. We only support a single
72    // segment here.
73    if artifact.contains('/') || artifact.contains('\\') {
74        return error_404(&state, &req, "Not found".to_string());
75    }
76
77    if artifact == "latest.json" {
78        return get_latest_manifest(State(state), req, Path(platform)).await;
79    }
80
81    if artifact == "latest.json.sig" {
82        return get_latest_manifest_sig(State(state), req, Path(platform))
83            .await;
84    }
85
86    if let Some(version) = artifact.strip_suffix(".json") {
87        return get_manifest_by_version(
88            State(state),
89            req,
90            Path((platform, version.to_string())),
91        )
92        .await;
93    }
94
95    if let Some(version) = artifact.strip_suffix(".json.sig") {
96        return get_manifest_sig_by_version(
97            State(state),
98            req,
99            Path((platform, version.to_string())),
100        )
101        .await;
102    }
103
104    if let Some(version) = artifact.strip_suffix(".tar") {
105        return get_offline_tarball(
106            State(state),
107            req,
108            headers,
109            Path((platform, version.to_string())),
110        )
111        .await;
112    }
113
114    error_404(&state, &req, "Not found".to_string())
115}
116
117/// GET /releases/chunks/{prefix1}/{prefix2}/{*tail}
118///
119/// Dispatcher used to support URLs like:
120/// - `/releases/chunks/{prefix1}/{prefix2}/{hash}.json`
121pub async fn get_chunks_dispatch(
122    State(state): State<AppState>,
123    req: RequestState,
124    Path((prefix1, prefix2, tail)): Path<(String, String, String)>,
125) -> Response {
126    // The catch-all may include additional slashes. We only support a single
127    // segment here.
128    if tail.contains('/') || tail.contains('\\') {
129        return error_404(&state, &req, "Not found".to_string());
130    }
131
132    if tail.ends_with(".json") {
133        return get_chunk_json(
134            State(state),
135            req,
136            Path((prefix1, prefix2, tail)),
137        )
138        .await;
139    }
140
141    get_chunk_raw(State(state), req, Path((prefix1, prefix2, tail))).await
142}
143
144/// Response structure for chunk data as JSON.
145#[derive(Serialize)]
146struct ChunkResponse {
147    /// SHA-256 hash of the chunk.
148    hash: String,
149    /// Base64-encoded chunk data.
150    data: String,
151    /// Length of the chunk in bytes.
152    length: u64,
153}
154
155/// Response structure for public key endpoint.
156#[derive(Serialize)]
157struct PublicKeyResponse {
158    /// Base64-encoded Ed25519 public key.
159    public_key: String,
160    /// Key ID (first 8 bytes of public key hash, hex-encoded).
161    key_id: String,
162}
163
164/// Returns the releases directory within the storage directory.
165fn get_releases_dir(
166    storage_dir_override: Option<&PathBuf>,
167) -> anyhow::Result<PathBuf> {
168    let storage = if let Some(path) = storage_dir_override {
169        path.clone()
170    } else {
171        get_storage_dir()?
172    };
173    Ok(storage.join("releases"))
174}
175
176/// Returns the chunks directory (bh/) within the releases directory.
177fn get_chunks_dir(
178    storage_dir_override: Option<&PathBuf>,
179) -> anyhow::Result<PathBuf> {
180    Ok(get_releases_dir(storage_dir_override)?.join("bh"))
181}
182
183fn find_manifest_file<'a>(
184    manifest: &'a ReleaseManifest,
185    install_path: &str,
186) -> Result<&'a FileEntry, TarballLoadError> {
187    manifest
188        .files
189        .iter()
190        .find(|entry| entry.path == install_path)
191        .ok_or_else(|| {
192            TarballLoadError::BadRequest(format!(
193                "Release file not found in manifest: {install_path}"
194            ))
195        })
196}
197
198fn assemble_release_file_bytes(
199    entry: &FileEntry,
200    chunks_dir: &StdPath,
201) -> Result<Vec<u8>, TarballLoadError> {
202    let total_len = usize::try_from(entry.file_size).map_err(|_| {
203        TarballLoadError::BadRequest(
204            "Release file size exceeds usize range".to_string(),
205        )
206    })?;
207    let mut bytes = vec![0u8; total_len];
208
209    for info in &entry.chunks {
210        let start = usize::try_from(info.offset).map_err(|_| {
211            TarballLoadError::BadRequest(
212                "Chunk offset exceeds usize range".to_string(),
213            )
214        })?;
215        let length = usize::try_from(info.length).map_err(|_| {
216            TarballLoadError::BadRequest(
217                "Chunk length exceeds usize range".to_string(),
218            )
219        })?;
220        let end = start.checked_add(length).ok_or_else(|| {
221            TarballLoadError::BadRequest(
222                "Chunk range overflow while assembling release file"
223                    .to_string(),
224            )
225        })?;
226        if end > bytes.len() {
227            return Err(TarballLoadError::BadRequest(format!(
228                "Chunk range exceeds assembled file size for {}",
229                entry.path
230            )));
231        }
232
233        let chunk = read_chunk_from_directory_compressed(
234            &info.hash,
235            chunks_dir,
236            info.offset,
237        )
238        .map_err(|error| TarballLoadError::BadRequest(error.to_string()))?;
239        if chunk.data.len() != length {
240            return Err(TarballLoadError::BadRequest(format!(
241                "Chunk length mismatch for {}: expected {}, got {}",
242                info.hash,
243                info.length,
244                chunk.data.len()
245            )));
246        }
247        if let Some(slice) = bytes.get_mut(start..end) {
248            slice.copy_from_slice(&chunk.data);
249        }
250    }
251
252    let assembled_hash = compute_sha256_hex(&bytes);
253    if assembled_hash != entry.checksum {
254        return Err(TarballLoadError::BadRequest(format!(
255            "Assembled file checksum mismatch for {}: expected {}, got {}",
256            entry.path, entry.checksum, assembled_hash
257        )));
258    }
259
260    Ok(bytes)
261}
262
263/// Returns whether `platform` (lowercased) is a supported release target slug.
264pub(crate) fn is_supported_release_platform(platform: &str) -> bool {
265    matches!(
266        platform,
267        "linux-x64"
268            | "linux-x86"
269            | "windows-x64"
270            | "freebsd-x64"
271            | "mac-x64"
272            | "mac-arm64"
273    )
274}
275
276/// Computes the path to a compressed chunk using two-level prefix.
277///
278/// Format: `{chunks_dir}/{first-2-chars}/{next-2-chars}/{full-hash}.br`
279fn compressed_chunk_file_path(chunks_dir: &StdPath, hash: &str) -> PathBuf {
280    ctb_installer::chunking::compressed_chunk_file_path(chunks_dir, hash)
281}
282
283/// GET /releases/{platform}/latest.json
284///
285/// Serves the latest release manifest for a specific platform.
286/// The latest manifest is expected to be symlinked or copied to
287/// `{storage_dir}/releases/ctb-{platform}-latest.json`.
288pub async fn get_latest_manifest(
289    State(state): State<AppState>,
290    req: RequestState,
291    Path(platform): Path<String>,
292) -> Response {
293    // Validate target
294    let platform = platform.to_lowercase();
295    if !is_supported_release_platform(&platform) {
296        return error_400(
297            &state,
298            &req,
299            anyhow!(
300                "Invalid platform: {platform}. Use e.g. linux-x64, linux-x86, windows-x64, freebsd-x64, mac-x64, or mac-arm64."
301            ),
302        );
303    }
304
305    let releases_dir =
306        match get_releases_dir(state.storage_dir_override.as_ref()) {
307            Ok(d) => d,
308            Err(e) => return error_400(&state, &req, e),
309        };
310
311    let manifest_path =
312        releases_dir.join(format!("ctb-{platform}-latest.json"));
313    serve_json_file(&state, &req, &manifest_path).await
314}
315
316/// GET /releases/{platform}/{version}.json
317///
318/// Serves a specific release manifest by platform and version string.
319/// The version should match a manifest file named `ctb-{platform}-{version}.json`.
320pub async fn get_manifest_by_version(
321    State(state): State<AppState>,
322    req: RequestState,
323    Path((platform, version)): Path<(String, String)>,
324) -> Response {
325    // Validate target
326    let platform = platform.to_lowercase();
327    if !is_supported_release_platform(&platform) {
328        return error_400(
329            &state,
330            &req,
331            anyhow!(
332                "Invalid platform: {platform}. Use e.g. linux-x64, linux-x86, windows-x64, freebsd-x64, mac-x64, or mac-arm64."
333            ),
334        );
335    }
336
337    // Sanitize version string to prevent path traversal
338    if version.contains("..") || version.contains('/') || version.contains('\\')
339    {
340        return error_400(&state, &req, anyhow!("Invalid version string"));
341    }
342
343    let releases_dir =
344        match get_releases_dir(state.storage_dir_override.as_ref()) {
345            Ok(d) => d,
346            Err(e) => return error_400(&state, &req, e),
347        };
348
349    // Try to find a manifest matching the platform and version
350    // Format: ctb-{platform}-{version}.json
351    let manifest_path =
352        releases_dir.join(format!("ctb-{platform}-{version}.json"));
353    serve_json_file(&state, &req, &manifest_path).await
354}
355
356/// GET /releases/chunks/{prefix1}/{prefix2}/{hash}
357///
358/// Serves raw chunk bytes by SHA-256 hash from the bh/ directory.
359/// Chunks are stored compressed (.gz) but served decompressed.
360/// Uses two-level prefix: bh/{first-2-chars}/{next-2-chars}/{full-hash}.gz
361pub async fn get_chunk_raw(
362    State(state): State<AppState>,
363    req: RequestState,
364    Path((prefix1, prefix2, hash)): Path<(String, String, String)>,
365) -> Response {
366    // Validate hash format (should be 64 hex characters for SHA-256)
367    if !is_valid_chunk_hash(&hash) {
368        return error_400(&state, &req, anyhow!("Invalid chunk hash format"));
369    }
370
371    // Validate prefixes match hash (already checked length via is_valid_chunk_hash)
372    if hash.get(0..2) != Some(prefix1.as_str())
373        || hash.get(2..4) != Some(prefix2.as_str())
374    {
375        return error_400(&state, &req, anyhow!("Prefix mismatch"));
376    }
377
378    let chunks_dir = match get_chunks_dir(state.storage_dir_override.as_ref()) {
379        Ok(d) => d,
380        Err(e) => return error_400(&state, &req, e),
381    };
382
383    let chunk_path = compressed_chunk_file_path(&chunks_dir, &hash);
384
385    // Check if compressed file exists
386    if !chunk_path.exists() {
387        return error_404(&state, &req, format!("Chunk '{hash}' not found"));
388    }
389
390    // Read and decompress the chunk using Brotli
391    let compressed_data = match tokio::fs::read(&chunk_path).await {
392        Ok(d) => d,
393        Err(e) => return error_400(&state, &req, anyhow!(e)),
394    };
395
396    let mut decoder = brotli::Decompressor::new(&compressed_data[..], 4096);
397    let mut decompressed = Vec::new();
398    if let Err(e) = decoder.read_to_end(&mut decompressed) {
399        return error_400(
400            &state,
401            &req,
402            anyhow!("Failed to decompress chunk: {e}"),
403        );
404    }
405
406    let body = Body::from(decompressed);
407
408    let mut resp = Response::new(body);
409    resp.headers_mut().insert(
410        header::CONTENT_TYPE,
411        HeaderValue::from_static("application/octet-stream"),
412    );
413    resp
414}
415
416/// GET /releases/chunks/{prefix}/{hash}.json
417///
418/// Serves chunk data as JSON containing base64-encoded bytes.
419/// Chunks are stored compressed but decompressed for the response.
420/// This allows adding metadata in the future if needed.
421pub async fn get_chunk_json(
422    State(state): State<AppState>,
423    req: RequestState,
424    Path((prefix1, prefix2, hash)): Path<(String, String, String)>,
425) -> Response {
426    // The path may include .json suffix, so strip it to get the actual hash
427    let hash = hash.trim_end_matches(".json");
428
429    // Validate hash format
430    if !is_valid_chunk_hash(hash) {
431        return error_400(&state, &req, anyhow!("Invalid chunk hash format"));
432    }
433
434    // Validate prefixes match hash (already checked length via is_valid_chunk_hash)
435    if hash.get(0..2) != Some(prefix1.as_str())
436        || hash.get(2..4) != Some(prefix2.as_str())
437    {
438        return error_400(&state, &req, anyhow!("Prefix mismatch"));
439    }
440
441    let chunks_dir = match get_chunks_dir(state.storage_dir_override.as_ref()) {
442        Ok(d) => d,
443        Err(e) => return error_400(&state, &req, e),
444    };
445
446    let chunk_path = compressed_chunk_file_path(&chunks_dir, hash);
447
448    // Check if compressed file exists
449    if !chunk_path.exists() {
450        return error_404(&state, &req, format!("Chunk '{hash}' not found"));
451    }
452
453    // Read and decompress the chunk data using Brotli
454    let compressed_data = match tokio::fs::read(&chunk_path).await {
455        Ok(d) => d,
456        Err(e) => return error_400(&state, &req, anyhow!(e)),
457    };
458
459    let mut decoder = brotli::Decompressor::new(&compressed_data[..], 4096);
460    let mut data = Vec::new();
461    if let Err(e) = decoder.read_to_end(&mut data) {
462        return error_400(
463            &state,
464            &req,
465            anyhow!("Failed to decompress chunk: {e}"),
466        );
467    }
468
469    // Encode as base64 and wrap in JSON
470    let data_b64 = base64::engine::general_purpose::STANDARD.encode(&data);
471
472    let response = ChunkResponse {
473        hash: hash.to_string(),
474        data: data_b64,
475        // Reason for fallback: data buffer length u64 conversion overflow defaults length to 0
476        length: u64::try_from(data.len()).unwrap_or(0),
477    };
478
479    let json = match serde_json::to_string(&response) {
480        Ok(j) => j,
481        Err(e) => return error_400(&state, &req, anyhow!(e)),
482    };
483
484    let mut resp = Response::new(Body::from(json));
485    resp.headers_mut().insert(
486        header::CONTENT_TYPE,
487        HeaderValue::from_static("application/json"),
488    );
489    resp
490}
491
492/// GET /releases/public-key
493///
494/// Returns JSON with the server's release verification public key and key ID.
495/// The public key is loaded from `pc_settings.release_public_key`.
496pub async fn get_public_key(
497    State(state): State<AppState>,
498    req: RequestState,
499) -> Response {
500    let Some(pubkey_b64) = get_str_setting(PcSettingStrKey::ReleasePublicKey)
501    else {
502        return error_404(
503            &state,
504            &req,
505            "Release public key not configured".to_string(),
506        );
507    };
508
509    // Decode the public key to compute the key ID
510    let pubkey_bytes =
511        match base64::engine::general_purpose::STANDARD.decode(&pubkey_b64) {
512            Ok(b) => b,
513            Err(e) => {
514                return error_400(
515                    &state,
516                    &req,
517                    anyhow!("Invalid public key encoding: {e}"),
518                );
519            }
520        };
521
522    let pubkey_array: [u8; PUBLIC_KEY_LENGTH] = match pubkey_bytes.try_into() {
523        Ok(arr) => arr,
524        Err(v) => {
525            return error_400(
526                &state,
527                &req,
528                anyhow!(
529                    "Invalid public key length: expected {}, got {}",
530                    PUBLIC_KEY_LENGTH,
531                    v.len()
532                ),
533            );
534        }
535    };
536
537    let pubkey = match SigningPublicKey::from_bytes(&pubkey_array) {
538        Ok(k) => k,
539        Err(e) => {
540            return error_400(&state, &req, anyhow!("Invalid public key: {e}"));
541        }
542    };
543
544    let key_id = KeyId::from_public_key(&pubkey);
545
546    let response = PublicKeyResponse {
547        public_key: pubkey_b64,
548        key_id: key_id.to_hex(),
549    };
550
551    let json = match serde_json::to_string(&response) {
552        Ok(j) => j,
553        Err(e) => return error_400(&state, &req, anyhow!(e)),
554    };
555
556    let mut resp = Response::new(Body::from(json));
557    resp.headers_mut().insert(
558        header::CONTENT_TYPE,
559        HeaderValue::from_static("application/json"),
560    );
561    resp
562}
563
564/// GET /releases/{platform}/{version}.tar
565///
566/// Serves an offline installer tarball containing the manifest and all chunks.
567/// Supports HTTP Range requests for resumable downloads.
568///
569/// The tarball structure is:
570/// ```text
571/// ctoolbox-{platform}-{version}/
572/// ├── manifest.json
573/// ├── chunks/
574/// │   ├── {hash1}.br
575/// │   ├── {hash2}.br
576/// │   └── ...
577/// └── ctoolbox-installer (optional, if installer binary exists)
578/// ```
579///
580/// # Range Request Support
581///
582/// This endpoint supports the `Range` header for resumable downloads:
583/// - `Range: bytes=0-` - Start from beginning
584/// - `Range: bytes=1000-` - Resume from byte 1000
585/// - `Range: bytes=1000-2000` - Request specific range
586///
587/// Range requests return 206 Partial Content with appropriate headers.
588pub async fn get_offline_tarball(
589    State(state): State<AppState>,
590    req: RequestState,
591    headers: HeaderMap,
592    Path((platform, version)): Path<(String, String)>,
593) -> Response {
594    use crate::controllers::base::SizedStreamBody;
595    use futures::SinkExt;
596
597    // Validate and load tarball metadata directly from manifest + bh/ chunks
598    let tarball = match load_tarball_for_version(
599        state.storage_dir_override.as_ref(),
600        &platform,
601        &version,
602    ) {
603        Ok(t) => t,
604        Err(TarballLoadError::BadRequest(msg)) => {
605            return error_400(&state, &req, anyhow!("{msg}"));
606        }
607        Err(TarballLoadError::NotFound(msg)) => {
608            let fallback_url =
609                format!("{}/releases/{platform}/{version}.tar", default_url());
610            return if environment::is_official_public_website() {
611                error_404(&state, &req, msg)
612            } else {
613                crate::controllers::base::redirect_temporary(
614                    req.is_js_request,
615                    &fallback_url,
616                )
617            };
618        }
619    };
620
621    let resolved_version = tarball.version();
622    let download_file_name =
623        format!("ctoolbox-{platform}-{resolved_version}.tar");
624    let total_size = tarball.total_size();
625    let range = parse_range_header(&headers, total_size);
626    // Reason for fallback: full download without Range header streams [0, total_size)
627    let (stream_start, stream_end) = range.unwrap_or((0, total_size));
628    let content_length = stream_end.saturating_sub(stream_start);
629
630    let (mut tx, rx) =
631        futures::channel::mpsc::channel::<std::io::Result<bytes::Bytes>>(4);
632    tokio::task::spawn_blocking(move || {
633        const SLICE_LEN: u64 = 2 * 1024 * 1024;
634        let mut pos = stream_start;
635        while pos < stream_end {
636            let next_pos = pos.saturating_add(SLICE_LEN).min(stream_end);
637            match tarball.generate_range(pos, Some(next_pos)) {
638                Ok(chunk_bytes) => {
639                    if chunk_bytes.is_empty() {
640                        break;
641                    }
642                    pos = next_pos;
643                    if futures::executor::block_on(
644                        tx.send(Ok(bytes::Bytes::from(chunk_bytes))),
645                    )
646                    .is_err()
647                    {
648                        break;
649                    }
650                }
651                Err(err) => {
652                    let _ = futures::executor::block_on(tx.send(Err(
653                        std::io::Error::other(err.to_string()),
654                    )));
655                    break;
656                }
657            }
658        }
659    });
660
661    let body = Body::new(SizedStreamBody {
662        stream: rx,
663        size: content_length,
664    });
665
666    let mut resp = Response::new(body);
667    if let Some((start, end)) = range {
668        *resp.status_mut() = StatusCode::PARTIAL_CONTENT;
669        let range_str =
670            format!("bytes {start}-{}/{total_size}", end.saturating_sub(1));
671        if let Ok(range_val) = HeaderValue::from_str(&range_str) {
672            resp.headers_mut().insert(header::CONTENT_RANGE, range_val);
673        }
674    }
675
676    let headers_mut = resp.headers_mut();
677    headers_mut.insert(
678        header::CONTENT_TYPE,
679        HeaderValue::from_static("application/x-tar"),
680    );
681    headers_mut
682        .insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
683
684    if let Ok(len_val) = HeaderValue::from_str(&content_length.to_string()) {
685        headers_mut.insert(header::CONTENT_LENGTH, len_val);
686    }
687    if let Ok(disposition) = HeaderValue::from_str(&format!(
688        "attachment; filename=\"{download_file_name}\""
689    )) {
690        headers_mut.insert(header::CONTENT_DISPOSITION, disposition);
691    }
692    headers_mut.insert(
693        header::SET_COOKIE,
694        HeaderValue::from_static(
695            "ctb_download_started=1; Path=/; SameSite=Lax",
696        ),
697    );
698    resp
699}
700
701/// Error type for tarball loading.
702enum TarballLoadError {
703    BadRequest(String),
704    NotFound(String),
705}
706
707/// Loads and validates a streaming tarball for the given platform and version.
708fn load_tarball_for_version(
709    storage_dir_override: Option<&PathBuf>,
710    platform: &str,
711    version: &str,
712) -> Result<StreamingTarball, TarballLoadError> {
713    let platform_lower = platform.to_lowercase();
714    if !is_supported_release_platform(&platform_lower) {
715        return Err(TarballLoadError::BadRequest(format!(
716            "Invalid platform: {platform}. Use linux-x86, linux-x64, windows-x64, freebsd-x64, mac-x64, or mac-arm64."
717        )));
718    }
719
720    if version.contains("..") || version.contains('/') || version.contains('\\')
721    {
722        return Err(TarballLoadError::BadRequest(
723            "Invalid version string".into(),
724        ));
725    }
726
727    let version = version.trim_end_matches(".tar");
728
729    let releases_dir = get_releases_dir(storage_dir_override)
730        .map_err(|e| TarballLoadError::BadRequest(e.to_string()))?;
731
732    let manifest_path = if version == "latest" {
733        releases_dir.join(format!("ctb-{platform_lower}-latest.json"))
734    } else {
735        releases_dir.join(format!("ctb-{platform_lower}-{version}.json"))
736    };
737
738    if !manifest_path.exists() {
739        return Err(TarballLoadError::NotFound(format!(
740            "Release manifest for {platform}/{version} not found"
741        )));
742    }
743
744    let manifest_content =
745        std::fs::read_to_string(&manifest_path).map_err(|e| {
746            TarballLoadError::BadRequest(format!(
747                "Failed to read manifest: {e}"
748            ))
749        })?;
750
751    let manifest: ReleaseManifest = serde_json::from_str(&manifest_content)
752        .map_err(|e| {
753            TarballLoadError::BadRequest(format!(
754                "Failed to parse manifest: {e}"
755            ))
756        })?;
757
758    let chunks_dir = get_chunks_dir(storage_dir_override)
759        .map_err(|e| TarballLoadError::BadRequest(e.to_string()))?;
760
761    let expected_installer = manifest.platform.installer_binary_name();
762    let installer_bytes = find_manifest_file(&manifest, expected_installer)
763        .or_else(|_| find_manifest_file(&manifest, "ctoolbox-installer"))
764        .and_then(|entry| assemble_release_file_bytes(entry, &chunks_dir))
765        .ok();
766
767    StreamingTarball::new_with_installer_bytes(
768        manifest,
769        chunks_dir.to_string_lossy().to_string(),
770        installer_bytes,
771    )
772    .map_err(|e| {
773        TarballLoadError::BadRequest(format!("Failed to create tarball: {e}"))
774    })
775}
776
777/// Parses the Range header and returns the start and end byte positions.
778///
779/// Returns `Some((start, end))` if a valid range was specified, where `end`
780/// is exclusive. Returns `None` if no Range header or invalid format.
781pub(crate) fn parse_range_header(
782    headers: &HeaderMap,
783    total_size: u64,
784) -> Option<(u64, u64)> {
785    let range_header = headers.get(header::RANGE)?;
786    let range_str = range_header.to_str().ok()?;
787
788    // Format: "bytes=start-end" or "bytes=start-"
789    let range_str = range_str.strip_prefix("bytes=")?;
790
791    let (start_str, end_str) = range_str.split_once('-')?;
792
793    let start: u64 = start_str.parse().ok()?;
794
795    let end: u64 = if end_str.is_empty() {
796        total_size
797    } else {
798        // HTTP ranges are inclusive, so add 1 for exclusive end
799        end_str
800            .parse::<u64>()
801            .ok()?
802            .saturating_add(1)
803            .min(total_size)
804    };
805
806    if start >= end || start >= total_size {
807        return None;
808    }
809
810    Some((start, end))
811}
812
813/// Validates that a string is a valid SHA-256 chunk hash (64 hex characters).
814fn is_valid_chunk_hash(hash: &str) -> bool {
815    hash.len() == 64 && hash.chars().all(|c| c.is_ascii_hexdigit())
816}
817
818/// Helper to serve a JSON file from disk.
819async fn serve_json_file(
820    state: &AppState,
821    req: &RequestState,
822    path: &PathBuf,
823) -> Response {
824    // Check if file exists
825    if !path.exists() {
826        return error_404(
827            state,
828            req,
829            format!(
830                "Manifest '{}' not found",
831                // Reason for fallback: file path without file_name component formats name as "unknown"
832                path.file_name().map_or_else(
833                    || "unknown".to_string(),
834                    |s| s.to_string_lossy().into_owned()
835                )
836            ),
837        );
838    }
839
840    // Open and stream the file
841    let file = match File::open(path).await {
842        Ok(f) => f,
843        Err(e) => return error_400(state, req, anyhow!(e)),
844    };
845
846    let stream = ReaderStream::new(file);
847    let body = Body::from_stream(stream);
848
849    let mut resp = Response::new(body);
850    resp.headers_mut().insert(
851        header::CONTENT_TYPE,
852        HeaderValue::from_static("application/json"),
853    );
854    resp
855}
856
857/// Helper to serve a signature file from disk.
858async fn serve_sig_file(
859    state: &AppState,
860    req: &RequestState,
861    path: &PathBuf,
862) -> Response {
863    if !path.exists() {
864        return error_404(
865            state,
866            req,
867            format!(
868                "Signature '{}' not found",
869                // Reason for fallback: file path without file_name component formats name as "unknown"
870                path.file_name().map_or_else(
871                    || "unknown".to_string(),
872                    |s| s.to_string_lossy().into_owned()
873                )
874            ),
875        );
876    }
877
878    let file = match File::open(path).await {
879        Ok(f) => f,
880        Err(e) => return error_400(state, req, anyhow!(e)),
881    };
882
883    let stream = ReaderStream::new(file);
884    let body = Body::from_stream(stream);
885
886    let mut resp = Response::new(body);
887    resp.headers_mut().insert(
888        header::CONTENT_TYPE,
889        HeaderValue::from_static("application/octet-stream"),
890    );
891    resp
892}
893
894/// GET /releases/{platform}/latest.json.sig
895pub async fn get_latest_manifest_sig(
896    State(state): State<AppState>,
897    req: RequestState,
898    Path(platform): Path<String>,
899) -> Response {
900    let platform = platform.to_lowercase();
901    if !is_supported_release_platform(&platform) {
902        return error_400(&state, &req, anyhow!("Invalid platform"));
903    }
904
905    let releases_dir =
906        match get_releases_dir(state.storage_dir_override.as_ref()) {
907            Ok(d) => d,
908            Err(e) => return error_400(&state, &req, e),
909        };
910
911    let mut sig_path =
912        releases_dir.join(format!("ctb-{platform}-latest.json.sig"));
913    if !sig_path.exists() {
914        let manifest_path =
915            releases_dir.join(format!("ctb-{platform}-latest.json"));
916        let resolved_manifest =
917            match files::symlink_is_in_dir(&manifest_path, &releases_dir) {
918                Ok(path) => path,
919                Err(error) => return error_400(&state, &req, error),
920            };
921        if resolved_manifest != manifest_path {
922            let mut sig_file = resolved_manifest.clone();
923            if let Some(ext) = resolved_manifest.extension() {
924                let mut new_ext = ext.to_os_string();
925                new_ext.push(".sig");
926                sig_file.set_extension(new_ext);
927            }
928            if sig_file.exists() {
929                sig_path = sig_file;
930            }
931        }
932        if !sig_path.exists() && manifest_path.is_file() {
933            let latest_bytes = match tokio::fs::read(&manifest_path).await {
934                Ok(bytes) => bytes,
935                Err(error) => return error_400(&state, &req, anyhow!(error)),
936            };
937            let manifest: ReleaseManifest =
938                match serde_json::from_slice(&latest_bytes) {
939                    Ok(manifest) => manifest,
940                    Err(error) => {
941                        return error_400(&state, &req, anyhow!(error));
942                    }
943                };
944            if manifest.platform.to_string() != platform {
945                return error_400(
946                    &state,
947                    &req,
948                    anyhow!(
949                        "Latest manifest platform does not match the requested platform"
950                    ),
951                );
952            }
953            let versioned_path = releases_dir.join(format!(
954                "ctb-{platform}-{}.json",
955                manifest.date.strftime("%Y%m%d-%H%M%S")
956            ));
957            let versioned_path = match files::symlink_is_in_dir(
958                &versioned_path,
959                &releases_dir,
960            ) {
961                Ok(path) => path,
962                Err(error) => return error_400(&state, &req, error),
963            };
964            let versioned_bytes = match tokio::fs::read(&versioned_path).await {
965                Ok(bytes) => bytes,
966                Err(error) => return error_400(&state, &req, anyhow!(error)),
967            };
968            if latest_bytes != versioned_bytes {
969                return error_400(
970                    &state,
971                    &req,
972                    anyhow!(
973                        "Copied latest manifest differs from its versioned manifest"
974                    ),
975                );
976            }
977            sig_path = versioned_path.with_extension("json.sig");
978        }
979    }
980    let sig_path = match files::symlink_is_in_dir(&sig_path, &releases_dir) {
981        Ok(path) => path,
982        Err(error) => return error_400(&state, &req, error),
983    };
984    serve_sig_file(&state, &req, &sig_path).await
985}
986
987/// GET /releases/{platform}/{version}.json.sig
988pub async fn get_manifest_sig_by_version(
989    State(state): State<AppState>,
990    req: RequestState,
991    Path((platform, version)): Path<(String, String)>,
992) -> Response {
993    let platform = platform.to_lowercase();
994    if !is_supported_release_platform(&platform) {
995        return error_400(&state, &req, anyhow!("Invalid platform"));
996    }
997
998    if version.contains("..") || version.contains('/') || version.contains('\\')
999    {
1000        return error_400(&state, &req, anyhow!("Invalid version string"));
1001    }
1002
1003    let releases_dir =
1004        match get_releases_dir(state.storage_dir_override.as_ref()) {
1005            Ok(d) => d,
1006            Err(e) => return error_400(&state, &req, e),
1007        };
1008
1009    let sig_path =
1010        releases_dir.join(format!("ctb-{platform}-{version}.json.sig"));
1011    serve_sig_file(&state, &req, &sig_path).await
1012}
1013
1014/// GET /releases/public-key.pem
1015pub async fn get_public_key_pem(
1016    State(state): State<AppState>,
1017    req: RequestState,
1018) -> Response {
1019    let Some(pubkey_b64) = get_str_setting(PcSettingStrKey::ReleasePublicKey)
1020    else {
1021        return error_404(
1022            &state,
1023            &req,
1024            "Release public key not configured".to_string(),
1025        );
1026    };
1027
1028    let pem = ed25519_base64_to_pem(&pubkey_b64);
1029
1030    let mut resp = Response::new(Body::from(pem));
1031    resp.headers_mut().insert(
1032        header::CONTENT_TYPE,
1033        HeaderValue::from_static("application/x-pem-file"),
1034    );
1035    resp
1036}
1037
1038/// Calculates download filesizes for the homepage based on latest manifests.
1039pub async fn calculate_download_sizes(
1040    storage_dir_override: Option<PathBuf>,
1041) -> std::collections::HashMap<String, String> {
1042    tokio::task::spawn_blocking(move || {
1043        let mut sizes = std::collections::HashMap::new();
1044
1045        let releases_dir = match get_releases_dir(storage_dir_override.as_ref())
1046        {
1047            Ok(d) => d,
1048            Err(_) => return sizes,
1049        };
1050
1051        for (platform_slug, key_prefix) in [
1052            ("linux-x64", "linux_x64"),
1053            ("linux-x86", "linux_x86"),
1054            ("windows-x64", "windows_x64"),
1055            ("freebsd-x64", "freebsd_x64"),
1056        ] {
1057            let manifest_path =
1058                releases_dir.join(format!("ctb-{platform_slug}-latest.json"));
1059            let Ok(content) = std::fs::read_to_string(&manifest_path) else {
1060                continue;
1061            };
1062            let Ok(manifest) = serde_json::from_str::<ReleaseManifest>(&content)
1063            else {
1064                continue;
1065            };
1066
1067            let installer_size = manifest.installer_file_size();
1068            if installer_size > 0 {
1069                sizes.insert(
1070                    format!("{key_prefix}_installer"),
1071                    ctb_utilities::string::bytes::format_bytes_decimal(
1072                        installer_size,
1073                    ),
1074                );
1075            }
1076            let expected_installer = manifest.platform.installer_binary_name();
1077            if let Some(installer_file) = manifest.files.iter().find(|f| {
1078                f.path == expected_installer || f.path == "ctoolbox-installer"
1079            }) {
1080                sizes.insert(
1081                    format!("{key_prefix}_installer_checksum"),
1082                    installer_file.checksum.clone(),
1083                );
1084            }
1085
1086            if let Ok(offline_size) = manifest.estimate_offline_tarball_size() {
1087                sizes.insert(
1088                    format!("{key_prefix}_offline"),
1089                    format!(
1090                        "approx. {}",
1091                        ctb_utilities::string::bytes::format_bytes_decimal(
1092                            offline_size
1093                        )
1094                    ),
1095                );
1096            }
1097
1098            if platform_slug == "linux-x64" {
1099                let build_info = ctb_build_info::build_info();
1100                let src_name = format!(
1101                    "ctoolbox-src-{}-{}.tar",
1102                    manifest.ctoolbox_version, build_info.commit
1103                );
1104                if let Ok(src_size) =
1105                    manifest.estimate_gzipped_file_size(&src_name)
1106                    && src_size > 0
1107                {
1108                    sizes.insert(
1109                        "src_tar_gz".to_string(),
1110                        format!(
1111                            "approx. {}",
1112                            ctb_utilities::string::bytes::format_bytes_decimal(
1113                                src_size
1114                            )
1115                        ),
1116                    );
1117                }
1118
1119                let dep_name = format!(
1120                    "ctoolbox-dependencies-{}-{}.tar",
1121                    manifest.ctoolbox_version, build_info.commit
1122                );
1123                if let Ok(dep_size) =
1124                    manifest.estimate_gzipped_file_size(&dep_name)
1125                    && dep_size > 0
1126                {
1127                    sizes.insert(
1128                        "dependencies_tar_gz".to_string(),
1129                        format!(
1130                            "approx. {}",
1131                            ctb_utilities::string::bytes::format_bytes_decimal(
1132                                dep_size
1133                            )
1134                        ),
1135                    );
1136                }
1137            }
1138        }
1139
1140        sizes
1141    })
1142    .await
1143    // Reason for fallback: tokio spawn_blocking join error defaults sizes map to empty HashMap
1144    .unwrap_or_default()
1145}
1146
1147#[cfg(test)]
1148#[allow(
1149    clippy::panic,
1150    clippy::expect_used,
1151    clippy::unwrap_used,
1152    clippy::unwrap_in_result,
1153    clippy::panic_in_result_fn,
1154    clippy::indexing_slicing,
1155    clippy::arithmetic_side_effects,
1156    reason = "Standard repository test boilerplate"
1157)]
1158mod tests {
1159    use super::*;
1160
1161    #[crate::ctb_test]
1162    fn test_is_valid_chunk_hash() {
1163        // Valid SHA-256 hash (64 hex chars)
1164        assert!(is_valid_chunk_hash(
1165            "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
1166        ));
1167
1168        // Too short
1169        assert!(!is_valid_chunk_hash("a1b2c3d4"));
1170
1171        // Too long
1172        assert!(!is_valid_chunk_hash(
1173            "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2a1b2"
1174        ));
1175
1176        // Invalid characters
1177        assert!(!is_valid_chunk_hash(
1178            "g1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
1179        ));
1180
1181        // Empty
1182        assert!(!is_valid_chunk_hash(""));
1183    }
1184
1185    #[crate::ctb_test]
1186    fn test_parse_range_header() {
1187        use axum::http::HeaderMap;
1188
1189        let mut headers = HeaderMap::new();
1190
1191        // No Range header
1192        assert_eq!(parse_range_header(&headers, 100), None);
1193
1194        // Invalid format
1195        headers.insert(header::RANGE, "bytes=invalid".parse().unwrap());
1196        assert_eq!(parse_range_header(&headers, 100), None);
1197
1198        // Valid full range from start
1199        headers.insert(header::RANGE, "bytes=0-".parse().unwrap());
1200        assert_eq!(parse_range_header(&headers, 100), Some((0, 100)));
1201
1202        // Valid mid range to end
1203        headers.insert(header::RANGE, "bytes=50-".parse().unwrap());
1204        assert_eq!(parse_range_header(&headers, 100), Some((50, 100)));
1205
1206        // Valid specific range
1207        headers.insert(header::RANGE, "bytes=10-49".parse().unwrap());
1208        assert_eq!(parse_range_header(&headers, 100), Some((10, 50)));
1209
1210        // Unsatisfiable range (start >= total_size)
1211        headers.insert(header::RANGE, "bytes=100-".parse().unwrap());
1212        assert_eq!(parse_range_header(&headers, 100), None);
1213
1214        // Unsatisfiable range (start >= end)
1215        headers.insert(header::RANGE, "bytes=50-40".parse().unwrap());
1216        assert_eq!(parse_range_header(&headers, 100), None);
1217    }
1218
1219    #[crate::ctb_test("tokio")]
1220    async fn test_get_latest_manifest_sig_fallback() {
1221        //bypass-tempdir-lint
1222        use crate::test_helpers::TestApp;
1223        use axum::http::{Method, StatusCode};
1224        use std::fs;
1225
1226        let test_app = TestApp::new();
1227        let releases_dir = test_app
1228            .state
1229            .storage_dir_override
1230            .as_ref()
1231            .unwrap()
1232            .join("releases");
1233        fs::create_dir_all(&releases_dir).unwrap();
1234
1235        // Create a dummy manifest file
1236        let manifest_filename = "ctb-linux-x64-20260617-120000.json";
1237        let manifest_path = releases_dir.join(manifest_filename);
1238        let manifest = serde_json::json!({
1239            "format_version": 1,
1240            "ctoolbox_version": "0.1.49",
1241            "platform": "linux-x64",
1242            "date": "2026-06-17T12:00:00Z",
1243            "signature": null,
1244            "revoked_key_ids": [],
1245            "files": [],
1246        });
1247        fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap())
1248            .unwrap();
1249
1250        // Create the corresponding signature file
1251        let sig_filename = "ctb-linux-x64-20260617-120000.json.sig";
1252        let sig_path = releases_dir.join(sig_filename);
1253        fs::write(&sig_path, "signature-bytes").unwrap();
1254
1255        // A copied manifest must resolve its signature without a latest .sig file.
1256        let latest_manifest_path =
1257            releases_dir.join("ctb-linux-x64-latest.json");
1258        fs::copy(&manifest_path, &latest_manifest_path).unwrap();
1259        assert!(!releases_dir.join("ctb-linux-x64-latest.json.sig").exists());
1260
1261        // Request latest.json.sig
1262        let resp = test_app
1263            .request_get_response::<()>(
1264                Method::GET,
1265                "/releases/linux-x64/latest.json.sig",
1266                None,
1267                None,
1268                None,
1269                None,
1270            )
1271            .await;
1272
1273        assert_eq!(resp.status(), StatusCode::OK);
1274        let body = crate::test_helpers::body_to_text(resp).await;
1275        assert_eq!(body, "signature-bytes");
1276
1277        fs::write(
1278            &latest_manifest_path,
1279            format!("{} ", serde_json::to_string(&manifest).unwrap()),
1280        )
1281        .unwrap();
1282        let resp = test_app
1283            .request_get_response::<()>(
1284                Method::GET,
1285                "/releases/linux-x64/latest.json.sig",
1286                None,
1287                None,
1288                None,
1289                None,
1290            )
1291            .await;
1292        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1293        assert!(
1294            crate::test_helpers::body_to_text(resp)
1295                .await
1296                .contains("differs from its versioned manifest")
1297        );
1298
1299        #[cfg(unix)]
1300        {
1301            fs::remove_file(&latest_manifest_path).unwrap();
1302            std::os::unix::fs::symlink(
1303                manifest_filename,
1304                &latest_manifest_path,
1305            )
1306            .unwrap();
1307            let resp = test_app
1308                .request_get_response::<()>(
1309                    Method::GET,
1310                    "/releases/linux-x64/latest.json.sig",
1311                    None,
1312                    None,
1313                    None,
1314                    None,
1315                )
1316                .await;
1317            assert_eq!(resp.status(), StatusCode::OK);
1318            assert_eq!(
1319                crate::test_helpers::body_to_text(resp).await,
1320                "signature-bytes"
1321            );
1322        }
1323    }
1324
1325    #[crate::ctb_test("tokio")]
1326    async fn test_offline_tarball_streaming_and_range_requests() {
1327        //bypass-tempdir-lint
1328        use crate::test_helpers::TestApp;
1329        use axum::http::{HeaderMap, Method, StatusCode};
1330        use std::fs;
1331
1332        let test_app = TestApp::new();
1333        let releases_dir = test_app
1334            .state
1335            .storage_dir_override
1336            .as_ref()
1337            .unwrap()
1338            .join("releases");
1339        fs::create_dir_all(&releases_dir).unwrap();
1340
1341        let chunks_dir = releases_dir.join("bh");
1342        fs::create_dir_all(&chunks_dir).unwrap();
1343
1344        // Write a mock manifest ctb-linux-x64-latest.json
1345        let manifest_content = r#"{
1346            "format_version": 1,
1347            "ctoolbox_version": "0.1.0",
1348            "platform": "linux-x64",
1349            "date": "2026-06-16T22:43:00Z",
1350            "revoked_key_ids": [],
1351            "files": []
1352        }"#;
1353
1354        fs::write(
1355            releases_dir.join("ctb-linux-x64-latest.json"),
1356            manifest_content,
1357        )
1358        .unwrap();
1359
1360        // 1. Request full tarball
1361        let resp = test_app
1362            .request_get_response::<()>(
1363                Method::GET,
1364                "/releases/linux-x64/latest.tar",
1365                None,
1366                None,
1367                None,
1368                None,
1369            )
1370            .await;
1371
1372        assert_eq!(resp.status(), StatusCode::OK);
1373        assert_eq!(
1374            resp.headers().get(header::CONTENT_TYPE).unwrap(),
1375            "application/x-tar"
1376        );
1377
1378        let full_body = crate::test_helpers::body_to_bytes(resp).await;
1379        assert!(full_body.len() > 1024); // Must have at least the directory header, manifest, and 1024 trailing null bytes
1380
1381        // Offline tarballs stream directly from bh/ chunks without saving a duplicate .tar file on disk
1382        let cache_file_path = releases_dir
1383            .join("downloads_cache")
1384            .join("ctoolbox-linux-x64-0.1.0.tar");
1385        assert!(!cache_file_path.exists());
1386
1387        // 2. Request range directly from streaming tarball
1388        let mut headers = HeaderMap::new();
1389        headers.insert(header::RANGE, "bytes=10-20".parse().unwrap());
1390
1391        let resp_range = test_app
1392            .request_get_response::<()>(
1393                Method::GET,
1394                "/releases/linux-x64/latest.tar",
1395                Some(headers),
1396                None,
1397                None,
1398                None,
1399            )
1400            .await;
1401
1402        assert_eq!(resp_range.status(), StatusCode::PARTIAL_CONTENT);
1403        assert_eq!(
1404            resp_range.headers().get(header::CONTENT_RANGE).unwrap(),
1405            &format!("bytes 10-20/{}", full_body.len())
1406        );
1407        assert_eq!(
1408            resp_range.headers().get(header::CONTENT_LENGTH).unwrap(),
1409            "11"
1410        );
1411
1412        let range_body = crate::test_helpers::body_to_bytes(resp_range).await;
1413        assert_eq!(range_body.len(), 11);
1414        assert_eq!(&range_body[..], &full_body[10..21]);
1415    }
1416}