ctb_io_webui/extractors/
request_state.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//! Shared request context and breadcrumb state extractors.
21
22use axum::extract::FromRequestParts;
23use http::StatusCode;
24use serde::Serialize;
25
26#[derive(Serialize, Clone, Debug, PartialEq)]
27pub struct BreadcrumbItem {
28    pub label: String,
29    pub url: Option<String>,
30}
31
32#[derive(Serialize, Clone)]
33pub struct RequestState {
34    pub route: String,
35    pub method: String,
36    pub accept: Option<String>,
37    pub is_js_request: bool,
38    pub is_embedded: bool,
39    pub breadcrumbs: Option<Vec<BreadcrumbItem>>,
40    pub logged_in_user: Option<String>,
41    pub back_url: Option<String>,
42}
43
44fn query_has_embed_flag(query: Option<&str>) -> bool {
45    query.is_some_and(|query| {
46        query.split('&').any(|pair| {
47            let mut parts = pair.splitn(2, '=');
48            // Reason for fallback: query pair without equals sign defaults key/value to empty string
49            let key = parts.next().unwrap_or_default();
50            // Reason for fallback: query pair without equals sign defaults key/value to empty string
51            let value = parts.next().unwrap_or_default();
52            key == "embed"
53                && (value == "1" || value.eq_ignore_ascii_case("true"))
54        })
55    })
56}
57
58pub fn generate_breadcrumbs(route: &str) -> Option<Vec<BreadcrumbItem>> {
59    if route.is_empty() || route == "/" {
60        return None;
61    }
62
63    if route == "/home" {
64        return Some(vec![BreadcrumbItem {
65            label: "Home".to_string(),
66            url: None,
67        }]);
68    }
69
70    if route == "/nodes" {
71        return Some(vec![
72            BreadcrumbItem {
73                label: "Home".to_string(),
74                url: Some("/home".to_string()),
75            },
76            BreadcrumbItem {
77                label: "Nodes".to_string(),
78                url: None,
79            },
80        ]);
81    }
82
83    if route == "/nodes/create" {
84        return Some(vec![
85            BreadcrumbItem {
86                label: "Home".to_string(),
87                url: Some("/home".to_string()),
88            },
89            BreadcrumbItem {
90                label: "Nodes".to_string(),
91                url: Some("/nodes".to_string()),
92            },
93            BreadcrumbItem {
94                label: "Create".to_string(),
95                url: None,
96            },
97        ]);
98    }
99
100    if route == "/nodes/upload" {
101        return Some(vec![
102            BreadcrumbItem {
103                label: "Home".to_string(),
104                url: Some("/home".to_string()),
105            },
106            BreadcrumbItem {
107                label: "Nodes".to_string(),
108                url: Some("/nodes".to_string()),
109            },
110            BreadcrumbItem {
111                label: "Upload".to_string(),
112                url: None,
113            },
114        ]);
115    }
116
117    if route == "/nodes/view" {
118        return Some(vec![
119            BreadcrumbItem {
120                label: "Home".to_string(),
121                url: Some("/home".to_string()),
122            },
123            BreadcrumbItem {
124                label: "Nodes".to_string(),
125                url: Some("/nodes".to_string()),
126            },
127            BreadcrumbItem {
128                label: "View".to_string(),
129                url: None,
130            },
131        ]);
132    }
133
134    if route == "/search" {
135        return Some(vec![
136            BreadcrumbItem {
137                label: "Home".to_string(),
138                url: Some("/home".to_string()),
139            },
140            BreadcrumbItem {
141                label: "Search".to_string(),
142                url: None,
143            },
144        ]);
145    }
146
147    if route == "/debug/db-tables" {
148        return Some(vec![
149            BreadcrumbItem {
150                label: "Home".to_string(),
151                url: Some("/home".to_string()),
152            },
153            BreadcrumbItem {
154                label: "Database Tables".to_string(),
155                url: None,
156            },
157        ]);
158    }
159
160    if let Some(table_name) = route.strip_prefix("/debug/db-tables/") {
161        if !table_name.is_empty() {
162            return Some(vec![
163                BreadcrumbItem {
164                    label: "Home".to_string(),
165                    url: Some("/home".to_string()),
166                },
167                BreadcrumbItem {
168                    label: "Database Tables".to_string(),
169                    url: Some("/debug/db-tables".to_string()),
170                },
171                BreadcrumbItem {
172                    label: table_name.to_string(),
173                    url: None,
174                },
175            ]);
176        }
177    }
178
179    if route == "/pc-settings" {
180        return Some(vec![
181            BreadcrumbItem {
182                label: "Home".to_string(),
183                url: Some("/home".to_string()),
184            },
185            BreadcrumbItem {
186                label: "Settings".to_string(),
187                url: None,
188            },
189        ]);
190    }
191
192    if route == "/home/subscribe" {
193        return Some(vec![
194            BreadcrumbItem {
195                label: "Home".to_string(),
196                url: Some("/home".to_string()),
197            },
198            BreadcrumbItem {
199                label: "Subscribe".to_string(),
200                url: None,
201            },
202        ]);
203    }
204
205    if route == "/privacy-policy" {
206        return Some(vec![
207            BreadcrumbItem {
208                label: "Home".to_string(),
209                url: Some("/home".to_string()),
210            },
211            BreadcrumbItem {
212                label: "Privacy Policy".to_string(),
213                url: None,
214            },
215        ]);
216    }
217
218    if route == "/login" {
219        return Some(vec![
220            BreadcrumbItem {
221                label: "Home".to_string(),
222                url: Some("/home".to_string()),
223            },
224            BreadcrumbItem {
225                label: "Login".to_string(),
226                url: None,
227            },
228        ]);
229    }
230
231    if route == "/registration" {
232        return Some(vec![
233            BreadcrumbItem {
234                label: "Home".to_string(),
235                url: Some("/home".to_string()),
236            },
237            BreadcrumbItem {
238                label: "Registration".to_string(),
239                url: None,
240            },
241        ]);
242    }
243
244    if route == "/newsletters" {
245        return Some(vec![
246            BreadcrumbItem {
247                label: "Home".to_string(),
248                url: Some("/home".to_string()),
249            },
250            BreadcrumbItem {
251                label: "Newsletters".to_string(),
252                url: None,
253            },
254        ]);
255    }
256
257    if let Some(date) = route.strip_prefix("/newsletters/") {
258        if !date.is_empty() {
259            return Some(vec![
260                BreadcrumbItem {
261                    label: "Home".to_string(),
262                    url: Some("/home".to_string()),
263                },
264                BreadcrumbItem {
265                    label: "Newsletters".to_string(),
266                    url: Some("/newsletters".to_string()),
267                },
268                BreadcrumbItem {
269                    label: date.to_string(),
270                    url: None,
271                },
272            ]);
273        }
274    }
275
276    if route == "/docs/LICENSE.md" {
277        return Some(vec![
278            BreadcrumbItem {
279                label: "Home".to_string(),
280                url: Some("/home".to_string()),
281            },
282            BreadcrumbItem {
283                label: "License".to_string(),
284                url: None,
285            },
286        ]);
287    }
288
289    if route == "/docs/TRADEMARKS.md" {
290        return Some(vec![
291            BreadcrumbItem {
292                label: "Home".to_string(),
293                url: Some("/home".to_string()),
294            },
295            BreadcrumbItem {
296                label: "Trademark Policy".to_string(),
297                url: None,
298            },
299        ]);
300    }
301
302    if route == "/docs/CHANGELOG.md" {
303        return Some(vec![
304            BreadcrumbItem {
305                label: "Home".to_string(),
306                url: Some("/home".to_string()),
307            },
308            BreadcrumbItem {
309                label: "Changelog".to_string(),
310                url: None,
311            },
312        ]);
313    }
314
315    if route == "/docs" {
316        return Some(vec![
317            BreadcrumbItem {
318                label: "Home".to_string(),
319                url: Some("/home".to_string()),
320            },
321            BreadcrumbItem {
322                label: "Documentation".to_string(),
323                url: None,
324            },
325        ]);
326    }
327
328    if let Some(doc_path) = route.strip_prefix("/docs/") {
329        if !doc_path.is_empty() {
330            let mut items = vec![
331                BreadcrumbItem {
332                    label: "Home".to_string(),
333                    url: Some("/home".to_string()),
334                },
335                BreadcrumbItem {
336                    label: "Documentation".to_string(),
337                    url: Some("/docs".to_string()),
338                },
339            ];
340            let parts: Vec<&str> =
341                doc_path.split('/').filter(|s| !s.is_empty()).collect();
342            let mut current_subpath = "/docs".to_string();
343            for part in &parts {
344                let part_clean = if part.to_ascii_lowercase().ends_with(".md") {
345                    // Reason for fallback: slice truncation safety on non-ASCII suffix defaults to empty string
346                    part.get(..part.len().saturating_sub(3)).unwrap_or("")
347                } else {
348                    *part
349                };
350
351                if part_clean.eq_ignore_ascii_case("index") {
352                    continue;
353                }
354
355                current_subpath.push('/');
356                current_subpath.push_str(part);
357                let label = format_segment_label(part_clean);
358                items.push(BreadcrumbItem {
359                    label,
360                    url: Some(current_subpath.clone()),
361                });
362            }
363            if let Some(last) = items.last_mut() {
364                last.url = None;
365            }
366            return Some(items);
367        }
368    }
369
370    None
371}
372
373fn format_segment_label(segment: &str) -> String {
374    let mut label = String::new();
375    let mut capitalize_next = true;
376    for c in segment.chars() {
377        if c == '-' || c == '_' {
378            label.push(' ');
379            capitalize_next = true;
380        } else if capitalize_next {
381            label.extend(c.to_uppercase());
382            capitalize_next = false;
383        } else {
384            label.push(c);
385        }
386    }
387    label
388}
389
390fn parse_relative_back_url(val: &str) -> Option<String> {
391    // Reason for fallback: url without query string separator retains original url string
392    let path_part = val.split('?').next().unwrap_or(val);
393    let bytes = path_part.as_bytes();
394    if path_part.starts_with('/')
395        && bytes.get(1) != Some(&b'/')
396        && bytes.get(1) != Some(&b'\\')
397    {
398        Some(val.to_string())
399    } else {
400        None
401    }
402}
403
404impl<S> FromRequestParts<S> for RequestState
405where
406    S: Send + Sync,
407{
408    type Rejection = StatusCode;
409    async fn from_request_parts(
410        parts: &mut axum::http::request::Parts,
411        _state: &S,
412    ) -> Result<Self, Self::Rejection> {
413        let is_embedded = query_has_embed_flag(parts.uri.query());
414        let route = parts.uri.path().to_string();
415        let breadcrumbs = if is_embedded {
416            None
417        } else {
418            generate_breadcrumbs(&route)
419        };
420
421        let session_key_bytes =
422            crate::session_auth::session_key_from_headers(&parts.headers);
423        let mut logged_in_user = None;
424        if let Some(session_key_bytes) = session_key_bytes {
425            use base64::Engine;
426            let token = base64::engine::general_purpose::URL_SAFE_NO_PAD
427                .encode(&session_key_bytes);
428            if let Ok(Some(user_id)) =
429                ctb_storage::user::validate_session(&token)
430            {
431                if let Some(public_info) =
432                    ctb_storage::user::UserPublicInfo::get_by_id(user_id)
433                {
434                    logged_in_user = Some(public_info.name().to_string());
435                }
436            }
437        }
438
439        let back_url = parts
440            .headers
441            .get("X-Back-Url")
442            .or_else(|| parts.headers.get(axum::http::header::REFERER))
443            .and_then(|v| v.to_str().ok())
444            .and_then(parse_relative_back_url);
445
446        Ok(RequestState {
447            route,
448            method: parts.method.to_string(),
449            accept: parts
450                .headers
451                .get(axum::http::header::ACCEPT)
452                .and_then(|v| v.to_str().ok())
453                .map(ToOwned::to_owned),
454            is_js_request: parts
455                .headers
456                .get("X-CollectiveToolbox-IsJsRequest")
457                .and_then(|v| v.to_str().ok())
458                .is_some_and(|s| s.eq_ignore_ascii_case("true")),
459            is_embedded,
460            breadcrumbs,
461            logged_in_user,
462            back_url,
463        })
464    }
465}
466
467#[cfg(test)]
468#[allow(
469    clippy::panic,
470    clippy::expect_used,
471    clippy::unwrap_used,
472    clippy::unwrap_in_result,
473    clippy::panic_in_result_fn,
474    clippy::indexing_slicing,
475    clippy::arithmetic_side_effects,
476    reason = "Standard repository test boilerplate"
477)]
478mod tests {
479    use super::*;
480
481    #[crate::ctb_test]
482    fn test_breadcrumbs_various_routes() {
483        let home = generate_breadcrumbs("/home").unwrap();
484        assert_eq!(home.len(), 1);
485        assert_eq!(home[0].label, "Home");
486        assert_eq!(home[0].url, None);
487
488        let privacy = generate_breadcrumbs("/privacy-policy").unwrap();
489        assert_eq!(privacy.len(), 2);
490        assert_eq!(privacy[0].label, "Home");
491        assert_eq!(privacy[0].url, Some("/home".to_string()));
492        assert_eq!(privacy[1].label, "Privacy Policy");
493        assert_eq!(privacy[1].url, None);
494
495        // 2. License and Trademark Policy special cases
496        let license = generate_breadcrumbs("/docs/LICENSE.md").unwrap();
497        assert_eq!(license.len(), 2);
498        assert_eq!(license[0].label, "Home");
499        assert_eq!(license[1].label, "License");
500        assert_eq!(license[1].url, None);
501
502        let trademark = generate_breadcrumbs("/docs/TRADEMARKS.md").unwrap();
503        assert_eq!(trademark.len(), 2);
504        assert_eq!(trademark[0].label, "Home");
505        assert_eq!(trademark[1].label, "Trademark Policy");
506        assert_eq!(trademark[1].url, None);
507
508        let changelog = generate_breadcrumbs("/docs/CHANGELOG.md").unwrap();
509        assert_eq!(changelog.len(), 2);
510        assert_eq!(changelog[0].label, "Home");
511        assert_eq!(changelog[1].label, "Changelog");
512        assert_eq!(changelog[1].url, None);
513
514        // 3. Regular documentation index
515        let docs = generate_breadcrumbs("/docs").unwrap();
516        assert_eq!(docs.len(), 2);
517        assert_eq!(docs[0].label, "Home");
518        assert_eq!(docs[1].label, "Documentation");
519        assert_eq!(docs[1].url, None);
520
521        // 4. index.md omission
522        let index_md = generate_breadcrumbs("/docs/index.md").unwrap();
523        assert_eq!(index_md.len(), 2);
524        assert_eq!(index_md[0].label, "Home");
525        assert_eq!(index_md[1].label, "Documentation");
526        assert_eq!(index_md[1].url, None);
527
528        // 5. Nested paths with and without .md
529        let nested_file =
530            generate_breadcrumbs("/docs/some-dir/some-file.md").unwrap();
531        assert_eq!(nested_file.len(), 4);
532        assert_eq!(nested_file[0].label, "Home");
533        assert_eq!(nested_file[1].label, "Documentation");
534        assert_eq!(nested_file[2].label, "Some Dir");
535        assert_eq!(nested_file[2].url, Some("/docs/some-dir".to_string()));
536        assert_eq!(nested_file[3].label, "Some File");
537        assert_eq!(nested_file[3].url, None);
538
539        let nested_index =
540            generate_breadcrumbs("/docs/some-dir/index.md").unwrap();
541        assert_eq!(nested_index.len(), 3);
542        assert_eq!(nested_index[0].label, "Home");
543        assert_eq!(nested_index[1].label, "Documentation");
544        assert_eq!(nested_index[2].label, "Some Dir");
545        assert_eq!(nested_index[2].url, None);
546    }
547
548    #[crate::ctb_test]
549    fn test_parse_relative_back_url() {
550        assert_eq!(
551            parse_relative_back_url("/search?q=test"),
552            Some("/search?q=test".to_string())
553        );
554        assert_eq!(
555            parse_relative_back_url("/search?q=a:b"),
556            Some("/search?q=a:b".to_string())
557        );
558        assert_eq!(parse_relative_back_url("/a:b"), Some("/a:b".to_string()));
559        assert_eq!(parse_relative_back_url("a:b"), None);
560        assert_eq!(parse_relative_back_url("//foo.com/"), None);
561        assert_eq!(parse_relative_back_url("/\\foo.com/"), None);
562        assert_eq!(parse_relative_back_url("http://localhost/nodes"), None);
563    }
564}