k2db-api-server 0.1.1

Single-binary Rust server for the k2db API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// SPDX-FileCopyrightText: 2026 Alexander R. Croft
// SPDX-License-Identifier: MIT

use std::collections::{BTreeSet, HashMap};

use k2db::{AggregationMode, DatabaseConfig, HostConfig, OwnershipMode, QueryHooks};
use mongodb::bson::{Bson, doc};
use mongodb::options::{ClientOptions, ServerAddress};
use mongodb::{Client, Database};
use serde::Deserialize;

use crate::bootstrap::BootstrapConfig;

#[derive(Debug, Clone)]
pub struct AppConfig {
    pub server: ServerConfig,
    pub k2db: K2DbSection,
    pub apikey: ApiKeySection,
}

#[derive(Debug, Clone)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
}

#[derive(Debug, Clone)]
pub struct K2DbSection {
    pub hosts: Vec<HostEntry>,
    pub user: Option<String>,
    pub password: Option<String>,
    pub auth_source: Option<String>,
    pub ownership_mode: Option<OwnershipMode>,
    pub replica_set: Option<String>,
    pub slow_query_ms: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct HostEntry {
    pub host: String,
    pub port: Option<u16>,
}

#[derive(Debug, Clone)]
pub struct ApiKeySection {
    pub keys: HashMap<String, ApiKeyConfig>,
}

#[derive(Debug, Clone)]
pub struct ApiKeyConfig {
    pub key_id: String,
    pub secret_hash: String,
    pub database: String,
    pub permissions: Vec<String>,
    pub active: bool,
    pub expires_at: Option<i64>,
}

#[derive(Debug, thiserror::Error)]
pub enum AppConfigError {
    #[error("mongo control-plane error: {0}")]
    Mongo(#[from] mongodb::error::Error),
    #[error("missing active server_config document in control-plane database")]
    MissingActiveServerConfig,
    #[error("invalid configuration: {0}")]
    Validation(String),
}

#[derive(Debug, Deserialize)]
struct ServerConfigDocument {
    listen: ListenConfigDocument,
    #[serde(default)]
    k2db: RuntimeK2DbDocument,
}

#[derive(Debug, Deserialize)]
struct ListenConfigDocument {
    host: String,
    port: u16,
}

#[derive(Debug, Default, Deserialize)]
struct RuntimeK2DbDocument {
    #[serde(default)]
    ownership_mode: Option<OwnershipMode>,
    #[serde(default)]
    slow_query_ms: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct ApiKeyDocument {
    key_id: String,
    secret_hash: String,
    database: String,
    #[serde(default)]
    permissions: Vec<String>,
    active: bool,
    #[serde(default)]
    expires_at: Option<Bson>,
}

impl AppConfig {
    pub async fn load(bootstrap: &BootstrapConfig) -> Result<Self, AppConfigError> {
        let options = ClientOptions::parse(&bootstrap.mongo_uri).await?;
        let server_hosts = hosts_from_options(&options)?;
        let user = options
            .credential
            .as_ref()
            .and_then(|credential| credential.username.clone());
        let password = options
            .credential
            .as_ref()
            .and_then(|credential| credential.password.clone());
        let auth_source = options
            .credential
            .as_ref()
            .and_then(|credential| credential.source.clone());
        let replica_set = options.repl_set_name.clone();
        let client = Client::with_options(options)?;
        let control_plane = client.database(&bootstrap.system_db_name);

        let server_doc = load_server_config(&control_plane).await?;
        let keys = load_api_keys(&control_plane).await?;
        let config = Self {
            server: ServerConfig {
                host: server_doc.listen.host,
                port: server_doc.listen.port,
            },
            k2db: K2DbSection {
                hosts: server_hosts,
                user,
                password,
                auth_source,
                ownership_mode: server_doc.k2db.ownership_mode,
                replica_set,
                slow_query_ms: server_doc.k2db.slow_query_ms,
            },
            apikey: ApiKeySection { keys },
        };

        config.validate()?;
        Ok(config)
    }

    pub fn tenant_databases(&self) -> Vec<String> {
        self.apikey
            .keys
            .values()
            .map(|entry| entry.database.trim().to_owned())
            .filter(|name| !name.is_empty())
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect()
    }

    pub fn database_config(&self, database: &str) -> DatabaseConfig {
        DatabaseConfig {
            name: database.to_owned(),
            hosts: self
                .k2db
                .hosts
                .iter()
                .map(|host| HostConfig {
                    host: host.host.clone(),
                    port: host.port,
                })
                .collect(),
            user: self.k2db.user.clone(),
            password: self.k2db.password.clone(),
            auth_source: self.k2db.auth_source.clone(),
            replica_set: self.k2db.replica_set.clone(),
            slow_query_ms: self.k2db.slow_query_ms,
            ownership_mode: self.k2db.ownership_mode.unwrap_or_default(),
            aggregation_mode: AggregationMode::default(),
            secure_field_prefixes: Vec::new(),
            secure_field_encryption: None,
            hooks: QueryHooks::default(),
        }
    }

    fn validate(&self) -> Result<(), AppConfigError> {
        if self.server.host.trim().is_empty() {
            return Err(AppConfigError::Validation(
                "server.listen.host must not be empty".to_owned(),
            ));
        }
        if self.server.port == 0 {
            return Err(AppConfigError::Validation(
                "server.listen.port must be positive".to_owned(),
            ));
        }
        if self.k2db.hosts.is_empty() {
            return Err(AppConfigError::Validation(
                "bootstrap mongo_uri must resolve at least one host".to_owned(),
            ));
        }
        if self.k2db.hosts.iter().any(|host| host.host.trim().is_empty()) {
            return Err(AppConfigError::Validation(
                "bootstrap mongo_uri resolved an empty host entry".to_owned(),
            ));
        }
        for key in self.apikey.keys.values() {
            if key.key_id.trim().is_empty() {
                return Err(AppConfigError::Validation(
                    "control-plane key_id is required".to_owned(),
                ));
            }
            if key.secret_hash.trim().is_empty() {
                return Err(AppConfigError::Validation(format!(
                    "control-plane secret_hash is required for key {}",
                    key.key_id
                )));
            }
            if key.database.trim().is_empty() {
                return Err(AppConfigError::Validation(format!(
                    "control-plane database binding is required for key {}",
                    key.key_id
                )));
            }
        }
        Ok(())
    }
}

async fn load_server_config(
    control_plane: &Database,
) -> Result<ServerConfigDocument, AppConfigError> {
    let collection = control_plane.collection::<ServerConfigDocument>("server_config");
    let filter = doc! {
        "kind": "server_config",
        "active": true,
    };
    let count = collection.count_documents(filter.clone()).await?;
    if count == 0 {
        return Err(AppConfigError::MissingActiveServerConfig);
    }
    if count > 1 {
        return Err(AppConfigError::Validation(
            "multiple active server_config documents found".to_owned(),
        ));
    }

    collection
        .find_one(filter)
        .await?
        .ok_or(AppConfigError::MissingActiveServerConfig)
}

async fn load_api_keys(
    control_plane: &Database,
) -> Result<HashMap<String, ApiKeyConfig>, AppConfigError> {
    let collection = control_plane.collection::<ApiKeyDocument>("keys");
    let mut cursor = collection.find(doc! { "kind": "api_key" }).await?;
    let mut keys = HashMap::new();

    while cursor.advance().await? {
        let document = cursor.deserialize_current()?;
        let key_id = document.key_id.trim().to_owned();
        if key_id.is_empty() {
            return Err(AppConfigError::Validation(
                "control-plane key document contains an empty key_id".to_owned(),
            ));
        }
        if keys.contains_key(&key_id) {
            return Err(AppConfigError::Validation(format!(
                "duplicate control-plane key_id detected: {key_id}"
            )));
        }

        keys.insert(
            key_id.clone(),
            ApiKeyConfig {
                key_id,
                secret_hash: document.secret_hash,
                database: document.database,
                permissions: document.permissions,
                active: document.active,
                expires_at: normalize_expiry(document.expires_at)?,
            },
        );
    }

    Ok(keys)
}

fn hosts_from_options(options: &ClientOptions) -> Result<Vec<HostEntry>, AppConfigError> {
    let mut hosts = Vec::with_capacity(options.hosts.len());
    for address in &options.hosts {
        match address {
            ServerAddress::Tcp { host, port } => hosts.push(HostEntry {
                host: host.clone(),
                port: *port,
            }),
            #[cfg(unix)]
            ServerAddress::Unix { path } => {
                return Err(AppConfigError::Validation(format!(
                    "unix socket bootstrap addresses are not supported: {}",
                    path.display()
                )));
            }
            _ => {
                return Err(AppConfigError::Validation(
                    "unsupported bootstrap mongo server address".to_owned(),
                ));
            }
        }
    }
    Ok(hosts)
}

fn normalize_expiry(value: Option<Bson>) -> Result<Option<i64>, AppConfigError> {
    match value {
        None | Some(Bson::Null) => Ok(None),
        Some(Bson::Int64(value)) => Ok(Some(value)),
        Some(Bson::Int32(value)) => Ok(Some(i64::from(value))),
        Some(Bson::DateTime(value)) => Ok(Some(value.timestamp_millis())),
        Some(Bson::String(value)) => chrono::DateTime::parse_from_rfc3339(value.trim())
            .map(|parsed| Some(parsed.timestamp_millis()))
            .map_err(|_| {
                AppConfigError::Validation(format!(
                    "invalid control-plane expires_at value: {value}"
                ))
            }),
        Some(other) => Err(AppConfigError::Validation(format!(
            "unsupported control-plane expires_at type: {other}"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn base_config() -> AppConfig {
        AppConfig {
            server: ServerConfig {
                host: "0.0.0.0".to_owned(),
                port: 3000,
            },
            k2db: K2DbSection {
                hosts: vec![HostEntry {
                    host: "localhost".to_owned(),
                    port: Some(27017),
                }],
                user: None,
                password: None,
                auth_source: None,
                ownership_mode: Some(OwnershipMode::Strict),
                replica_set: None,
                slow_query_ms: Some(250),
            },
            apikey: ApiKeySection {
                keys: HashMap::from([
                    (
                        "beta".to_owned(),
                        ApiKeyConfig {
                            key_id: "beta".to_owned(),
                            secret_hash: "hash-2".to_owned(),
                            database: "zed".to_owned(),
                            permissions: Vec::new(),
                            active: true,
                            expires_at: None,
                        },
                    ),
                    (
                        "alpha".to_owned(),
                        ApiKeyConfig {
                            key_id: "alpha".to_owned(),
                            secret_hash: "hash-1".to_owned(),
                            database: "alpha".to_owned(),
                            permissions: Vec::new(),
                            active: true,
                            expires_at: None,
                        },
                    ),
                    (
                        "gamma".to_owned(),
                        ApiKeyConfig {
                            key_id: "gamma".to_owned(),
                            secret_hash: "hash-3".to_owned(),
                            database: "zed".to_owned(),
                            permissions: Vec::new(),
                            active: true,
                            expires_at: None,
                        },
                    ),
                ]),
            },
        }
    }

    #[test]
    fn tenant_databases_are_unique_and_sorted() {
        assert_eq!(
            base_config().tenant_databases(),
            vec!["alpha".to_owned(), "zed".to_owned()]
        );
    }

    #[test]
    fn normalize_expiry_accepts_epoch_millis() {
        let value = normalize_expiry(Some(Bson::Int64(1_770_000_000_000)))
            .expect("expiry");
        assert_eq!(value, Some(1_770_000_000_000));
    }

    #[test]
    fn normalize_expiry_accepts_rfc3339_strings() {
        let value = normalize_expiry(Some(Bson::String("2026-02-03T04:05:06Z".to_owned())))
            .expect("expiry")
            .expect("timestamp");
        assert_eq!(value, 1_770_091_506_000);
    }
}