ordinary-api 0.6.0-pre.13

API server for Ordinary
Documentation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

mod ops;

use anyhow::bail;
use bytes::{BufMut, BytesMut};
use fs_err::DirEntry;
use ordinary_auth::token::{extract_hmac_no_check, get_exp};
use std::env::home_dir;
use std::path::Path;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
use tracing::instrument;

use crate::ApiInfo;
use ed25519_dalek::{SigningKey, ed25519::signature::SignerMut};
use ordinary_monitor::LogFileMetadata;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use totp_rs::TOTP;
use uuid::Uuid;

/// client for interaction with Ordinary API Server
pub struct OrdinaryApiClient<'a> {
    pub(crate) addr: &'a str,
    pub(crate) account: &'a str,
    pub(crate) api_domain: Option<&'a str>,
    pub(crate) client: Client,
    pub(crate) correlation_id: Option<Uuid>,
}

fn compress_zstd(val: &[u8]) -> std::io::Result<Vec<u8>> {
    zstd::stream::encode_all(std::io::Cursor::new(val), 17)
}

fn strip_http(addr: &str) -> &str {
    if let Some(stripped) = addr.strip_prefix("https://") {
        return stripped;
    }
    if let Some(stripped) = addr.strip_prefix("http://") {
        return stripped;
    }

    addr
}

fn get_client_dir(domain: &str, account: &str) -> PathBuf {
    home_dir()
        .expect("failed to get home dir")
        .join(".ordinary")
        .join("clients")
        .join(domain)
        .join(account)
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AccountMeta {
    pub id: String,
    pub host: String,
    pub domain: String,
    pub name: String,
    pub project: String,
    pub permissions: Vec<u8>,
    pub refresh_exp: u64,
}

impl<'a> OrdinaryApiClient<'a> {
    pub fn new(
        addr: &'a str,
        account: &'a str,
        api_domain: Option<&'a str>,
        danger_accept_invalid_certs: bool,
        user_agent: &str,
        correlation_id: bool,
    ) -> anyhow::Result<OrdinaryApiClient<'a>> {
        tracing::debug!("initializing Ordinary API client");

        let mut client_builder = Client::builder().use_rustls_tls().zstd(true);
        client_builder = client_builder.user_agent(user_agent);

        if danger_accept_invalid_certs {
            client_builder = client_builder.danger_accept_invalid_certs(true);
        }

        let client = client_builder.build()?;

        Ok(OrdinaryApiClient {
            addr,
            account,
            api_domain,
            client,
            correlation_id: correlation_id.then(Uuid::new_v4),
        })
    }

    pub(crate) fn get_password_hash_and_domain(&self, password: &str) -> (Vec<u8>, &'a str) {
        let (mut input, domain) = match self.api_domain {
            Some(domain) => (domain.as_bytes().to_vec(), domain),
            None => (
                strip_http(self.addr).as_bytes().to_vec(),
                strip_http(self.addr),
            ),
        };

        input.extend_from_slice(self.account.as_bytes());
        input.extend_from_slice(password.as_bytes());

        let mut hasher = Sha256::new();
        hasher.update(&input);
        let password = hasher.finalize().to_vec();

        (password, domain)
    }

    #[allow(clippy::missing_panics_doc)]
    pub fn get_host(domain: &str, account: &str) -> anyhow::Result<String> {
        let clients = home_dir()
            .expect("failed to get home dir")
            .join(".ordinary")
            .join("clients");

        let host = fs_err::read_to_string(clients.join(domain).join(account).join("host"))?;

        Ok(host)
    }

    #[allow(clippy::missing_panics_doc)]
    pub fn list_accounts() -> anyhow::Result<Vec<AccountMeta>> {
        let clients = home_dir()
            .expect("failed to get home dir")
            .join(".ordinary")
            .join("clients");

        let mut out = vec![];

        for entry in fs_err::read_dir(&clients)? {
            let path = entry?.path();

            if path.is_dir()
                && let Some(domain) = &path.strip_prefix(&clients)?.to_str()
            {
                for entry in fs_err::read_dir(&path)? {
                    let path = entry?.path();

                    if path.is_dir()
                        && let Some(account) = path.strip_prefix(clients.join(domain))?.to_str()
                    {
                        let host = fs_err::read_to_string(
                            clients.join(domain).join(account).join("host"),
                        )?;
                        out.push(Self::get_account(&host, domain, account)?);
                    }
                }
            }
        }

        Ok(out)
    }

    pub fn get_account(host: &str, domain: &str, account: &str) -> anyhow::Result<AccountMeta> {
        tracing::debug!("getting account");

        let path = get_client_dir(domain, account);
        tracing::debug!(path = %path.display());

        let refresh_token = fs_err::read(path.join("refresh_token"))?;
        let access_token = fs_err::read(path.join("access_token"))?;

        tracing::debug!("extracting claims");
        let claims = extract_hmac_no_check(&access_token)?;

        let claims_vec = match flexbuffers::Reader::get_root(
            &claims[..claims.len().checked_sub(8 + 64).unwrap_or(claims.len())],
        ) {
            Ok(v) => v.as_vector(),
            Err(_) => flexbuffers::Reader::get_root(claims)?.as_vector(),
        };

        let system_claims = claims_vec.idx(0).as_vector();
        let token_uuid_bytes: [u8; 16] = system_claims.idx(0).as_blob().0.try_into()?;

        let token_uuid_str = Uuid::from_bytes(token_uuid_bytes).to_string();

        let project = claims_vec.idx(1).as_str();
        let permissions = claims_vec
            .idx(2)
            .as_vector()
            .iter()
            .map(|r| r.as_u8())
            .collect::<Vec<u8>>();

        Ok(AccountMeta {
            id: token_uuid_str,
            host: (*host).to_owned(),
            domain: (*domain).to_owned(),
            name: (*account).to_owned(),
            project: project.to_owned(),
            permissions,
            refresh_exp: get_exp(&refresh_token)?,
        })
    }

    /// register with API server
    #[instrument(skip_all, err)]
    pub async fn register(
        &self,
        password: &str,
        invite_code: &str,
    ) -> anyhow::Result<(TOTP, String)> {
        ops::account::register(self, password, invite_code).await
    }

    /// log in to API server
    #[instrument(skip_all, err)]
    pub async fn login(&self, password: &str, mfa_code: &str) -> anyhow::Result<()> {
        ops::account::login(self, password, mfa_code).await
    }

    /// get access token for API server
    pub async fn get_access(
        &self,
        duration_s: Option<u32>,
        correlation_id: Option<String>,
    ) -> anyhow::Result<Vec<u8>> {
        ops::account::get_access(self, duration_s, correlation_id).await
    }

    /// reset API account password
    #[instrument(skip_all, err)]
    pub async fn reset_password(
        &self,
        old_password: &str,
        mfa_code: &str,
        new_password: &str,
    ) -> anyhow::Result<()> {
        ops::account::reset_password(self, old_password, mfa_code, new_password).await
    }

    /// recover forgotten API account password
    #[instrument(skip_all, err)]
    pub async fn forgot_password(
        &self,
        new_password: &str,
        recovery_code: &str,
    ) -> anyhow::Result<()> {
        // todo: forgot password should include MFA code?
        ops::account::forgot_password(self, new_password, recovery_code).await
    }

    /// reset MFA TOTP secret for API account
    #[instrument(skip_all, err)]
    pub async fn mfa_totp_reset(&self, password: &str, mfa_code: &str) -> anyhow::Result<TOTP> {
        ops::account::mfa_totp_reset(self, password, mfa_code).await
    }

    /// recover lost MFA TOTP secret for API account
    #[instrument(skip_all, err)]
    pub async fn mfa_totp_lost(&self, password: &str, recovery_code: &str) -> anyhow::Result<TOTP> {
        ops::account::mfa_totp_lost(self, password, recovery_code).await
    }

    /// reset API account recovery codes
    #[instrument(skip_all, err)]
    pub async fn recovery_codes_reset(
        &self,
        password: &str,
        mfa_code: &str,
    ) -> anyhow::Result<String> {
        ops::account::recovery_codes_reset(self, password, mfa_code).await
    }

    /// delete API account
    #[instrument(skip_all, err)]
    pub async fn delete_account(&self, password: &str, mfa_code: &str) -> anyhow::Result<()> {
        ops::account::delete(self, password, mfa_code).await
    }

    /// invite API account
    #[instrument(skip(self), err)]
    pub async fn invite_api_account(
        &self,
        app_domain: &str,
        account_name: &str,
        permissions: Vec<u8>,
    ) -> anyhow::Result<String> {
        ops::account::invite_account(self, app_domain, account_name, permissions).await
    }

    /// list accounts for the API server
    #[instrument(skip(self), err)]
    pub async fn api_accounts_list(&self, proj_path: Option<&str>) -> anyhow::Result<String> {
        ops::account::accounts_list(self, proj_path).await
    }

    /// deploy app to a API server
    #[instrument(skip(self), err)]
    pub async fn deploy(&self, proj_path: &str) -> anyhow::Result<u16> {
        ops::app::deploy(self, proj_path).await
    }

    /// kill app on API server
    #[instrument(skip(self), err)]
    pub async fn kill(&self, proj_path: &str) -> anyhow::Result<()> {
        ops::app::kill(self, proj_path).await
    }

    /// restart app on API server
    #[instrument(skip(self), err)]
    pub async fn restart(&self, proj_path: &str) -> anyhow::Result<u16> {
        ops::app::restart(self, proj_path).await
    }

    /// erase app on API server
    #[instrument(skip(self), err)]
    pub async fn erase(&self, proj_path: &str) -> anyhow::Result<()> {
        ops::app::erase(self, proj_path).await
    }

    /// root info
    #[instrument(skip_all, err)]
    pub async fn root_get_info(&self) -> anyhow::Result<ApiInfo> {
        ops::root::info(self, None).await
    }

    /// locks an account
    #[instrument(skip_all, err)]
    pub async fn root_lock_account(&self, account: &str) -> anyhow::Result<()> {
        ops::root::set_lock(self, None, account, true).await
    }

    /// unlocks a locked account
    #[instrument(skip_all, err)]
    pub async fn root_unlock_account(&self, account: &str) -> anyhow::Result<()> {
        ops::root::set_lock(self, None, account, false).await
    }

    /// get the local logs metadata
    #[instrument(skip_all, err)]
    pub fn root_logs_local_metadata(&self) -> anyhow::Result<Vec<LogFileMetadata>> {
        ops::logs::logs_local_metadata("root", false)
    }

    /// get the remote logs metadata
    #[instrument(skip_all, err)]
    pub async fn root_logs_remote_metadata(&self) -> anyhow::Result<Vec<LogFileMetadata>> {
        ops::logs::logs_remote_metadata(self, "root", None, false).await
    }

    #[instrument(skip_all, err)]
    pub async fn root_logs_sync(
        &self,
        force: Option<bool>,
        file: Option<&str>,
    ) -> anyhow::Result<()> {
        ops::logs::logs_sync(self, "root", force, file, false).await
    }

    /// query an app's logs
    #[instrument(skip_all, err)]
    pub fn root_logs_search(
        &self,
        query: &str,
        format: &str,
        limit: &Option<usize>,
    ) -> anyhow::Result<String> {
        ops::app::logs_search("root", query, format, limit)
    }

    /// get the local logs metadata
    #[instrument(skip_all, err)]
    pub fn app_logs_local_metadata(&self, proj_path: &str) -> anyhow::Result<Vec<LogFileMetadata>> {
        ops::logs::logs_local_metadata(proj_path, true)
    }

    /// get the remote logs metadata
    #[instrument(skip_all, err)]
    pub async fn app_logs_remote_metadata(
        &self,
        proj_path: &str,
    ) -> anyhow::Result<Vec<LogFileMetadata>> {
        ops::logs::logs_remote_metadata(self, proj_path, None, true).await
    }

    #[instrument(skip_all, err)]
    pub async fn app_logs_sync(
        &self,
        proj_path: &str,
        force: Option<bool>,
        file: Option<&str>,
    ) -> anyhow::Result<()> {
        ops::logs::logs_sync(self, proj_path, force, file, true).await
    }

    /// query an app's logs
    #[instrument(skip_all, err)]
    pub fn app_logs_search(
        &self,
        proj_path: &str,
        query: &str,
        format: &str,
        limit: &Option<usize>,
    ) -> anyhow::Result<String> {
        ops::app::logs_search(proj_path, query, format, limit)
    }

    /// list accounts for an app
    #[instrument(skip(self), err)]
    pub async fn app_accounts_list(&self, proj_path: &str) -> anyhow::Result<String> {
        ops::app::accounts_list(self, proj_path).await
    }

    /// list app items by their model index
    #[instrument(skip(self), err)]
    pub async fn items_list(&self, proj_path: &str, model_name: &str) -> anyhow::Result<String> {
        ops::models::items_list(self, proj_path, model_name).await
    }

    /// write a single asset
    #[instrument(skip(self), err)]
    pub async fn write(&self, proj_path: &str, asset_path: &str) -> anyhow::Result<()> {
        ops::assets::write(self, proj_path, asset_path).await
    }

    /// write all assets in assets `dir_path`
    #[instrument(skip(self), err)]
    pub async fn write_all(&self, proj_path: &str) -> anyhow::Result<()> {
        ops::assets::write_all(self, proj_path).await
    }

    /// upload a single template
    #[instrument(skip(self), err)]
    pub async fn upload(&self, proj_path: &str, template_name: &str) -> anyhow::Result<()> {
        ops::templates::upload(self, proj_path, template_name).await
    }

    /// upload all templates
    #[instrument(skip(self), err)]
    pub async fn upload_all(&self, proj_path: &str) -> anyhow::Result<()> {
        ops::templates::upload_all(self, proj_path).await
    }

    /// install single action
    #[instrument(skip(self), err)]
    pub async fn install(&self, proj_path: &str, action_name: &str) -> anyhow::Result<()> {
        ops::actions::install(self, proj_path, action_name).await
    }

    /// install all actions
    #[instrument(skip(self), err)]
    pub async fn install_all(&self, proj_path: &str) -> anyhow::Result<()> {
        ops::actions::install_all(self, proj_path).await
    }

    /// update content
    #[instrument(skip(self), err)]
    pub async fn update(&self, proj_path: &str) -> anyhow::Result<()> {
        ops::content::update(self, proj_path).await
    }

    /// store secret
    #[instrument(skip(self, secret), err)]
    pub async fn store(&self, proj_path: &str, name: &str, secret: &[u8]) -> anyhow::Result<()> {
        ops::secrets::store(self, proj_path, name, secret).await
    }

    fn sign_token(
        client_dir: &Path,
        token: &mut BytesMut,
        signing_key: Option<SigningKey>,
        duration_s: Option<u32>,
    ) -> anyhow::Result<()> {
        let client_exp = match SystemTime::now()
            .checked_add(Duration::from_secs(u64::from(duration_s.unwrap_or(3))))
        {
            Some(v) => v,
            None => bail!("failed to add"),
        }
        .duration_since(SystemTime::UNIX_EPOCH)?
        .as_secs();

        token.put_u64(client_exp);

        let mut signing_key = if let Some(sk) = signing_key {
            sk
        } else {
            let signing_key_bytes: [u8; 32] =
                match fs_err::read(client_dir.join("signing_key"))?.try_into() {
                    Ok(v) => v,
                    Err(_) => bail!("failed to convert"),
                };

            let signing_key: SigningKey = SigningKey::from_bytes(&signing_key_bytes);
            signing_key
        };

        let signature = signing_key.sign(&token[..]);

        token.put(&signature.to_bytes()[..]);

        Ok(())
    }
}

pub fn traverse(dir: &Path, cb: &dyn Fn(&DirEntry)) -> std::io::Result<()> {
    if dir.is_dir() {
        for entry in fs_err::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                traverse(&path, cb)?;
            } else {
                cb(&entry);
            }
        }
    }
    Ok(())
}