ordinaryd 0.8.0

Ordinary Server
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#![doc = include_str!("../README.md")]
#![doc = include_str!("../docs/cli-reference.md")]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]

// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

pub mod cmds;
pub mod fmt;

use clap::{Args, Parser, Subcommand};
use ordinary_config::OrdinaryConfig;
use std::fmt::Display;
use std::fs::DirEntry;
use std::path::Path;

use crate::fmt::StdioLogFmt;
use ordinary_monitor::LOG_FILE_FORMAT;
use ordinary_monitor::tracing::logger::OrdinaryLogger;
use tracing::level_filters::LevelFilter;

#[derive(Clone, Debug)]
pub enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

impl LogLevel {
    fn to_level_filter(&self) -> LevelFilter {
        match self {
            Self::Error => LevelFilter::ERROR,
            Self::Warn => LevelFilter::WARN,
            Self::Info => LevelFilter::INFO,
            Self::Debug => LevelFilter::DEBUG,
            Self::Trace => LevelFilter::TRACE,
        }
    }
}

impl clap::ValueEnum for LogLevel {
    fn value_variants<'a>() -> &'a [Self] {
        &[
            Self::Error,
            Self::Warn,
            Self::Info,
            Self::Debug,
            Self::Trace,
        ]
    }

    fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
        match self {
            Self::Error => Some(clap::builder::PossibleValue::new("error")),
            Self::Warn => Some(clap::builder::PossibleValue::new("warn")),
            Self::Info => Some(clap::builder::PossibleValue::new("info")),
            Self::Debug => Some(clap::builder::PossibleValue::new("debug")),
            Self::Trace => Some(clap::builder::PossibleValue::new("trace")),
        }
    }
}

impl Display for LogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let str = match self {
            Self::Error => String::from("error"),
            Self::Warn => String::from("warn"),
            Self::Info => String::from("info"),
            Self::Debug => String::from("debug"),
            Self::Trace => String::from("trace"),
        };
        write!(f, "{str}")
    }
}

#[derive(Clone, Debug)]
pub enum LogFileRotation {
    Day,
    Hour,
    Minute,
    Never,
}

impl clap::ValueEnum for LogFileRotation {
    fn value_variants<'a>() -> &'a [Self] {
        &[Self::Day, Self::Hour, Self::Minute, Self::Never]
    }

    fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
        match self {
            Self::Day => Some(clap::builder::PossibleValue::new("day")),
            Self::Hour => Some(clap::builder::PossibleValue::new("hour")),
            Self::Minute => Some(clap::builder::PossibleValue::new("minute")),
            Self::Never => Some(clap::builder::PossibleValue::new("never")),
        }
    }
}

impl Display for LogFileRotation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let str = match self {
            Self::Day => String::from("day"),
            Self::Hour => String::from("hour"),
            Self::Minute => String::from("minute"),
            Self::Never => String::from("never"),
        };
        write!(f, "{str}")
    }
}

#[derive(Clone, Debug)]
pub enum ProvisionMode {
    Localhost,
    Staging,
    Production,
}

impl clap::ValueEnum for ProvisionMode {
    fn value_variants<'a>() -> &'a [Self] {
        &[Self::Staging, Self::Production, Self::Localhost]
    }

    fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
        match self {
            Self::Localhost => Some(clap::builder::PossibleValue::new("localhost")),
            Self::Staging => Some(clap::builder::PossibleValue::new("staging")),
            Self::Production => Some(clap::builder::PossibleValue::new("production")),
        }
    }
}

impl Display for ProvisionMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let str = match self {
            Self::Localhost => String::from("localhost"),
            Self::Staging => String::from("staging"),
            Self::Production => String::from("production"),
        };
        write!(f, "{str}")
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
#[command(propagate_version = true)]
pub struct Cli {
    #[command(subcommand)]
    pub commands: Commands,

    #[command(flatten)]
    pub global_args: GlobalArgs,
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Args, Clone)]
pub struct GlobalArgs {
    /// specify the data directory
    #[arg(long, global = true, default_value_t = std::env::home_dir().expect("failed to get home dir").join(".ordinary").to_str().expect("failed to convert to str").to_string())]
    pub data_dir: String,

    /// persists JSON formatted log lines to <data-dir>/logs/<domain>/
    #[arg(long, global = true, default_value_t = false)]
    pub stored_logs: bool,

    /// logs events to stdio
    #[arg(long, global = true, default_value_t = false)]
    pub stdio_logs: bool,

    /// how to format stdio logs
    #[arg(long, global = true, default_value_t = StdioLogFmt::Json)]
    pub stdio_logs_fmt: StdioLogFmt,

    /// logs events to `journald` (only works on Linux distros that use `systemd`)
    #[arg(long, global = true, default_value_t = false)]
    pub journald_logs: bool,

    // todo: allow setting log levels for api, app, storage, templates, actions and integrations, independently
    /// base log level for every component
    #[arg(long, global = true, default_value_t = LogLevel::Info)]
    pub log_level: LogLevel,

    /// whether storage and certain payload sizes are logged
    #[arg(long, global = true, default_value_t = false)]
    pub log_sizes: bool,

    /// whether span timing is logged
    #[arg(long, global = true, default_value_t = false)]
    pub stdio_logs_timing: bool,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// initialize the environment for an Ordinary API server
    Init {
        #[command(flatten)]
        api_init: ApiInit,

        /// domain name for API console
        #[arg(long)]
        api_domain: String,

        /// instance user password
        #[arg(long, default_value_t = String::from("password"))]
        password: String,

        /// store the MFA key locally instead of copying a QR code
        #[arg(long, default_value_t = false)]
        mfa_stored: bool,

        /// contacts for the API domain cert provisioning
        #[arg(long, value_delimiter = ',', num_args = 1..)]
        api_contacts: Vec<String>,

        /// domains that apps can subdomain off of.
        ///
        /// i.e. when `example.com` is passed, `my.example.com` is
        /// considered a valid app domain.
        #[arg(long, value_delimiter = ',', num_args = 1..)]
        app_domains: Vec<String>,

        /// list of applications that have access to API server
        /// level commands (i.e. API server invite token generation)
        ///
        /// currently intended to enable API server admins to set up a
        /// web-based registration portal.
        #[arg(long, value_delimiter = ',', num_args = 0..)]
        privileged_domains: Option<Vec<String>>,
    },
    /// start the Ordinary API server
    Api {
        #[command(flatten)]
        api_init: ApiInit,

        #[command(flatten)]
        app_api: AppApi,

        /// give each app its own port
        #[arg(long, default_value_t = false)]
        dedicated_ports: bool,

        /// whether to expose the [OpenAPI](https://swagger.io/specification/) JSON at `/openapi`
        ///
        /// Note: this will automatically be turned on when `--swagger` is passed.
        #[arg(long, default_value_t = false)]
        openapi: bool,

        /// whether to expose the [Swagger](https://swagger.io) docs at `/swagger`
        #[arg(long, default_value_t = false)]
        swagger: bool,
    },
    /// start an Ordinary Application server
    App {
        #[command(flatten)]
        app_api: AppApi,

        /// for running a standalone project. (project must already be built)
        #[arg(short, long, default_value = ".")]
        project: String,

        /// use a different domain than what's in the `ordinary.json`
        #[arg(long)]
        domain_override: Option<String>,
    },
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Args)]
pub struct AppApi {
    /// what mode TLS certs should be provisioned in
    #[arg(long, default_value_t = ProvisionMode::Localhost)]
    pub provision: ProvisionMode,

    /// specify HTTP(s) port for server
    #[arg(long)]
    pub port: Option<u16>,

    /// specify HTTP port for server when
    /// running in secure mode.
    #[arg(long)]
    pub redirect_port: Option<u16>,

    /// run without HTTPS
    #[arg(long, default_value_t = false)]
    pub insecure: bool,

    /// run with insecure cookies
    #[arg(long, default_value_t = false)]
    pub insecure_cookies: bool,

    /// max period of time logs are stored
    #[arg(long, default_value_t = 72)]
    pub log_ttl_hours: u16,

    /// max size (in bytes) per log file
    #[arg(long, default_value_t = 10_000_000)]
    pub log_rotation_file_size: u64,

    /// max amount of time a log file is appended to
    /// before being compressed and stored
    #[arg(long, default_value_t = 60)]
    pub log_rotation_mins: u16,

    /// whether HTTP request and response headers are logged
    #[arg(long, default_value_t = false)]
    pub log_headers: bool,

    /// whether IP Addresses are logged with HTTP requests
    #[arg(long, default_value_t = false)]
    pub log_ips: bool,

    // todo: document and use enum
    /// "none" | "blake2" | "blake3"
    #[arg(long, default_value_t = String::from("none"))]
    pub redacted_header_hash: String,

    /// set to `true` to bypass verification of proxy domain and CNAME
    /// DNS TXT records.
    ///
    /// **IMPORTANT**: should ONLY be used for local development
    /// and testing.
    #[arg(long, default_value_t = false)]
    pub danger_dns_no_verify: bool,
}

#[derive(Debug, Args)]
pub struct ApiInit {
    /// environment (e.g production, development, staging)
    #[arg(long, default_value_t = String::from("staging"))]
    pub environment: String,

    /// Storage size in bytes (rounded up to nearest OS page size).
    #[arg(long)]
    pub storage_size: usize,
}

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

#[allow(clippy::too_many_lines)]
pub fn setup(cli: &Cli) -> anyhow::Result<Option<OrdinaryLogger>> {
    let logs_dir = match &cli.commands {
        Commands::App { project, .. } => {
            let config = OrdinaryConfig::get(project)?;

            Path::new(&cli.global_args.data_dir)
                .join("apps")
                .join(config.domain)
                .join("logs")
        }
        Commands::Init { api_init, .. } | Commands::Api { api_init, .. } => {
            Path::new(&cli.global_args.data_dir)
                .join("environments")
                .join(&api_init.environment)
                .join("logs")
        }
    };

    std::fs::create_dir_all(&logs_dir)?;

    let log_level_str = cli.global_args.log_level.to_string();

    let directives = [
        ("ordinary_config", &log_level_str),      // config
        ("ordinary_studio", &log_level_str),      // studio
        ("ordinary_doctor", &log_level_str),      // doctor
        ("ordinary_build", &log_level_str),       // build
        ("ordinary_modify", &log_level_str),      // modify
        ("ordinary_utils", &log_level_str),       // utils
        ("ordinary_auth", &log_level_str),        // auth
        ("ordinary_api", &log_level_str),         // api
        ("ordinary_app", &log_level_str),         // app
        ("ordinary_template", &log_level_str),    // templates
        ("ordinary_action", &log_level_str),      // actions
        ("ordinary_integration", &log_level_str), // integrations
        ("ordinary_storage", &log_level_str),     // storage
        ("ordinary_monitor", &log_level_str),     // storage
        ("tower_http", &log_level_str),           // http
        ("axum::rejection", &"trace".into()),     // http
        ("axum::serve", &log_level_str),          // http
    ];

    let mut directives_string = format!("ordinaryd={}", &log_level_str);

    for (lib, lvl) in directives {
        directives_string = format!("{directives_string},{lib}={lvl}");
    }

    let filter = tracing_subscriber::EnvFilter::builder()
        .with_default_directive(cli.global_args.log_level.to_level_filter().into())
        .parse(directives_string)?;

    let logger = if cli.global_args.stored_logs || cli.global_args.stdio_logs {
        let mut args = None;

        if let Commands::Api { app_api, .. } = &cli.commands {
            args = Some(app_api);
        }

        if let Commands::App { app_api, .. } = &cli.commands {
            args = Some(app_api);
        }

        if let Some(AppApi {
            log_ttl_hours,
            log_rotation_file_size,
            log_rotation_mins,
            ..
        }) = args
        {
            Some(OrdinaryLogger::new(
                cli.global_args.stored_logs,
                cli.global_args.stdio_logs,
                &cli.global_args.stdio_logs_fmt.to_string(),
                cli.global_args.journald_logs,
                &logs_dir,
                filter,
                *log_ttl_hours,
                *log_rotation_mins,
                usize::try_from(*log_rotation_file_size)?,
                LOG_FILE_FORMAT,
                cli.global_args.log_sizes,
                cli.global_args.stdio_logs_timing,
            )?)
        } else {
            None
        }
    } else {
        None
    };

    std::panic::set_hook(Box::new(|info| {
        if let Some(msg) = info.payload_as_str()
            && let Some(loc) = info.location()
        {
            tracing::error!(%loc, msg, "panic");
        } else if let Some(loc) = info.location() {
            tracing::error!(%loc, "panic");
        }
    }));

    Ok(logger)
}

#[allow(clippy::too_many_lines, clippy::missing_panics_doc)]
pub async fn run(cli: &Cli, logger: Option<OrdinaryLogger>) -> anyhow::Result<()> {
    match &cli.commands {
        Commands::App {
            app_api,
            project,
            domain_override,
        } => {
            cmds::app::run(
                project,
                domain_override,
                &cli.global_args.data_dir,
                cli.global_args.log_sizes,
                app_api.insecure,
                app_api.insecure_cookies,
                app_api.log_headers,
                app_api.log_ips,
                app_api.port,
                app_api.redirect_port,
                &app_api.provision,
                app_api.danger_dns_no_verify,
            )
            .await?;
        }
        Commands::Init {
            api_init,
            api_domain,
            password,
            mfa_stored,
            api_contacts,
            app_domains,
            privileged_domains,
        } => {
            cmds::init::run(
                &api_init.environment,
                api_domain,
                password,
                &cli.global_args.data_dir,
                api_init.storage_size,
                *mfa_stored,
                api_contacts,
                app_domains,
                privileged_domains,
                logger,
            )
            .await?;
        }
        Commands::Api {
            api_init,
            app_api,
            dedicated_ports,
            openapi,
            swagger,
            ..
        } => {
            cmds::api::run(
                &api_init.environment,
                &cli.global_args.data_dir,
                api_init.storage_size,
                cli.global_args.log_sizes,
                app_api.insecure,
                app_api.insecure_cookies,
                app_api.log_headers,
                app_api.log_ips,
                app_api.port,
                app_api.redirect_port,
                &app_api.provision,
                cli.global_args.stored_logs,
                logger,
                &app_api.redacted_header_hash,
                *dedicated_ports,
                *openapi,
                *swagger,
                app_api.danger_dns_no_verify,
            )
            .await?;
        }
    }

    Ok(())
}