1
use crate::command::{admin_connection, connection};
2
use sqlx::Row;
3
use sqlx::types::Uuid;
4
use std::fmt::Debug;
5
use supp_macro::command;
6

            
7
use super::{CmdError, CmdResult};
8
use crate::{
9
    config::{ConfigError, ConfigOption, config_on, list_config_on, set_config_on},
10
    timezone,
11
    user::User,
12
};
13
/// The config key as stored: trimmed, never blank.
14
23590
fn config_key(name: &str) -> Result<&str, CmdError> {
15
23590
    match name.trim() {
16
1
        "" => Err(CmdError::Args(
17
1
            "The config name must not be blank".to_string(),
18
1
        )),
19
23589
        key => Ok(key),
20
    }
21
23590
}
22

            
23
/// A timezone value must name a zone and is stored trimmed; every other key is stored as given.
24
7207
fn stored_value(key: &str, value: String) -> Result<String, CmdError> {
25
7207
    if !timezone::is_key(key) {
26
4145
        return Ok(value);
27
3062
    }
28
3062
    let name = value.trim();
29
3062
    timezone::parse_zone(name).map_err(CmdError::Refused)?;
30
3061
    Ok(name.to_string())
31
7207
}
32

            
33
command! {
34
    GetConfig {
35
        #[required]
36
        user_id: Uuid,
37
        #[required]
38
        name: String,
39
    } => {
40
        let user = User { id: user_id };
41
        // An absent key is "not set" (Ok(None) → the native emits
42
        // `(:config-value nil)`), not a hard error. This keeps absent
43
        // (nil) distinct from a key holding the empty string ("") while
44
        // letting genuine DB errors still propagate.
45
        let mut conn = connection(&user).await?;
46
        match config_on(&mut conn, config_key(&name)?).await {
47
1128
            Ok(opt) => Ok(opt.map(|v| match v {
48
1128
                ConfigOption::String(s) => CmdResult::String(s),
49
                ConfigOption::Blob(b) => CmdResult::Data(b),
50
1128
            })),
51
            Err(ConfigError::NoConfig(_)) => Ok(None),
52
            Err(e) => Err(e.into()),
53
        }
54
    }
55
68199
}
56

            
57
command! {
58
    ListConfig {
59
        #[required]
60
        user_id: Uuid,
61
    } => {
62
        let mut conn = connection(&User { id: user_id }).await?;
63
        let entries = list_config_on(&mut conn).await?;
64
        Ok(Some(CmdResult::ConfigEntries(entries)))
65
    }
66
3646
}
67

            
68
command! {
69
    GetTimezone {
70
        #[required]
71
        user_id: Uuid,
72
    } => {
73
        let mut conn = connection(&User { id: user_id }).await?;
74
        match timezone::zone_on(&mut conn).await {
75
            Ok(zone) => Ok(Some(CmdResult::Timezone(zone))),
76
            Err(ConfigError::InvalidTimezone(message)) => Err(CmdError::Refused(message)),
77
            Err(err) => Err(err.into()),
78
        }
79
    }
80
187420
}
81

            
82
command! {
83
    GetVersion {
84
    } => {
85
        const HASH: &str = env!("GIT_HASH");
86
        Ok(Some(CmdResult::String(HASH.to_string())))
87
    }
88
1541
}
89

            
90
command! {
91
    GetBuildDate {
92
    } => {
93
    const BUILD: &str = env!("BUILD_DATE");
94
        Ok(Some(CmdResult::String(BUILD.to_string())))
95
    }
96
861
}
97

            
98
command! {
99
    SetConfig {
100
        #[required]
101
        user_id: Uuid,
102
        #[required]
103
        name: String,
104
        #[required]
105
        value: String,
106
    } => {
107
        let key = config_key(&name)?;
108
        let value = stored_value(key, value)?;
109
        let user = User { id: user_id };
110
        let mut conn = connection(&user).await?;
111
        set_config_on(&mut conn, key, ConfigOption::String(value)).await?;
112
        Ok(None)
113
    }
114
31424
}
115

            
116
command! {
117
    SelectColumn {
118
        #[required]
119
        field: String,
120
        #[required]
121
        table: String,
122
    } => {
123
        let mut conn = admin_connection().await?;
124

            
125
        // `field`/`table` are SQL identifiers (not bindable as `$n`), so they
126
        // are interpolated. `AssertSqlSafe` is sound ONLY because select-column
127
        // is a trusted-operator escape hatch: it is reachable from the CLI
128
        // `sql selcol` / direct dispatch, never registered as an RPC/script
129
        // native (see rpc::natives::config). Do not expose it to untrusted
130
        // callers without validating/quoting the identifiers first.
131
        let values: Vec<String> = sqlx::query(sqlx::AssertSqlSafe(format!(
132
            "SELECT {field}::text FROM {table}"
133
        )))
134
            .fetch_all(&mut *conn)
135
            .await?
136
            .into_iter()
137
            .map(|row| row.get::<Option<String>, _>(0).unwrap_or_default())
138
            .collect();
139

            
140
        Ok(Some(CmdResult::Lines(values)))
141
    }
142
}
143

            
144
#[cfg(test)]
145
mod command_config_tests {
146
    use super::*;
147
    use crate::{db::install_test_pool, user::User};
148
    use sqlx::{PgPool, types::Uuid};
149
    use supp_macro::local_db_sqlx_test;
150
    use tokio::sync::OnceCell;
151

            
152
    /// Context for keeping environment intact
153
    static CONTEXT: OnceCell<()> = OnceCell::const_new();
154
    static USER: OnceCell<User> = OnceCell::const_new();
155

            
156
3
    async fn setup() {
157
3
        CONTEXT
158
3
            .get_or_init(|| async {
159
3
                crate::telemetry::init_test_logging();
160
6
            })
161
3
            .await;
162
6
        USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
163
3
            .await;
164
3
    }
165

            
166
    #[local_db_sqlx_test]
167
    async fn set_then_get_config_round_trips_per_user(pool: PgPool) -> anyhow::Result<()> {
168
        let user_id = Uuid::new_v4();
169
        SetConfig::new()
170
            .user_id(user_id)
171
            .name("testfield".to_string())
172
            .value("testval".to_string())
173
            .run()
174
            .await?;
175

            
176
        let val = GetConfig::new()
177
            .user_id(user_id)
178
            .name("testfield".to_string())
179
            .run()
180
            .await?
181
            .unwrap();
182
        assert_eq!(val.to_string(), "testval");
183
    }
184

            
185
    #[local_db_sqlx_test]
186
    async fn set_config_refuses_a_blank_name(pool: PgPool) -> anyhow::Result<()> {
187
        let result = SetConfig::new()
188
            .user_id(Uuid::new_v4())
189
            .name(" \t".to_string())
190
            .value("v".to_string())
191
            .run()
192
            .await;
193

            
194
        assert!(matches!(result, Err(CmdError::Args(_))), "{result:?}");
195
    }
196

            
197
    #[local_db_sqlx_test]
198
    async fn list_config_returns_the_users_pairs_ordered_by_name(
199
        pool: PgPool,
200
    ) -> anyhow::Result<()> {
201
        let user_id = Uuid::new_v4();
202
        for (name, value) in [("beta", "2"), ("Alpha", "1"), ("beta", "3")] {
203
            SetConfig::new()
204
                .user_id(user_id)
205
                .name(name.to_string())
206
                .value(value.to_string())
207
                .run()
208
                .await?;
209
        }
210

            
211
        let Some(CmdResult::ConfigEntries(listed)) =
212
            ListConfig::new().user_id(user_id).run().await?
213
        else {
214
            anyhow::bail!("no config entries");
215
        };
216
        assert_eq!(
217
            listed,
218
            vec![
219
                ("Alpha".to_string(), "1".to_string()),
220
                ("beta".to_string(), "3".to_string()),
221
            ]
222
        );
223
    }
224
}