1
use server::config::{ConfigError, system_config};
2
use server::db::DBError;
3

            
4
/// Public-facing SSH endpoint advertised in the
5
/// `/account/ssh-key` "key added" snippet. All three values are
6
/// optional — operators set them via env (`SSH_HOSTNAME`,
7
/// `SSH_PORT`, `SSH_HOST_FINGERPRINT`) on the deployment ConfigMap.
8
#[derive(Debug, Clone)]
9
pub struct SshConnectInfo {
10
    pub hostname: String,
11
    pub port: u16,
12
    pub host_fingerprint: String,
13
}
14

            
15
impl SshConnectInfo {
16
    fn from_env() -> Self {
17
        Self {
18
            hostname: std::env::var("SSH_HOSTNAME")
19
                .unwrap_or_else(|_| "ssh.example.invalid".to_string()),
20
            port: std::env::var("SSH_PORT")
21
                .ok()
22
                .and_then(|raw| raw.parse::<u16>().ok())
23
                .unwrap_or(2222),
24
            host_fingerprint: std::env::var("SSH_HOST_FINGERPRINT")
25
                .unwrap_or_else(|_| "(not configured)".to_string()),
26
        }
27
    }
28
}
29

            
30
/// An environment value, if the deployment actually supplied one.
31
///
32
/// A key set to nothing counts as unset: a ConfigMap can carry an empty
33
/// string, and taking that literally would override good configuration with a
34
/// URL that cannot parse.
35
///
36
/// Takes the looked-up value rather than reading the environment so it is
37
/// testable without mutating process-global state.
38
4
pub fn env_override(raw: Option<String>) -> Option<String> {
39
4
    raw.filter(|value| !value.trim().is_empty())
40
4
}
41

            
42
#[derive(Debug, Clone)]
43
pub struct Config {
44
    pub site_url: String,
45

            
46
    pub redis_url: String,
47

            
48
    // Token lifetimes only. Signing keys are no longer global config — each user
49
    // signs with their own keypair (see `crate::auth_keys` / `server::auth_keys`).
50
    pub access_token_max_age: i64,
51

            
52
    pub refresh_token_max_age: i64,
53

            
54
    pub ssh: SshConnectInfo,
55
}
56

            
57
impl Config {
58
    pub async fn init() -> Result<Config, DBError> {
59
        let site_url = system_config("site_url")
60
            .await?
61
            .ok_or(ConfigError::NoConfig("site_url".to_string()))?
62
            .to_string();
63

            
64
        // The environment wins for the session store: it is a deployment
65
        // endpoint, like DATABASE_URL, not something an operator edits in the
66
        // running site. The seeded row is redis://127.0.0.1:6379/, so without
67
        // this every fresh install crash-loops on any host where Redis is not
68
        // on loopback, and the only cure is rewriting the row by hand after
69
        // the first boot.
70
        let redis_url = match env_override(std::env::var("REDIS_URL").ok()) {
71
            Some(url) => url,
72
            None => system_config("redis_url")
73
                .await?
74
                .ok_or(ConfigError::NoConfig("redis_url".to_string()))?
75
                .to_string(),
76
        };
77

            
78
        let access_token_max_age = system_config("access_token_maxage")
79
            .await?
80
            .ok_or(ConfigError::NoConfig("access_token_maxage".to_string()))?
81
            .to_string();
82

            
83
        let refresh_token_max_age = system_config("refresh_token_maxage")
84
            .await?
85
            .ok_or(ConfigError::NoConfig("refresh_token_maxage".to_string()))?
86
            .to_string();
87

            
88
        Ok(Config {
89
            site_url,
90
            redis_url,
91
            access_token_max_age: parse_age(access_token_max_age, "access_token_maxage")?,
92
            refresh_token_max_age: parse_age(refresh_token_max_age, "refresh_token_maxage")?,
93
            ssh: SshConnectInfo::from_env(),
94
        })
95
    }
96
}
97

            
98
/// Longest token lifetime accepted, in minutes: one year.
99
///
100
/// A bound, not a policy preference: the minutes are added to `now` when a
101
/// token is minted and multiplied into a Redis TTL, and a large enough value
102
/// overflows the date (a panic in every login) before it overflows `i64`.
103
const MAX_TOKEN_AGE_MINUTES: i64 = 525_600;
104

            
105
/// A token lifetime in minutes, refused unless it is in `1..=MAX_TOKEN_AGE_MINUTES`.
106
///
107
/// # Errors
108
/// [`ConfigError::NoConfig`] naming `field` when `raw` is not such a number.
109
16
fn parse_age(raw: String, field: &str) -> Result<i64, ConfigError> {
110
16
    raw.parse::<i64>()
111
16
        .ok()
112
12
        .filter(|minutes| (1..=MAX_TOKEN_AGE_MINUTES).contains(minutes))
113
12
        .ok_or_else(|| ConfigError::NoConfig(field.to_string()))
114
16
}
115

            
116
#[cfg(test)]
117
mod parse_age_tests {
118
    use super::{MAX_TOKEN_AGE_MINUTES, parse_age};
119

            
120
    #[test]
121
2
    fn a_lifetime_that_cannot_be_minted_is_refused() {
122
2
        for bad in ["0", "-15", "abc", "", "200000000000", &i64::MAX.to_string()] {
123
12
            assert!(
124
12
                parse_age(bad.to_string(), "access_token_maxage").is_err(),
125
                "{bad:?} must be refused"
126
            );
127
        }
128
2
    }
129

            
130
    #[test]
131
2
    fn an_ordinary_lifetime_is_accepted() {
132
2
        assert_eq!(parse_age("15".to_string(), "f").ok(), Some(15));
133
2
        assert_eq!(
134
2
            parse_age(MAX_TOKEN_AGE_MINUTES.to_string(), "f").ok(),
135
2
            Some(MAX_TOKEN_AGE_MINUTES)
136
        );
137
2
    }
138
}