mortise-core 1.1.0

Reads Laravel apps that use nwidart/laravel-modules. No interface.
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! The runtime status of a running app, read through `nwidart/laravel-actuator`.
//!
//! The client asks for the actuator base path, `health`, `info`, `mappings`, `scheduledtasks` and
//! `prometheus` only. It never asks for `env` and follows no redirect. It asks for `prometheus`
//! only while the Metrics tab is open and the window is visible, and reads that answer as text.
//! What the app answers is called Runtime; it is not mixed with Findings, which Mortise works out
//! from files.

use std::io::Read;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::runtime::environment::{Credentials, Environment};

/// The status the actuator reports, for the app or for one component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Status {
    Up,
    Down,
    OutOfService,
    Unknown,
}

impl Status {
    fn parse(text: &str) -> Self {
        match text {
            "UP" => Status::Up,
            "DOWN" => Status::Down,
            "OUT_OF_SERVICE" => Status::OutOfService,
            _ => Status::Unknown,
        }
    }
}

/// One health indicator of the app.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Component {
    pub name: String,
    pub status: Status,
    /// The details the app gives, as it wrote them, in its order.
    pub details: Vec<(String, String)>,
}

/// What `info` says. Every part is absent when the app does not give it.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Info {
    pub environment: Option<String>,
    pub laravel: Option<String>,
    pub git_branch: Option<String>,
    pub git_commit: Option<String>,
    pub php_version: Option<String>,
    pub php_sapi: Option<String>,
    /// Bytes. A limit of -1 means there is none.
    pub memory_usage: Option<i64>,
    pub memory_peak: Option<i64>,
    pub memory_limit: Option<i64>,
}

/// One route of the app, from `mappings`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Route {
    pub methods: Vec<String>,
    /// Without a leading slash, as Laravel has it.
    pub uri: String,
    pub name: Option<String>,
    /// `Modules\Blog\Http\Controllers\BlogController@index`, or `Closure`.
    pub action: String,
    pub middleware: Vec<String>,
}

/// One scheduled task of the app, from `scheduledtasks`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Task {
    /// The description, else the command, else the class of the job.
    pub target: String,
    /// The cron expression. `None` for a task that runs more than once a minute.
    pub expression: Option<String>,
    /// For a task that runs more than once a minute: how often, in milliseconds.
    pub interval_ms: Option<u64>,
    pub timezone: Option<String>,
    /// The next run, as the app wrote it: ISO 8601 in the task's timezone.
    pub next: Option<String>,
    /// The module that scheduled the task, from its `tags.module`. Newer versions of
    /// laravel-actuator and laravel-modules add the tag (PKG-2); older versions give `None`.
    #[serde(default)]
    pub module: Option<String>,
}

/// What a running app answered.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Runtime {
    pub status: Status,
    /// The components of `health`. `None` when the app hides them.
    pub components: Option<Vec<Component>>,
    /// The endpoints the app exposes, from the links at the actuator's base path.
    pub exposed: Vec<String>,
    /// `None` when `info` is not exposed.
    pub info: Option<Info>,
    /// `None` when `mappings` is not exposed.
    pub routes: Option<Vec<Route>>,
    /// `None` when `scheduledtasks` is not exposed.
    pub tasks: Option<Vec<Task>>,
}

impl Runtime {
    /// True when the app exposes this endpoint.
    pub fn exposes(&self, endpoint: &str) -> bool {
        self.exposed.iter().any(|exposed| exposed == endpoint)
    }

    /// The endpoints Mortise reads beside `health` that the app does not expose.
    pub fn not_exposed(&self) -> Vec<&'static str> {
        ["info", "mappings", "scheduledtasks"]
            .into_iter()
            .filter(|endpoint| !self.exposes(endpoint))
            .collect()
    }
}

/// What asking an environment gave. "No answer" and "Not authorized" are Mortise's
/// words for the connection, not statuses of the app.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Answer {
    /// Nothing came back: a refused connection, a timeout, a name that does not resolve.
    NoAnswer {
        url: String,
        message: String,
    },
    /// The app answered 401 or 403.
    NotAuthorized {
        url: String,
        status: u16,
    },
    /// The app answered with a status the actuator does not use, such as 500 or 404.
    Unexpected {
        url: String,
        status: u16,
        /// Where a redirect sends to, as a full address. Mortise does not follow it.
        location: Option<String>,
    },
    Answered(Box<Runtime>),
}

/// The secret that goes with [`Credentials`]: a token, a password or a header value.
pub type Secret = Option<String>;

/// The most text Mortise reads from one `prometheus` answer, after decompression.
pub const METRICS_BODY_LIMIT: u64 = 16 * 1024 * 1024;

/// Why a read of `prometheus` gave no metrics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoMetrics {
    /// 200 with an empty body: metrics are off in the app.
    Off,
    /// 503: the first line of the body as the app wrote it, at most 200 characters.
    Unavailable {
        url: String,
        line: String,
    },
    /// The body is longer than the limit.
    TooLarge {
        url: String,
        limit: u64,
    },
    NoAnswer {
        url: String,
        message: String,
    },
    NotAuthorized {
        url: String,
        status: u16,
    },
    Unexpected {
        url: String,
        status: u16,
        location: Option<String>,
    },
}

/// A response of the app: its status, its body and the `Location` header.
struct Reply {
    status: u16,
    body: String,
    /// The body was longer than the limit of the request. `body` is then empty.
    too_large: bool,
    location: Option<String>,
}

/// One connection to an environment: an agent, and the credentials every request carries.
struct Client<'a> {
    agent: ureq::Agent,
    environment: &'a Environment,
    secret: &'a Secret,
}

impl<'a> Client<'a> {
    fn new(environment: &'a Environment, secret: &'a Secret) -> Self {
        let config = ureq::Agent::config_builder()
            .timeout_global(Some(TIMEOUT))
            // A 503 from health is an answer, not a failed request.
            .http_status_as_error(false)
            // A redirect is not followed. It could take a custom header with the secret to
            // another host, or ask for a path Mortise does not read. It comes back as an
            // unexpected answer that names where it sends to.
            .max_redirects(0)
            // The certificates this computer trusts, so that a local site with its own
            // certificate authority works as it does in the browser.
            .tls_config(
                ureq::tls::TlsConfig::builder()
                    .root_certs(ureq::tls::RootCerts::PlatformVerifier)
                    .build(),
            )
            .build();
        Self {
            agent: ureq::Agent::new_with_config(config),
            environment,
            secret,
        }
    }

    /// Asks for `url`. With a limit, only the body of a 200 or a 503 is read, up to that many
    /// decoded bytes, and a read of it that fails, such as a timeout, is a failed request. Any
    /// other status comes back with an empty body, so a body that breaks off cannot hide it.
    fn get(&self, url: &str, limit: Option<u64>) -> Result<Reply, ureq::Error> {
        // Laravel answers errors as JSON only when it is asked for JSON.
        let mut request = self.agent.get(url).header("Accept", "application/json");
        let secret = self.secret.as_deref().unwrap_or_default();
        match &self.environment.credentials {
            Credentials::None => {}
            Credentials::Bearer => {
                request = request.header("Authorization", format!("Bearer {secret}"));
            }
            Credentials::Basic { user } => {
                let pair = base64(format!("{user}:{secret}").as_bytes());
                request = request.header("Authorization", format!("Basic {pair}"));
            }
            Credentials::Header { name } => request = request.header(name.as_str(), secret),
        }
        let mut response = request.call()?;
        let status = response.status().as_u16();
        let location = response
            .headers()
            .get("location")
            .and_then(|value| value.to_str().ok())
            .map(|location| resolve(url, location));
        let (body, too_large) = match limit {
            None => (
                response.body_mut().read_to_string().unwrap_or_default(),
                false,
            ),
            Some(_) if !matches!(status, 200 | 503) => (String::new(), false),
            Some(limit) => {
                // The reader of `with_config()` has no limit of its own and decodes gzip, so
                // this one counts decoded bytes. One byte past the limit says the body is longer.
                let mut bytes = Vec::new();
                response
                    .body_mut()
                    .with_config()
                    .reader()
                    .take(limit.saturating_add(1))
                    .read_to_end(&mut bytes)
                    .map_err(ureq::Error::from)?;
                if bytes.len() as u64 > limit {
                    (String::new(), true)
                } else {
                    (String::from_utf8_lossy(&bytes).into_owned(), false)
                }
            }
        };
        Ok(Reply {
            status,
            body,
            too_large,
            location,
        })
    }

    /// The JSON an endpoint answers, or the answer that says why there is none.
    fn fetch(&self, endpoint: &str) -> Result<Value, Answer> {
        let url = self.environment.url(endpoint);
        let reply = match self.get(&url, None) {
            Ok(reply) => reply,
            Err(error) => {
                return Err(Answer::NoAnswer {
                    url,
                    message: reason(&error),
                });
            }
        };
        match reply.status {
            // 503: the app is down or out of service, and says so in the body.
            200 | 503 => Ok(serde_json::from_str(&reply.body).unwrap_or(Value::Null)),
            status @ (401 | 403) => Err(Answer::NotAuthorized { url, status }),
            status => Err(Answer::Unexpected {
                url,
                status,
                location: reply.location.filter(|_| (300..400).contains(&status)),
            }),
        }
    }

    /// The text of `prometheus`, or why there is none.
    fn metrics(&self) -> Result<String, NoMetrics> {
        let url = self.environment.url("prometheus");
        let reply = match self.get(&url, Some(METRICS_BODY_LIMIT)) {
            Ok(reply) => reply,
            Err(error) => {
                return Err(NoMetrics::NoAnswer {
                    url,
                    message: reason(&error),
                });
            }
        };
        match reply.status {
            200 | 503 if reply.too_large => Err(NoMetrics::TooLarge {
                url,
                limit: METRICS_BODY_LIMIT,
            }),
            200 if reply.body.trim().is_empty() => Err(NoMetrics::Off),
            200 => Ok(reply.body),
            // A 503 of maintenance mode can be a whole page: only its first line is kept.
            503 => Err(NoMetrics::Unavailable {
                url,
                line: reply
                    .body
                    .lines()
                    .next()
                    .unwrap_or_default()
                    .chars()
                    .take(200)
                    .collect(),
            }),
            status @ (401 | 403) => Err(NoMetrics::NotAuthorized { url, status }),
            status => Err(NoMetrics::Unexpected {
                url,
                status,
                location: reply.location.filter(|_| (300..400).contains(&status)),
            }),
        }
    }

    /// The status of the app and of its components, from `health`.
    fn health(&self) -> Result<(Status, Option<Vec<Component>>), Answer> {
        let health = self.fetch("health")?;
        let status = |value: &Value| {
            value
                .get("status")
                .and_then(Value::as_str)
                .map_or(Status::Unknown, Status::parse)
        };
        let components = health
            .get("components")
            .and_then(Value::as_object)
            .map(|components| {
                components
                    .iter()
                    .map(|(name, component)| Component {
                        name: name.clone(),
                        status: status(component),
                        details: component
                            .get("details")
                            .and_then(Value::as_object)
                            .map(|details| {
                                details
                                    .iter()
                                    .map(|(key, value)| (key.clone(), plain(value)))
                                    .collect()
                            })
                            .unwrap_or_default(),
                    })
                    .collect()
            });
        Ok((status(&health), components))
    }

    fn everything(&self) -> Result<Runtime, Answer> {
        // What is exposed: the links at the base path. An endpoint that is not listed
        // has no route in the app.
        let exposed: Vec<String> = self
            .fetch("")?
            .get("_links")
            .and_then(Value::as_object)
            .map(|links| {
                links
                    .keys()
                    .filter(|key| *key != "self" && !key.contains('-'))
                    .cloned()
                    .collect()
            })
            .unwrap_or_default();
        let (status, components) = self.health()?;
        let mut runtime = Runtime {
            status,
            components,
            exposed,
            info: None,
            routes: None,
            tasks: None,
        };
        if runtime.exposes("info") {
            runtime.info = Some(read_info(&self.fetch("info")?));
        }
        if runtime.exposes("mappings") {
            runtime.routes = Some(read_routes(&self.fetch("mappings")?));
        }
        if runtime.exposes("scheduledtasks") {
            runtime.tasks = Some(read_tasks(&self.fetch("scheduledtasks")?));
        }
        Ok(runtime)
    }
}

/// A `Location` header read against the address that was asked for.
fn resolve(url: &str, location: &str) -> String {
    let Some((scheme, rest)) = url.split_once("://") else {
        return location.to_owned();
    };
    let host = rest.split('/').next().unwrap_or_default();
    if location.starts_with("//") {
        format!("{scheme}:{location}")
    } else if location.starts_with('/') {
        format!("{scheme}://{host}{location}")
    } else {
        // A full address, or a relative path, which is shown as given.
        location.to_owned()
    }
}

/// How long Mortise waits for one endpoint.
const TIMEOUT: Duration = Duration::from_secs(10);

/// Why nothing came back, in a few words.
fn reason(error: &ureq::Error) -> String {
    use std::io::ErrorKind;
    let timeout = || format!("no answer in {} s", TIMEOUT.as_secs());
    let text = match error {
        ureq::Error::Timeout(_) => return timeout(),
        ureq::Error::HostNotFound => return "the host was not found".to_owned(),
        ureq::Error::ConnectionFailed => return "connection failed".to_owned(),
        ureq::Error::BadUri(_) => return "the URL is not valid".to_owned(),
        ureq::Error::Io(error) => match error.kind() {
            ErrorKind::ConnectionRefused => return "connection refused".to_owned(),
            ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted => {
                return "the connection was closed".to_owned();
            }
            ErrorKind::TimedOut => return timeout(),
            // WSAHOST_NOT_FOUND and WSANO_DATA: the name does not resolve.
            #[cfg(windows)]
            _ if matches!(error.raw_os_error(), Some(11001 | 11004)) => {
                return "the host was not found".to_owned();
            }
            _ => error.to_string(),
        },
        other => other.to_string(),
    };
    // What is left comes as the text of the operating system or of the TLS library.
    if text.contains("lookup address") {
        "the host was not found".to_owned()
    } else if text.contains("invalid peer certificate") {
        "the certificate is not trusted on this computer".to_owned()
    } else {
        text
    }
}

/// Asks an environment for everything Mortise reads: what is exposed, `health`,
/// and `info`, `mappings` and `scheduledtasks` where they are exposed.
///
/// This waits for the app, for at most 10 s an endpoint: call it from a worker thread.
pub fn ask(environment: &Environment, secret: &Secret) -> Answer {
    match Client::new(environment, secret).everything() {
        Ok(runtime) => Answer::Answered(Box::new(runtime)),
        Err(answer) => answer,
    }
}

/// Asks an environment for `health` only, which is what the regular check does.
/// The rest is taken over from `earlier`, the last full answer.
pub fn ask_status(environment: &Environment, secret: &Secret, earlier: &Runtime) -> Answer {
    match Client::new(environment, secret).health() {
        Ok((status, components)) => Answer::Answered(Box::new(Runtime {
            status,
            components,
            ..earlier.clone()
        })),
        Err(answer) => answer,
    }
}

/// Asks an environment for `prometheus`. `Ok` is the text of a 200 that is not empty.
///
/// The request carries `Accept: application/json` and the credentials, as every request does.
/// This waits for the app, for at most 10 s: call it from a worker thread.
pub fn ask_metrics(environment: &Environment, secret: &Secret) -> Result<String, NoMetrics> {
    Client::new(environment, secret).metrics()
}

/// A JSON value as the app wrote it, without quotes around a string.
fn plain(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        // The certificate check of the operating system said no.
        other if other.to_string().starts_with("invalid peer certificate") => {
            "the certificate is not trusted on this computer".to_owned()
        }
        other => other.to_string(),
    }
}

fn text(value: &Value, path: &[&str]) -> Option<String> {
    path.iter()
        .try_fold(value, |value, key| value.get(key))?
        .as_str()
        .map(str::to_owned)
}

fn number(value: &Value, path: &[&str]) -> Option<i64> {
    path.iter()
        .try_fold(value, |value, key| value.get(key))?
        .as_i64()
}

fn read_info(info: &Value) -> Info {
    Info {
        environment: text(info, &["app", "environment"]),
        laravel: text(info, &["app", "laravel"]),
        git_branch: text(info, &["git", "branch"]),
        git_commit: text(info, &["git", "commit", "id"]),
        php_version: text(info, &["php", "version"]),
        php_sapi: text(info, &["php", "sapi"]),
        memory_usage: number(info, &["process", "memory", "usage"]),
        memory_peak: number(info, &["process", "memory", "peak"]),
        memory_limit: number(info, &["process", "memory", "limit"]),
    }
}

fn strings(value: Option<&Value>) -> Vec<String> {
    value
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_owned)
                .collect()
        })
        .unwrap_or_default()
}

fn read_routes(mappings: &Value) -> Vec<Route> {
    mappings
        .get("routes")
        .and_then(Value::as_array)
        .map(|routes| {
            routes
                .iter()
                .map(|route| Route {
                    methods: strings(route.get("methods")),
                    uri: text(route, &["uri"]).unwrap_or_default(),
                    name: text(route, &["name"]),
                    action: text(route, &["action"]).unwrap_or_default(),
                    middleware: strings(route.get("middleware")),
                })
                .collect()
        })
        .unwrap_or_default()
}

fn read_tasks(tasks: &Value) -> Vec<Task> {
    let list = |key: &str| {
        tasks
            .get(key)
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default()
    };
    let cron = list("cron").into_iter().map(|task| Task {
        target: text(&task, &["runnable", "target"]).unwrap_or_default(),
        expression: text(&task, &["expression"]),
        interval_ms: None,
        timezone: text(&task, &["timezone"]),
        next: text(&task, &["nextExecution", "time"]),
        module: text(&task, &["tags", "module"]),
    });
    let fixed = list("fixedRate").into_iter().map(|task| Task {
        target: text(&task, &["runnable", "target"]).unwrap_or_default(),
        expression: None,
        interval_ms: task.get("interval").and_then(Value::as_u64),
        timezone: None,
        next: None,
        module: text(&task, &["tags", "module"]),
    });
    cron.chain(fixed).collect()
}

/// Base64, for HTTP basic.
fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let group = u32::from(chunk[0]) << 16
            | u32::from(*chunk.get(1).unwrap_or(&0)) << 8
            | u32::from(*chunk.get(2).unwrap_or(&0));
        for i in 0..4 {
            if i <= chunk.len() {
                out.push(ALPHABET[(group >> (18 - 6 * i) & 63) as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

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

    #[test]
    fn base64_matches_known_values() {
        assert_eq!(base64(b""), "");
        assert_eq!(base64(b"f"), "Zg==");
        assert_eq!(base64(b"fo"), "Zm8=");
        assert_eq!(base64(b"foo"), "Zm9v");
        assert_eq!(base64(b"mortise:secret"), "bW9ydGlzZTpzZWNyZXQ=");
    }
}