forklaunch 1.32.0

Launch faster with forklaunch
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
use std::io::{IsTerminal, Write};

use anyhow::{Context, Result, bail};
use clap::{Arg, ArgAction, ArgMatches, Command};
use dialoguer::{Confirm, theme::ColorfulTheme};
use reqwest::StatusCode;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};

use crate::{
    CliCommand,
    constants::ERROR_FAILED_TO_SEND_REQUEST,
    core::{
        command::command,
        email_sender::{self, EmailSender},
        http_client,
    },
    managed::client::{
        UNSUPPORTED_CONTROL_PLANE, is_unrouted_404, managed_url, require_managed_mode,
        resolve_managed_auth,
    },
};

const DEFAULT_INSTANCE_SENDER: &str = "no-reply@<host prefix>.<platform sending domain>";

fn email_sender_path(id: &str) -> String {
    format!("/instances/{}/email-sender", urlencoding::encode(id))
}

fn id_arg(help: &'static str) -> Arg {
    Arg::new("id").long("id").required(true).help(help)
}

/// Session auth, as every other `managed instance` command uses.
fn require_session() -> Result<()> {
    let auth_mode = resolve_managed_auth()?;
    require_managed_mode(&auth_mode)?;
    Ok(())
}

/// A 404 from a route that was never mounted is an old control plane, not "no sender".
fn unsupported_if_unrouted(body: &str) -> Result<()> {
    if is_unrouted_404(body) {
        bail!("{}", UNSUPPORTED_CONTROL_PLANE);
    }
    Ok(())
}

#[derive(Debug)]
pub(super) struct EmailCommand {
    set: EmailSetCommand,
    status: EmailStatusCommand,
    remove: EmailRemoveCommand,
}

impl EmailCommand {
    pub(super) fn new() -> Self {
        Self {
            set: EmailSetCommand,
            status: EmailStatusCommand,
            remove: EmailRemoveCommand,
        }
    }
}

impl CliCommand for EmailCommand {
    fn command(&self) -> Command {
        command(
            "email",
            "Send an instance's managed-gateway email from your own domain (Pro)",
        )
        .long_about(
            "Send a managed instance's email from a domain you own instead of the default \
             no-reply@<host prefix>.<platform sending domain> address (Pro and Enterprise \
             plans).\n\n\
             Until the domain verifies, mail keeps going from the default sender, so sends \
             never fail while you wait. If the domain is delegated to ForkLaunch the DKIM \
             records are written for you; otherwise publish the CNAMEs that `set` and \
             `status` print. A domain can belong to one organization only.\n\n\
             This is separate from `email-gateway`, which sets the instance's sending limits.",
        )
        .subcommand_required(true)
        .subcommand(self.set.command())
        .subcommand(self.status.command())
        .subcommand(self.remove.command())
    }

    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        match matches.subcommand() {
            Some(("set", m)) => self.set.handler(m),
            Some(("status", m)) => self.status.handler(m),
            Some(("remove", m)) => self.remove.handler(m),
            _ => unreachable!(),
        }
    }
}

#[derive(Debug)]
struct EmailSetCommand;

impl CliCommand for EmailSetCommand {
    fn command(&self) -> Command {
        command("set", "Send this instance's email from your own domain")
            .arg(id_arg("Id of the instance"))
            .arg(
                Arg::new("domain")
                    .long("domain")
                    .required(true)
                    .help("Domain to send from (e.g. clinic.com)"),
            )
            .arg(
                Arg::new("from")
                    .long("from")
                    .help("Local part of the address, before the @ (e.g. care; default no-reply)"),
            )
            .arg(
                Arg::new("name")
                    .long("name")
                    .help("Display name shown to recipients (e.g. \"Clinic Care\")"),
            )
    }

    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let id = matches
            .get_one::<String>("id")
            .context("--id is required")?;
        let domain = matches
            .get_one::<String>("domain")
            .context("--domain is required")?;
        email_sender::validate_domain(domain)?;
        let mut body = serde_json::json!({ "domain": domain });
        if let Some(from) = matches.get_one::<String>("from") {
            email_sender::validate_local_part(from)?;
            body["localPart"] = serde_json::Value::String(from.clone());
        }
        if let Some(name) = matches.get_one::<String>("name") {
            email_sender::validate_display_name(name)?;
            body["displayName"] = serde_json::Value::String(name.clone());
        }

        require_session()?;
        let response = http_client::put(&managed_url(&email_sender_path(id)), body)
            .with_context(|| ERROR_FAILED_TO_SEND_REQUEST)?;
        let status = response.status();
        if !status.is_success() {
            let text = response.text().unwrap_or_default();
            if status == StatusCode::NOT_FOUND {
                unsupported_if_unrouted(&text)?;
            }
            return Err(email_sender::request_error(
                "set the email sender",
                status,
                &text,
            ));
        }
        let sender: EmailSender = response
            .json()
            .with_context(|| "Failed to parse email sender response")?;

        let mut stdout = StandardStream::stdout(ColorChoice::Always);
        stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
        write!(stdout, "  Set")?;
        stdout.reset()?;
        writeln!(
            stdout,
            "  instance {} sends from {}",
            id,
            sender.formatted_from()
        )?;
        email_sender::write_sender(
            &mut stdout,
            &sender,
            &format!("instance {}", id),
            DEFAULT_INSTANCE_SENDER,
        )?;
        writeln!(stdout)?;
        writeln!(
            stdout,
            "  Next: run `forklaunch managed instance email status --id {}` to check verification.",
            id
        )?;
        Ok(())
    }
}

#[derive(Debug)]
struct EmailStatusCommand;

impl CliCommand for EmailStatusCommand {
    fn command(&self) -> Command {
        command(
            "status",
            "Show the instance's custom email sender and its verification",
        )
        .arg(id_arg("Id of the instance"))
        .arg(
            Arg::new("json")
                .long("json")
                .help("Output raw JSON instead of formatted terminal output")
                .action(ArgAction::SetTrue),
        )
    }

    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let id = matches
            .get_one::<String>("id")
            .context("--id is required")?;
        let json = matches.get_flag("json");

        require_session()?;
        let response = http_client::get(&managed_url(&email_sender_path(id)))
            .with_context(|| ERROR_FAILED_TO_SEND_REQUEST)?;
        let status = response.status();
        let text = response.text().unwrap_or_default();

        let mut stdout = StandardStream::stdout(ColorChoice::Always);
        if status == StatusCode::NO_CONTENT || status == StatusCode::NOT_FOUND {
            unsupported_if_unrouted(&text)?;
            if json {
                writeln!(stdout, "null")?;
            } else {
                writeln!(
                    stdout,
                    "No custom email sender for instance {}: it sends from the default platform sender.",
                    id
                )?;
            }
            return Ok(());
        }
        if !status.is_success() {
            return Err(email_sender::request_error(
                "get the email sender",
                status,
                &text,
            ));
        }
        if json {
            let value: serde_json::Value = serde_json::from_str(&text)
                .with_context(|| "Failed to parse email sender response")?;
            writeln!(stdout, "{}", serde_json::to_string_pretty(&value)?)?;
            return Ok(());
        }
        let sender: EmailSender =
            serde_json::from_str(&text).with_context(|| "Failed to parse email sender response")?;
        email_sender::write_sender(
            &mut stdout,
            &sender,
            &format!("instance {}", id),
            DEFAULT_INSTANCE_SENDER,
        )?;
        writeln!(stdout)?;
        Ok(())
    }
}

#[derive(Debug)]
struct EmailRemoveCommand;

impl CliCommand for EmailRemoveCommand {
    fn command(&self) -> Command {
        command(
            "remove",
            "Go back to the default platform sender for an instance",
        )
        .arg(id_arg("Id of the instance"))
        .arg(
            Arg::new("yes")
                .long("yes")
                .short('y')
                .action(ArgAction::SetTrue)
                .help("Skip the confirmation prompt"),
        )
    }

    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let id = matches
            .get_one::<String>("id")
            .context("--id is required")?;

        let mut stdout = StandardStream::stdout(ColorChoice::Always);
        if !matches.get_flag("yes") {
            if !std::io::stdin().is_terminal() {
                bail!(
                    "Refusing to remove the email sender for instance {} without a terminal. Pass --yes to confirm.",
                    id
                );
            }
            writeln!(
                stdout,
                "Email from instance {} will go back to the default platform sender ({}).",
                id, DEFAULT_INSTANCE_SENDER
            )?;
            let confirmed = Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Remove the custom email sender?")
                .default(false)
                .interact()?;
            if !confirmed {
                writeln!(stdout, "Cancelled.")?;
                return Ok(());
            }
        }

        require_session()?;
        let response = http_client::delete(&managed_url(&email_sender_path(id)))
            .with_context(|| ERROR_FAILED_TO_SEND_REQUEST)?;
        let status = response.status();
        if !status.is_success() {
            let text = response.text().unwrap_or_default();
            if status == StatusCode::NOT_FOUND {
                unsupported_if_unrouted(&text)?;
            }
            return Err(email_sender::request_error(
                "remove the email sender",
                status,
                &text,
            ));
        }
        stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
        write!(stdout, "  Removed")?;
        stdout.reset()?;
        writeln!(
            stdout,
            "  the custom email sender for instance {}; it sends from the default platform sender again",
            id
        )?;
        Ok(())
    }
}

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

    fn email_cmd() -> Command {
        EmailCommand::new().command().version("0.0.0-test")
    }

    #[test]
    fn command_definition_is_valid() {
        email_cmd().debug_assert();
    }

    #[test]
    fn requires_a_subcommand() {
        assert!(email_cmd().try_get_matches_from(["email"]).is_err());
    }

    #[test]
    fn subcommands_parse() {
        assert!(
            email_cmd()
                .try_get_matches_from([
                    "email",
                    "set",
                    "--id",
                    "inst-1",
                    "--domain",
                    "clinic.com",
                    "--from",
                    "care",
                    "--name",
                    "Clinic Care",
                ])
                .is_ok()
        );
        assert!(
            email_cmd()
                .try_get_matches_from(["email", "status", "--id", "inst-1", "--json"])
                .is_ok()
        );
        assert!(
            email_cmd()
                .try_get_matches_from(["email", "remove", "--id", "inst-1", "-y"])
                .is_ok()
        );
    }

    #[test]
    fn required_args() {
        assert!(
            email_cmd()
                .try_get_matches_from(["email", "set", "--id", "inst-1"])
                .is_err()
        );
        assert!(
            email_cmd()
                .try_get_matches_from(["email", "set", "--domain", "clinic.com"])
                .is_err()
        );
        assert!(
            email_cmd()
                .try_get_matches_from(["email", "status"])
                .is_err()
        );
        assert!(
            email_cmd()
                .try_get_matches_from(["email", "remove", "--yes"])
                .is_err()
        );
    }

    #[test]
    fn path_encodes_the_instance_id() {
        assert_eq!(
            email_sender_path("inst-1"),
            "/instances/inst-1/email-sender"
        );
        assert_eq!(email_sender_path("a/b"), "/instances/a%2Fb/email-sender");
    }
}