ctb_io_webui/controllers/
pc_settings.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 general app UI pages.
21
22use crate::flexible_form::FlexibleForm;
23use crate::json::maybe_value::{
24    MaybeOption, MaybeValue, bool_or_default, str_or_default, str_or_empty,
25    u16_or_empty,
26};
27use crate::json::patch::{bool_to_patch, string_to_patch, u16_string_to_patch};
28use axum::{extract::State, response::Response};
29use axum_typed_multipart::TryFromMultipart;
30use serde::{Deserialize, Serialize};
31use serde_json::{Map, Value};
32
33use crate::controllers::base::redirect_temporary;
34use crate::error::{WebErr, WebError, WebResult};
35use crate::extractors::request_state::RequestState;
36use crate::utilities::password::{Password, hash, verify};
37use crate::utilities::*;
38use crate::{AppState, error_400, error_403, respond_page};
39use crate::{debug_fmt, json_value};
40use ctb_build_info::build_info;
41use ctb_formats_ipaddr::get_regex_ipv4_ipv6_exact;
42use ctb_storage::user::UserPublicInfo;
43
44/// The first-run setup and public PC settings page. For multi-user systems,
45/// public servers, kiosks, etc. this should typically be locked down, but it
46/// needs to be available for long enough after install for the administrator to
47/// get the computer set up. FIXME: May not exactly be accurate? TBD.
48pub async fn get_public_pc_settings(
49    State(state): State<AppState>,
50    req: RequestState,
51) -> WebResult<Response> {
52    #[derive(Serialize, Debug)]
53    struct UserWithAdmin {
54        admin: bool,
55        local_id: u64,
56        username: String,
57        display_name: Option<Vec<u8>>,
58        picture: Option<Vec<u8>>,
59    }
60
61    let build_info = build_info();
62    // Reason for fallback: unreadable settings file defaults to default settings struct
63    let current_settings = pc_settings::PcSettings::load().unwrap_or_default();
64    let raw_settings = match pc_settings::PcSettings::load_raw_json() {
65        Ok(v) => v,
66        Err(_) => Value::Object(Map::new()),
67    };
68    let raw_obj = raw_settings.as_object();
69
70    let is_default_key = |key: &str| match raw_obj.and_then(|o| o.get(key)) {
71        None => true,
72        Some(v) => v.is_null(),
73    };
74
75    let all_users = UserPublicInfo::list_all().web_err(&state, &req)?;
76
77    debug_fmt!("All users: {all_users:#?}");
78
79    let current_admin_users: Vec<u64> = match &current_settings.admin_users {
80        MaybeOption::Value(v) => v.clone(),
81        MaybeOption::Missing | MaybeOption::Null => Vec::new(),
82    };
83
84    let users: Vec<UserWithAdmin> = all_users
85        .into_iter()
86        .map(|u| UserWithAdmin {
87            admin: current_admin_users.contains(&u.local_id()),
88            local_id: u.local_id(),
89            username: u.name().to_string(),
90            display_name: u.display_name().map(<[u8]>::to_vec),
91            picture: u.user_picture().map(<[u8]>::to_vec),
92        })
93        .collect();
94
95    // debug_fmt!("Rendering PC settings page with users: {users:#?}");
96
97    Ok(respond_page(
98        &state,
99        req,
100        "settings.pc-settings",
101        &json_value! ({
102            "show_users" => bool_or_default(&current_settings.show_users, pc_settings::DEFAULT_SHOW_USERS),
103            "show_users_default" => is_default_key("show_users"),
104            "allow_local_account_creation" => bool_or_default(&current_settings.allow_local_account_creation, pc_settings::DEFAULT_ALLOW_LOCAL_ACCOUNT_CREATION),
105            "allow_local_account_creation_default" => is_default_key("allow_local_account_creation"),
106            "bind_to_ip" => str_or_default(&current_settings.bind_to_ip, pc_settings::DEFAULT_BIND_TO_IP),
107            "bind_to_ip_default" => is_default_key("bind_to_ip"),
108            "bind_to_ip_regex" => get_regex_ipv4_ipv6_exact(),
109            "server_url" => str_or_default(&current_settings.server_url, pc_settings::DEFAULT_SERVER_URL),
110            "server_url_default" => is_default_key("server_url"),
111            "domain_name" => str_or_empty(&current_settings.domain_name),
112            "domain_name_default" => is_default_key("domain_name"),
113            // Reason for fallback: unconfigured fixed port option defaults string representation to empty
114            "fixed_http_port" => u16_or_empty(&current_settings.fixed_http_port).map(|p| p.to_string()).unwrap_or_default(),
115            "fixed_http_port_default" => is_default_key("fixed_http_port"),
116            // Reason for fallback: unconfigured fixed port option defaults string representation to empty
117            "fixed_https_port" => u16_or_empty(&current_settings.fixed_https_port).map(|p| p.to_string()).unwrap_or_default(),
118            "fixed_https_port_default" => is_default_key("fixed_https_port"),
119            "http_redirect" => bool_or_default(&current_settings.http_redirect, pc_settings::DEFAULT_HTTP_REDIRECT),
120            "http_redirect_default" => is_default_key("http_redirect"),
121            "redirect_www_to_non_www" => bool_or_default(&current_settings.redirect_www_to_non_www, pc_settings::DEFAULT_REDIRECT_WWW_TO_NON_WWW),
122            "redirect_www_to_non_www_default" => is_default_key("redirect_www_to_non_www"),
123            "tls_certificate" => str_or_empty(&current_settings.tls_certificate),
124            "tls_certificate_default" => is_default_key("tls_certificate"),
125            "tls_client_verification_cert" => {
126                str_or_empty(&current_settings.tls_client_verification_cert)
127            },
128            "tls_client_verification_cert_default" => {
129                is_default_key("tls_client_verification_cert")
130            },
131            "dev_signing_public_key" => str_or_empty(&current_settings.dev_signing_public_key),
132            "dev_signing_public_key_default" => is_default_key("dev_signing_public_key"),
133            "release_public_key" => str_or_empty(&current_settings.release_public_key),
134            "release_public_key_default" => is_default_key("release_public_key"),
135            "serve_public_web_site_only" => bool_or_default(&current_settings.serve_public_web_site_only, pc_settings::DEFAULT_SERVE_PUBLIC_WEB_SITE_ONLY),
136            "serve_public_web_site_only_default" => is_default_key("serve_public_web_site_only"),
137            "log_stack_file" => bool_or_default(&current_settings.log_stack_file, pc_settings::DEFAULT_LOG_STACK_FILE),
138            "log_stack_file_default" => is_default_key("log_stack_file"),
139            "access_log_mode_off" => current_settings.get_access_log_mode() == pc_settings::AccessLogMode::Off,
140            "access_log_mode_errors" => current_settings.get_access_log_mode() == pc_settings::AccessLogMode::Errors,
141            "access_log_mode_on" => current_settings.get_access_log_mode() == pc_settings::AccessLogMode::On,
142            "access_log_mode_default" => is_default_key("access_log_mode"),
143
144            // Feature flags
145            "feature_login" => bool_or_default(&current_settings.feature_login, pc_settings::DEFAULT_FEATURE_LOGIN),
146            "feature_registration" => bool_or_default(&current_settings.feature_registration, pc_settings::DEFAULT_FEATURE_REGISTRATION),
147            "feature_provide_sync_server" => bool_or_default(&current_settings.feature_provide_sync_server, pc_settings::DEFAULT_FEATURE_PROVIDE_SYNC_SERVER),
148            "feature_login_default" => is_default_key("feature_login"),
149            "feature_registration_default" => {
150                is_default_key("feature_registration")
151            },
152            "feature_provide_sync_server_default" => is_default_key("feature_provide_sync_server"),
153
154            // Secrets not shown, just whether they are set
155            "tls_private_key_set" => matches!(current_settings.tls_private_key, MaybeOption::Value(_)),
156            "tls_private_key_default" => is_default_key("tls_private_key"),
157            "dev_signing_private_key_set" => matches!(current_settings.dev_signing_private_key, MaybeOption::Value(_)),
158            "dev_signing_private_key_default" => is_default_key("dev_signing_private_key"),
159            "admin_password_set" => matches!(current_settings.admin_password_hash, MaybeOption::Value(_)),
160
161            // All users, for building list
162            "users" => users,
163
164            // Provide build info for display
165            "official_application_name" => crate::utilities::branding::official_application_name(),
166            "crate_name" => build_info.name,
167            "crate_version" => build_info.version,
168            "build_date" => build_info.build_date,
169            "commit" => build_info.commit
170        }),
171    ))
172}
173
174#[derive(TryFromMultipart, Serialize, Deserialize)]
175#[expect(
176    clippy::similar_names,
177    reason = "settings form fields have similar names by design"
178)]
179#[try_from_multipart(strict)]
180pub struct PcSettingsForm {
181    show_users: Option<bool>,
182    show_users_default: Option<bool>,
183    allow_local_account_creation: Option<bool>,
184    allow_local_account_creation_default: Option<bool>,
185    bind_to_ip: Option<String>,
186    bind_to_ip_default: Option<bool>,
187    server_url: Option<String>,
188    server_url_default: Option<bool>,
189    domain_name: Option<String>,
190    domain_name_default: Option<bool>,
191    fixed_http_port: Option<String>,
192    fixed_http_port_default: Option<bool>,
193    fixed_https_port: Option<String>,
194    fixed_https_port_default: Option<bool>,
195    http_redirect: Option<bool>,
196    http_redirect_default: Option<bool>,
197    redirect_www_to_non_www: Option<bool>,
198    redirect_www_to_non_www_default: Option<bool>,
199    tls_certificate: Option<String>,
200    tls_certificate_default: Option<bool>,
201    tls_private_key: Option<String>,
202    tls_private_key_default: Option<bool>,
203    tls_client_verification_cert: Option<String>,
204    tls_client_verification_cert_default: Option<bool>,
205    dev_signing_public_key: Option<String>,
206    dev_signing_public_key_default: Option<bool>,
207    dev_signing_private_key: Option<String>,
208    dev_signing_private_key_default: Option<bool>,
209    release_public_key: Option<String>,
210    release_public_key_default: Option<bool>,
211    #[serde(default)]
212    // I guess since it's a Vec, "empty" vs "omitted" can't really be distinguished with the way it gets serialized in the request
213    admin_users: Vec<u64>,
214    admin_password: Option<String>,
215    serve_public_web_site_only: Option<bool>,
216    serve_public_web_site_only_default: Option<bool>,
217    log_stack_file: Option<bool>,
218    log_stack_file_default: Option<bool>,
219    feature_login: Option<bool>,
220    feature_login_default: Option<bool>,
221    feature_registration: Option<bool>,
222    feature_registration_default: Option<bool>,
223    feature_provide_sync_server: Option<bool>,
224    feature_provide_sync_server_default: Option<bool>,
225    access_log_mode: Option<String>,
226    access_log_mode_default: Option<bool>,
227}
228
229#[expect(
230    clippy::too_many_lines,
231    clippy::similar_names,
232    reason = "form processing is naturally long and references similar names"
233)]
234pub async fn post_public_pc_settings(
235    State(state): State<AppState>,
236    headers: axum::http::HeaderMap,
237    req: RequestState,
238    form: FlexibleForm<PcSettingsForm>,
239) -> WebResult<Response> {
240    let PcSettingsForm {
241        show_users,
242        show_users_default,
243        allow_local_account_creation,
244        allow_local_account_creation_default,
245        bind_to_ip,
246        bind_to_ip_default,
247        server_url,
248        server_url_default,
249        domain_name,
250        domain_name_default,
251        fixed_http_port: fixed_http_port_str,
252        fixed_http_port_default,
253        fixed_https_port: fixed_https_port_str,
254        fixed_https_port_default,
255        http_redirect,
256        http_redirect_default,
257        redirect_www_to_non_www,
258        redirect_www_to_non_www_default,
259        tls_certificate,
260        tls_certificate_default,
261        tls_private_key,
262        tls_private_key_default,
263        tls_client_verification_cert,
264        tls_client_verification_cert_default,
265        dev_signing_public_key,
266        dev_signing_public_key_default,
267        dev_signing_private_key,
268        dev_signing_private_key_default,
269        release_public_key,
270        release_public_key_default,
271        admin_users,
272        admin_password,
273        serve_public_web_site_only,
274        serve_public_web_site_only_default,
275        log_stack_file,
276        log_stack_file_default,
277        feature_login,
278        feature_login_default,
279        feature_registration,
280        feature_registration_default,
281        feature_provide_sync_server,
282        feature_provide_sync_server_default,
283        access_log_mode,
284        access_log_mode_default,
285    } = form.0;
286
287    let admin_password: Option<Password> = admin_password
288        .map(|admin_password| Password::from_string(&admin_password));
289
290    // Reason for fallback: unreadable settings file defaults to default settings struct
291    let current_settings = pc_settings::PcSettings::load().unwrap_or_default();
292
293    let current_admin_users: Vec<u64> = match &current_settings.admin_users {
294        MaybeOption::Value(v) => v.clone(),
295        MaybeOption::Missing | MaybeOption::Null => Vec::new(),
296    };
297
298    if !current_admin_users.is_empty() {
299        let session_key_bytes =
300            crate::session_auth::session_key_from_headers(&headers);
301        let mut user_id = None;
302        if let Some(key) = session_key_bytes {
303            if let Some(user_mutex) =
304                crate::session_auth::Session::get_user_by_key(
305                    &mut state.clone(),
306                    &key,
307                )
308                .await
309            {
310                user_id = Some(user_mutex.lock().await.local_id());
311            }
312        }
313        let is_admin =
314            user_id.is_some_and(|id| current_admin_users.contains(&id));
315        if !is_admin {
316            return Ok(error_403(
317                &state,
318                &req,
319                "Must be logged in as an admin user to change settings"
320                    .to_string(),
321            ));
322        }
323    }
324
325    let current_pass_hash = match &current_settings.admin_password_hash {
326        MaybeOption::Value(s) => Some(s.as_str()),
327        MaybeOption::Missing | MaybeOption::Null => None,
328    };
329
330    // If an admin password is set, require it
331    if let Some(current_pass_hash) = current_pass_hash {
332        let Some(provided) = admin_password.as_ref() else {
333            return Ok(error_403(
334                &state,
335                &req,
336                "Invalid admin password".to_string(),
337            ));
338        };
339
340        let ok = verify(provided, current_pass_hash)
341            .map_err(|e| WebError::new(e, state.clone(), req.clone()))?;
342
343        if !ok {
344            return Ok(error_403(
345                &state,
346                &req,
347                "Invalid admin password".to_string(),
348            ));
349        }
350    }
351
352    // If no admin password is set and one is provided, hash it and save it.
353    // If a password is already set, do not modify it here.
354    let admin_password_hash =
355        if current_pass_hash.is_none() {
356            if let Some(provided) = admin_password {
357                Some(hash(&provided).map_err(|e| {
358                    WebError::new(e, state.clone(), req.clone())
359                })?)
360            } else {
361                None
362            }
363        } else {
364            None
365        };
366
367    // Reason for fallback: unselected checkbox form input defaults boolean state to false
368    let checkbox_is_checked = |v: Option<bool>| v.unwrap_or(false);
369
370    let show_users =
371        bool_to_patch(checkbox_is_checked(show_users_default), show_users);
372
373    let allow_local_account_creation = bool_to_patch(
374        checkbox_is_checked(allow_local_account_creation_default),
375        allow_local_account_creation,
376    );
377
378    let http_redirect = bool_to_patch(
379        checkbox_is_checked(http_redirect_default),
380        http_redirect,
381    );
382
383    let redirect_www_to_non_www = bool_to_patch(
384        checkbox_is_checked(redirect_www_to_non_www_default),
385        redirect_www_to_non_www,
386    );
387
388    let serve_public_web_site_only = bool_to_patch(
389        checkbox_is_checked(serve_public_web_site_only_default),
390        serve_public_web_site_only,
391    );
392
393    let log_stack_file = bool_to_patch(
394        checkbox_is_checked(log_stack_file_default),
395        log_stack_file,
396    );
397
398    let feature_login = bool_to_patch(
399        checkbox_is_checked(feature_login_default),
400        feature_login,
401    );
402
403    let feature_registration = bool_to_patch(
404        checkbox_is_checked(feature_registration_default),
405        feature_registration,
406    );
407
408    let feature_provide_sync_server = bool_to_patch(
409        checkbox_is_checked(feature_provide_sync_server_default),
410        feature_provide_sync_server,
411    );
412
413    let access_log_mode = if checkbox_is_checked(access_log_mode_default) {
414        MaybeValue::Missing
415    } else {
416        match access_log_mode.as_deref() {
417            Some("off") => MaybeValue::Value(pc_settings::AccessLogMode::Off),
418            Some("errors") => {
419                MaybeValue::Value(pc_settings::AccessLogMode::Errors)
420            }
421            Some("on") => MaybeValue::Value(pc_settings::AccessLogMode::On),
422            _ => MaybeValue::Missing,
423        }
424    };
425
426    let bind_to_ip =
427        string_to_patch(checkbox_is_checked(bind_to_ip_default), bind_to_ip);
428
429    let target_bind_to_ip = match &bind_to_ip {
430        MaybeValue::Value(s) => s.as_str(),
431        MaybeValue::Missing => pc_settings::DEFAULT_BIND_TO_IP,
432    };
433    // Reason for fallback: invalid IP address string format evaluates bind address check as specified
434    let is_target_zero =
435        ctb_formats_ipaddr::is_unspecified(target_bind_to_ip).unwrap_or(false);
436    if is_target_zero {
437        let has_pass =
438            current_pass_hash.is_some() || admin_password_hash.is_some();
439        if !has_pass {
440            return Ok(error_400(
441                &state,
442                &req,
443                "Cannot bind to unspecified address (such as 0.0.0.0) without an admin password",
444            ));
445        }
446    }
447
448    let server_url =
449        string_to_patch(checkbox_is_checked(server_url_default), server_url);
450    let domain_name: Option<String> = if let Some(domain) = domain_name {
451        pc_settings::normalize_ctb_domain_name(&domain).ok()
452    } else {
453        None
454    };
455
456    let domain_name =
457        string_to_patch(checkbox_is_checked(domain_name_default), domain_name);
458
459    let Ok(fixed_http_port_patch) = u16_string_to_patch(
460        checkbox_is_checked(fixed_http_port_default),
461        fixed_http_port_str,
462    ) else {
463        return Ok(error_400(&state, &req, "Invalid fixed HTTP port"));
464    };
465
466    let Ok(fixed_https_port_patch) = u16_string_to_patch(
467        checkbox_is_checked(fixed_https_port_default),
468        fixed_https_port_str,
469    ) else {
470        return Ok(error_400(&state, &req, "Invalid fixed HTTPS port"));
471    };
472
473    // TLS: empty textarea clears for certs, but does not clear private key.
474    let tls_certificate = if checkbox_is_checked(tls_certificate_default) {
475        MaybeOption::Missing
476    } else if let Some(v) = tls_certificate {
477        if v.trim().is_empty() {
478            MaybeOption::Null
479        } else {
480            MaybeOption::Value(v)
481        }
482    } else {
483        MaybeOption::Missing
484    };
485
486    let tls_private_key = if checkbox_is_checked(tls_private_key_default) {
487        MaybeOption::Missing
488    } else if let Some(v) = tls_private_key {
489        if v.trim().is_empty() {
490            MaybeOption::Missing
491        } else {
492            MaybeOption::Value(v)
493        }
494    } else {
495        MaybeOption::Missing
496    };
497
498    let tls_client_verification_cert =
499        if checkbox_is_checked(tls_client_verification_cert_default) {
500            MaybeOption::Missing
501        } else if let Some(v) = tls_client_verification_cert {
502            if v.trim().is_empty() {
503                MaybeOption::Null
504            } else {
505                MaybeOption::Value(v)
506            }
507        } else {
508            MaybeOption::Missing
509        };
510
511    let dev_signing_public_key =
512        if checkbox_is_checked(dev_signing_public_key_default) {
513            MaybeOption::Missing
514        } else if let Some(v) = dev_signing_public_key {
515            if v.trim().is_empty() {
516                MaybeOption::Null
517            } else {
518                MaybeOption::Value(v)
519            }
520        } else {
521            MaybeOption::Missing
522        };
523
524    let dev_signing_private_key =
525        if checkbox_is_checked(dev_signing_private_key_default) {
526            MaybeOption::Missing
527        } else if let Some(v) = dev_signing_private_key {
528            if v.trim().is_empty() {
529                MaybeOption::Missing
530            } else {
531                MaybeOption::Value(v)
532            }
533        } else {
534            MaybeOption::Missing
535        };
536
537    let release_public_key = if checkbox_is_checked(release_public_key_default)
538    {
539        MaybeOption::Missing
540    } else if let Some(v) = release_public_key {
541        if v.trim().is_empty() {
542            MaybeOption::Null
543        } else {
544            MaybeOption::Value(v)
545        }
546    } else {
547        MaybeOption::Missing
548    };
549
550    let admin_users = if admin_users.is_empty() {
551        let current_admin_users: Vec<u64> = match &current_settings.admin_users
552        {
553            MaybeOption::Value(v) => v.clone(),
554            MaybeOption::Missing | MaybeOption::Null => Vec::new(),
555        };
556        if current_admin_users.is_empty() {
557            MaybeOption::Missing
558        } else {
559            MaybeOption::Null
560        }
561    } else {
562        MaybeOption::Value(admin_users)
563    };
564
565    let admin_password_hash = match admin_password_hash {
566        Some(hash) => MaybeOption::Value(hash),
567        None => MaybeOption::Missing,
568    };
569
570    let patch = pc_settings::PcSettings {
571        show_users,
572        bind_to_ip,
573        server_url,
574        domain_name,
575        fixed_http_port: fixed_http_port_patch,
576        fixed_https_port: fixed_https_port_patch,
577        http_redirect,
578        redirect_www_to_non_www,
579        tls_certificate,
580        tls_private_key,
581        tls_client_verification_cert,
582        dev_signing_public_key,
583        dev_signing_private_key,
584        release_public_key,
585        admin_users,
586        admin_password_hash,
587        serve_public_web_site_only,
588        log_stack_file,
589        allow_local_account_creation,
590        feature_login,
591        feature_registration,
592        feature_provide_sync_server,
593        access_log_mode,
594        ..Default::default()
595    };
596
597    pc_settings::PcSettings::apply_patch(patch).web_err(&state, &req)?;
598    Ok(redirect_temporary(req.is_js_request, "/pc-settings"))
599}
600
601#[cfg(test)]
602#[allow(
603    clippy::panic,
604    clippy::expect_used,
605    clippy::unwrap_used,
606    clippy::unwrap_in_result,
607    clippy::panic_in_result_fn,
608    clippy::indexing_slicing,
609    clippy::arithmetic_side_effects,
610    reason = "Standard repository test boilerplate"
611)]
612mod tests {
613
614    use crate::pc_settings::PcSettings;
615    use crate::test_helpers::{
616        assert_body_contains, assert_body_not_contains,
617        assert_eq_or_print_body, test_get_no_login, test_post_no_login,
618    };
619    use ctb_storage::user::{UserPublicInfo, get_test_user};
620    use ctb_utilities::json::maybe_value::{MaybeOption, MaybeValue};
621
622    #[crate::ctb_test("tokio")]
623    async fn can_get_pc_settings() {
624        let test_user_1 =
625            get_test_user(format!("{}_1", function_name!()).as_str());
626        let test_user_2 =
627            get_test_user(format!("{}_2", function_name!()).as_str());
628        let test_user_3 =
629            get_test_user(format!("{}_3", function_name!()).as_str());
630
631        let old_settings = PcSettings::load().unwrap();
632
633        // Set known settings
634        let settings = PcSettings {
635            show_users: MaybeValue::Value(true),
636            bind_to_ip: MaybeValue::Value("123.456.789".to_string()),
637            domain_name: MaybeOption::Value("foo.com".to_string()),
638            fixed_http_port: MaybeOption::Value(1234),
639            fixed_https_port: MaybeOption::Value(4567),
640            admin_users: MaybeOption::Value(vec![
641                test_user_1.local_id(),
642                test_user_3.local_id(),
643            ]),
644            ..Default::default()
645        };
646        settings.save().unwrap();
647
648        let (status, body) = test_get_no_login("/pc-settings").await;
649        assert_eq_or_print_body(status, 200, &body);
650        assert_body_contains(
651            "These options apply to all users on this computer",
652            &body,
653        );
654        // Check that the form contains the current values
655        assert_body_contains("value=\"foo.com\"", &body);
656        assert_body_contains("value=\"1234\"", &body);
657        assert_body_contains(
658            &format!("value=\"{}\"  checked", test_user_1.local_id()),
659            &body,
660        );
661        assert_body_not_contains(
662            &format!("value=\"{}\"  checked", test_user_2.local_id()),
663            &body,
664        );
665        assert_body_contains(
666            &format!("value=\"{}\"  checked", test_user_3.local_id()),
667            &body,
668        );
669        // assert_body_contains("checked", &body); // show_users checked
670
671        old_settings.save().unwrap();
672    }
673
674    #[crate::ctb_test("tokio")]
675    async fn can_save_settings_and_read_back() {
676        struct SettingsRestoreGuard(PcSettings);
677        impl Drop for SettingsRestoreGuard {
678            fn drop(&mut self) {
679                self.0.save().unwrap();
680            }
681        }
682
683        let old_settings = PcSettings::load().unwrap();
684        let _guard = SettingsRestoreGuard(old_settings.clone());
685
686        // Ensure no admin users are set first
687        let clear_settings = PcSettings {
688            admin_users: MaybeOption::Missing,
689            ..old_settings.clone()
690        };
691        clear_settings.save().unwrap();
692
693        // Prepare form data
694        #[derive(serde::Serialize)]
695        struct Form {
696            show_users: bool,
697            bind_to_ip: Option<String>,
698            domain_name: Option<String>,
699            fixed_http_port: Option<String>,
700            fixed_https_port: Option<String>,
701            admin_users: Vec<u64>,
702            feature_login: bool,
703            access_log_mode: Option<String>,
704        }
705        let form = Form {
706            show_users: false,
707            bind_to_ip: Some("127.0.0.1".to_string()),
708            domain_name: Some("example.com".to_string()),
709            fixed_http_port: Some("5678".to_string()),
710            fixed_https_port: Some("5679".to_string()),
711            admin_users: vec![18, 19],
712            feature_login: true,
713            access_log_mode: Some("on".to_string()),
714        };
715
716        let (status, body) =
717            test_post_no_login("/pc-settings", None, Some(&form), None).await;
718        assert_eq_or_print_body(status, 303, &body); // Should redirect
719
720        // Now load settings and check values
721        let loaded = PcSettings::load().unwrap();
722        assert_eq!(loaded.show_users, MaybeValue::Value(false));
723        assert_eq!(
724            loaded.bind_to_ip,
725            MaybeValue::Value("127.0.0.1".to_string())
726        );
727        assert_eq!(
728            loaded.domain_name,
729            MaybeOption::Value("example.com".to_string())
730        );
731        assert_eq!(loaded.fixed_http_port, MaybeOption::Value(5678));
732        assert_eq!(loaded.fixed_https_port, MaybeOption::Value(5679));
733        assert_eq!(loaded.admin_users, MaybeOption::Value(vec![18, 19]));
734        assert_eq!(loaded.feature_login, MaybeValue::Value(true));
735        assert_eq!(
736            loaded.access_log_mode,
737            MaybeValue::Value(crate::pc_settings::AccessLogMode::On)
738        );
739
740        // Clear admin_users before the second POST so it doesn't fail due to lack of login
741        let mut reset_settings = PcSettings::load().unwrap();
742        reset_settings.admin_users = MaybeOption::Missing;
743        reset_settings.save().unwrap();
744
745        // Test same values with multipart upload (just make sure it returns 303)
746        let (status, body) =
747            test_post_no_login("/pc-settings", None, None, Some(&form)).await;
748        assert_eq_or_print_body(status, 303, &body); // Should redirect
749    }
750
751    #[crate::ctb_test("tokio")]
752    async fn pc_settings_roundtrip_does_not_write_bogus_nulls() {
753        struct SettingsRestoreGuard(PcSettings);
754        impl Drop for SettingsRestoreGuard {
755            fn drop(&mut self) {
756                self.0.save().unwrap();
757            }
758        }
759
760        let old_settings = PcSettings::load().unwrap();
761        let _guard = SettingsRestoreGuard(old_settings.clone());
762
763        // Ensure no admin users are set first
764        let clear_settings = PcSettings {
765            admin_users: MaybeOption::Missing,
766            ..old_settings.clone()
767        };
768        clear_settings.save().unwrap();
769
770        // Simulate a browser submission where many "use default" checkboxes
771        // are checked because the keys are absent in the raw JSON.
772        #[derive(serde::Serialize)]
773        #[expect(
774            clippy::struct_excessive_bools,
775            reason = "test form data mock structure"
776        )]
777        struct Form {
778            // Intentionally set
779            tls_certificate: Option<String>,
780            admin_password: Option<String>,
781            feature_registration: bool,
782
783            // Defaults checked (historically caused JSON `null` entries)
784            domain_name_default: bool,
785            fixed_http_port_default: bool,
786            fixed_https_port_default: bool,
787            tls_private_key_default: bool,
788            tls_client_verification_cert_default: bool,
789
790            // This is not editable right now (IPC disabled), but the form type
791            // includes it and it used to get persisted as `[]`.
792            admin_users: Vec<u64>,
793        }
794
795        let form = Form {
796            tls_certificate: Some("test".to_string()),
797            admin_password: Some("password123".to_string()),
798            feature_registration: false,
799
800            domain_name_default: true,
801            fixed_http_port_default: true,
802            fixed_https_port_default: true,
803            tls_private_key_default: true,
804            tls_client_verification_cert_default: true,
805
806            admin_users: Vec::new(),
807        };
808
809        let (status, body) =
810            test_post_no_login("/pc-settings", None, Some(&form), None).await;
811        assert_eq_or_print_body(status, 303, &body);
812
813        let raw = PcSettings::load_raw_json().unwrap();
814        let obj = raw.as_object().unwrap();
815
816        // Should not create keys for defaulted/untouched fields.
817        assert!(!obj.contains_key("domain_name"));
818        assert!(!obj.contains_key("fixed_http_port"));
819        assert!(!obj.contains_key("fixed_https_port"));
820        assert!(!obj.contains_key("tls_private_key"));
821        assert!(!obj.contains_key("tls_client_verification_cert"));
822        assert!(!obj.contains_key("admin_users"));
823
824        // Should persist the intentionally set fields.
825        assert_eq!(
826            obj.get("tls_certificate"),
827            Some(&serde_json::Value::String("test".to_string()))
828        );
829        assert_eq!(
830            obj.get("feature_registration"),
831            Some(&serde_json::Value::Bool(false))
832        );
833        assert!(
834            obj.get("admin_password_hash")
835                .and_then(|v| v.as_str())
836                .is_some()
837        );
838
839        // Test same values with multipart upload (just make sure it returns 303)
840        let (status, body) =
841            test_post_no_login("/pc-settings", None, None, Some(&form)).await;
842        assert_eq_or_print_body(status, 303, &body);
843    }
844
845    #[crate::ctb_test("tokio")]
846    async fn post_refuses_saving_zero_ip_without_password() {
847        let old_settings = PcSettings::load().unwrap();
848
849        // Clear password first
850        let clear_settings = PcSettings {
851            admin_password_hash: MaybeOption::Null,
852            ..old_settings.clone()
853        };
854        clear_settings.save().unwrap();
855
856        #[derive(serde::Serialize)]
857        struct Form {
858            bind_to_ip: Option<String>,
859            admin_password: Option<String>,
860        }
861
862        let form = Form {
863            bind_to_ip: Some("0.0.0.0".to_string()),
864            admin_password: None,
865        };
866
867        // Submit form. Since we have bind_to_ip = "0.0.0.0" and no password, it should fail with 400.
868        let (status, body) =
869            test_post_no_login("/pc-settings", None, Some(&form), None).await;
870        assert_eq_or_print_body(status, 400, &body);
871        assert_body_contains(
872            "Cannot bind to unspecified address (such as 0.0.0.0) without an admin password",
873            &body,
874        );
875
876        old_settings.save().unwrap();
877    }
878
879    #[crate::ctb_test("tokio")]
880    async fn admin_users_restrictions() {
881        use crate::test_helpers::TestApp;
882        use http::Method;
883
884        struct SettingsRestoreGuard(PcSettings);
885        impl Drop for SettingsRestoreGuard {
886            fn drop(&mut self) {
887                self.0.save().unwrap();
888            }
889        }
890
891        let old_settings = PcSettings::load().unwrap();
892        let _guard = SettingsRestoreGuard(old_settings.clone());
893
894        // Ensure no admin users are set first
895        let clear_settings = PcSettings {
896            admin_users: MaybeOption::Null,
897            ..old_settings.clone()
898        };
899        clear_settings.save().unwrap();
900
901        let test_app = TestApp::new();
902
903        // 1. Register and login admin_user first to get their actual local ID
904        let admin_username = format!("{}_admin", function_name!());
905        let (admin_cookie, _admin_lock) =
906            test_app.register_and_login(&admin_username).await.unwrap();
907
908        // Look up the logged-in user's ID
909        let admin_user_info = UserPublicInfo::get_by_name(&admin_username)
910            .unwrap()
911            .unwrap();
912        let admin_user_id = admin_user_info.local_id();
913
914        // Register and login non_admin_user
915        let non_admin_username = format!("{}_non_admin", function_name!());
916        let (non_admin_cookie, _non_admin_lock) = test_app
917            .register_and_login(&non_admin_username)
918            .await
919            .unwrap();
920
921        // Prepare a form to submit
922        #[derive(serde::Serialize)]
923        struct Form {
924            show_users: bool,
925            admin_users: Vec<u64>,
926        }
927        let form_to_submit = Form {
928            show_users: true,
929            admin_users: vec![admin_user_id],
930        };
931
932        // Without admin users set, posting without login should succeed (redirects to /pc-settings)
933        let (status, body) = test_post_no_login(
934            "/pc-settings",
935            None,
936            Some(&form_to_submit),
937            None,
938        )
939        .await;
940        assert_eq_or_print_body(status, 303, &body);
941
942        // Now admin_user is in settings.admin_users
943        let loaded = PcSettings::load().unwrap();
944        assert_eq!(loaded.admin_users, MaybeOption::Value(vec![admin_user_id]));
945
946        // With admin users set:
947        // A. POST without login should fail with 403
948        let (status, body) = test_post_no_login(
949            "/pc-settings",
950            None,
951            Some(&form_to_submit),
952            None,
953        )
954        .await;
955        assert_eq_or_print_body(status, 403, &body);
956        assert_body_contains(
957            "Must be logged in as an admin user to change settings",
958            &body,
959        );
960
961        // B. POST with non_admin_user logged in should fail with 403
962        let (status, body) = test_app
963            .request(
964                Method::POST,
965                "/pc-settings",
966                None,
967                Some(&non_admin_cookie),
968                None,
969                Some(&form_to_submit),
970            )
971            .await;
972        assert_eq_or_print_body(status, 403, &body);
973        assert_body_contains(
974            "Must be logged in as an admin user to change settings",
975            &body,
976        );
977
978        // C. POST with admin_user logged in should succeed with 303
979        let form_to_clear = Form {
980            show_users: true,
981            admin_users: Vec::new(),
982        };
983
984        let (status, body) = test_app
985            .request(
986                Method::POST,
987                "/pc-settings",
988                None,
989                Some(&admin_cookie),
990                None,
991                Some(&form_to_clear),
992            )
993            .await;
994        assert_eq_or_print_body(status, 303, &body);
995
996        // Check that settings are updated and admin_users is cleared/missing
997        let loaded = PcSettings::load().unwrap();
998        assert!(matches!(
999            loaded.admin_users,
1000            MaybeOption::Missing | MaybeOption::Null
1001        ));
1002    }
1003}