shlane 0.2.1

A fastlane-like automation tool written in Rust with Rhai scripting support
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
//! Actions that talk to a network.

use crate::actions::context::ActionContext;
use crate::actions::{Action, ActionOutput, ArgSpec, Args};
use crate::error::Result;
use std::time::Duration;

const TIMEOUT: Duration = Duration::from_secs(30);

/// Attempts, and how long to wait before each retry.
const RETRIES: u32 = 3;
const BACKOFF: Duration = Duration::from_millis(500);

fn agent() -> ureq::Agent {
    ureq::Agent::config_builder()
        // A 4xx or 5xx is a result to report, not a transport error.
        .http_status_as_error(false)
        .timeout_global(Some(TIMEOUT))
        .build()
        .into()
}

pub struct Response {
    pub status: u16,
    pub body: String,
}

/// What to send, if anything.
pub enum Payload<'a> {
    Empty,
    Text(&'a str),
    Bytes(&'a [u8]),
}

/// Send a request, retrying transport failures and 5xx.
///
/// CI networks fail often enough that one attempt is not enough
/// (`docs/plan/11-ci-integration.md`).
pub fn send(
    ctx: &ActionContext<'_>,
    method: &str,
    url: &str,
    headers: &[(String, String)],
    body: Payload<'_>,
) -> std::result::Result<Response, String> {
    let agent = agent();
    let mut last = String::new();

    for attempt in 1..=RETRIES {
        // ureq types requests by whether they carry a body, so the two shapes
        // cannot share one builder variable.
        let result = match method {
            "POST" | "PUT" | "PATCH" => {
                let mut request = match method {
                    "POST" => agent.post(url),
                    "PUT" => agent.put(url),
                    _ => agent.patch(url),
                };
                for (name, value) in headers {
                    request = request.header(name, value);
                }
                match body {
                    Payload::Empty => request.send(""),
                    Payload::Text(text) => request.send(text),
                    Payload::Bytes(bytes) => request.send(bytes),
                }
            }
            "GET" | "DELETE" | "HEAD" => {
                let mut request = match method {
                    "GET" => agent.get(url),
                    "DELETE" => agent.delete(url),
                    _ => agent.head(url),
                };
                for (name, value) in headers {
                    request = request.header(name, value);
                }
                request.call()
            }
            other => return Err(format!("unsupported HTTP method '{other}'")),
        };

        match result {
            Ok(mut response) => {
                let status = response.status().as_u16();
                let text = response
                    .body_mut()
                    .read_to_string()
                    .unwrap_or_else(|err| format!("<could not read body: {err}>"));

                if status < 500 || attempt == RETRIES {
                    return Ok(Response { status, body: text });
                }
                last = format!("HTTP {status}");
            }
            Err(err) => {
                last = err.to_string();
                if attempt == RETRIES {
                    return Err(last);
                }
            }
        }

        ctx.ui
            .say(&format!("Attempt {attempt} failed ({last}); retrying..."));
        std::thread::sleep(BACKOFF * attempt);
    }

    Err(last)
}

/// Fetch a URL as bytes.
///
/// Separate from [`send`] because that reads the body as a string, which is
/// right for an API and wrong for a `.zip`: a keystore read through
/// `read_to_string` comes out replaced with U+FFFD and only fails later, when
/// something tries to sign with it.
pub fn fetch_bytes(
    ctx: &ActionContext<'_>,
    url: &str,
    headers: &[(String, String)],
) -> std::result::Result<(u16, Vec<u8>), String> {
    let agent = agent();
    let mut last = String::new();

    for attempt in 1..=RETRIES {
        let mut request = agent.get(url);
        for (name, value) in headers {
            request = request.header(name, value);
        }

        match request.call() {
            Ok(mut response) => {
                let status = response.status().as_u16();
                let bytes = response
                    .body_mut()
                    .with_config()
                    .limit(u64::MAX)
                    .read_to_vec()
                    .map_err(|err| format!("could not read the body: {err}"))?;

                if status < 500 || attempt == RETRIES {
                    return Ok((status, bytes));
                }
                last = format!("HTTP {status}");
            }
            Err(err) => {
                last = err.to_string();
                if attempt == RETRIES {
                    return Err(last);
                }
            }
        }

        ctx.ui
            .say(&format!("Attempt {attempt} failed ({last}); retrying..."));
        std::thread::sleep(BACKOFF * attempt);
    }

    Err(last)
}

fn parse_headers(raw: &str) -> Vec<(String, String)> {
    raw.split('\n')
        .filter_map(|line| line.split_once(':'))
        .map(|(name, value)| (name.trim().to_string(), value.trim().to_string()))
        .filter(|(name, _)| !name.is_empty())
        .collect()
}

pub struct HttpRequest;

impl Action for HttpRequest {
    fn name(&self) -> &'static str {
        "http_request"
    }

    fn description(&self) -> &'static str {
        "Send an HTTP request"
    }

    fn schema(&self) -> Vec<ArgSpec> {
        vec![
            ArgSpec::new("url", "Where to send it").required(),
            ArgSpec::new("method", "GET, POST, PUT, ...").default("GET"),
            ArgSpec::new("body", "Request body"),
            ArgSpec::new("headers", "One `Name: value` per line"),
            ArgSpec::new(
                "expect_status",
                "Fail unless the response has this status; empty means any 2xx",
            ),
        ]
    }

    fn run(&self, ctx: &mut ActionContext<'_>, args: &Args) -> Result<ActionOutput> {
        let url = args.get_or("url", "");
        let method = args.get_or("method", "GET").to_uppercase();
        let headers = parse_headers(args.get_or("headers", ""));

        if ctx.dry_run {
            ctx.ui.say(&format!("Would send {method} {url}"));
            return Ok(ActionOutput::new().with("status", "0").with("body", ""));
        }

        ctx.ui.say(&format!("{method} {url}"));
        let payload = match args.get("body") {
            Some(body) => Payload::Text(body),
            None => Payload::Empty,
        };
        let response = send(ctx, &method, url, &headers, payload).map_err(|message| {
            ctx.error(self.name(), format!("{method} {url} failed: {message}"))
        })?;

        let expected = args.get_or("expect_status", "");
        let ok = if expected.is_empty() {
            (200..300).contains(&response.status)
        } else {
            expected.parse::<u16>().ok() == Some(response.status)
        };

        if !ok {
            let body = response.body.trim();
            let detail = if body.is_empty() {
                String::new()
            } else {
                format!("\n  body: {}", body.chars().take(500).collect::<String>())
            };
            return Err(ctx.error(
                self.name(),
                format!("{method} {url} returned HTTP {}{detail}", response.status),
            ));
        }

        Ok(ActionOutput::new()
            .with("status", response.status.to_string())
            .with("body", response.body))
    }
}

pub struct NotifySlack;

impl Action for NotifySlack {
    fn name(&self) -> &'static str {
        "notify_slack"
    }

    fn description(&self) -> &'static str {
        "Post a message to a Slack incoming webhook"
    }

    fn schema(&self) -> Vec<ArgSpec> {
        vec![
            ArgSpec::new("webhook", "Incoming webhook URL")
                .required()
                .sensitive(),
            ArgSpec::new("text", "Message to post").required(),
            ArgSpec::new("channel", "Override the webhook's default channel"),
            ArgSpec::new("username", "Override the webhook's default name"),
        ]
    }

    fn run(&self, ctx: &mut ActionContext<'_>, args: &Args) -> Result<ActionOutput> {
        let webhook = args.get_or("webhook", "");
        // The URL is the credential; never let it reach the output.
        ctx.mark_secret(webhook);

        let mut fields = vec![("text", args.get_or("text", ""))];
        if let Some(channel) = args.get("channel") {
            fields.push(("channel", channel));
        }
        if let Some(username) = args.get("username") {
            fields.push(("username", username));
        }

        let payload = json_object(&fields);
        post_webhook(ctx, self.name(), "Slack", webhook, &payload)
    }
}

pub struct NotifyDiscord;

impl Action for NotifyDiscord {
    fn name(&self) -> &'static str {
        "notify_discord"
    }

    fn description(&self) -> &'static str {
        "Post a message to a Discord webhook"
    }

    fn schema(&self) -> Vec<ArgSpec> {
        vec![
            ArgSpec::new("webhook", "Webhook URL")
                .required()
                .sensitive(),
            ArgSpec::new("text", "Message to post").required(),
            ArgSpec::new("username", "Override the webhook's default name"),
        ]
    }

    fn run(&self, ctx: &mut ActionContext<'_>, args: &Args) -> Result<ActionOutput> {
        let webhook = args.get_or("webhook", "");
        ctx.mark_secret(webhook);

        let mut fields = vec![("content", args.get_or("text", ""))];
        if let Some(username) = args.get("username") {
            fields.push(("username", username));
        }
        post_webhook(ctx, self.name(), "Discord", webhook, &json_object(&fields))
    }
}

pub struct NotifyTeams;

impl Action for NotifyTeams {
    fn name(&self) -> &'static str {
        "notify_teams"
    }

    fn description(&self) -> &'static str {
        "Post a message to a Microsoft Teams webhook"
    }

    fn schema(&self) -> Vec<ArgSpec> {
        vec![
            ArgSpec::new("webhook", "Workflows or incoming webhook URL")
                .required()
                .sensitive(),
            ArgSpec::new("text", "Message to post").required(),
            ArgSpec::new("title", "A bold line above the message"),
        ]
    }

    fn run(&self, ctx: &mut ActionContext<'_>, args: &Args) -> Result<ActionOutput> {
        let webhook = args.get_or("webhook", "");
        ctx.mark_secret(webhook);

        let payload = teams_payload(args.get("title"), args.get_or("text", ""));
        post_webhook(ctx, self.name(), "Teams", webhook, &payload)
    }
}

/// An Adaptive Card wrapped in a message: the shape both Teams Workflows
/// webhooks and the older incoming-webhook connectors accept.
fn teams_payload(title: Option<&str>, text: &str) -> String {
    let block = |text: &str, bold: bool| {
        let weight = if bold {
            r#","weight":"Bolder","size":"Medium""#
        } else {
            ""
        };
        format!(
            r#"{{"type":"TextBlock","text":"{}","wrap":true{weight}}}"#,
            escape(text)
        )
    };
    let mut body = Vec::new();
    if let Some(title) = title {
        body.push(block(title, true));
    }
    body.push(block(text, false));

    format!(
        r#"{{"type":"message","attachments":[{{"contentType":"application/vnd.microsoft.card.adaptive","content":{{"type":"AdaptiveCard","$schema":"http://adaptivecards.io/schemas/adaptive-card.json","version":"1.4","body":[{}]}}}}]}}"#,
        body.join(",")
    )
}

fn json_object(fields: &[(&str, &str)]) -> String {
    format!(
        "{{{}}}",
        fields
            .iter()
            .map(|(key, value)| format!("\"{key}\":\"{}\"", escape(value)))
            .collect::<Vec<_>>()
            .join(",")
    )
}

/// POST a JSON payload to a chat webhook. The caller has already marked the
/// URL secret: it is the credential.
fn post_webhook(
    ctx: &mut ActionContext<'_>,
    action: &str,
    service: &str,
    webhook: &str,
    payload: &str,
) -> Result<ActionOutput> {
    if ctx.dry_run {
        ctx.ui.say(&format!("Would post to {service}: {payload}"));
        return Ok(ActionOutput::new().with("status", "0"));
    }

    ctx.ui.say(&format!("Posting to {service}"));
    let response = send(
        ctx,
        "POST",
        webhook,
        &[("Content-Type".to_string(), "application/json".to_string())],
        Payload::Text(payload),
    )
    .map_err(|message| ctx.error(action, format!("could not reach {service}: {message}")))?;

    if !(200..300).contains(&response.status) {
        return Err(ctx.error(
            action,
            format!(
                "{service} returned HTTP {}: {}",
                response.status,
                response.body.trim()
            ),
        ));
    }

    Ok(ActionOutput::new().with("status", response.status.to_string()))
}

pub fn escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out
}

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

    #[test]
    fn parses_headers() {
        let headers = parse_headers("Authorization: Bearer x\nContent-Type: application/json");
        assert_eq!(headers.len(), 2);
        assert_eq!(headers[0].0, "Authorization");
        assert_eq!(headers[0].1, "Bearer x");
    }

    #[test]
    fn ignores_malformed_header_lines() {
        assert!(parse_headers("nonsense").is_empty());
        assert!(parse_headers("").is_empty());
    }

    #[test]
    fn escapes_json_payloads() {
        assert_eq!(escape("say \"hi\""), "say \\\"hi\\\"");
        assert_eq!(escape("a\nb"), "a\\nb");
    }

    #[test]
    fn builds_flat_json_objects() {
        assert_eq!(
            json_object(&[("content", "hi \"you\""), ("username", "ci")]),
            r#"{"content":"hi \"you\"","username":"ci"}"#
        );
    }

    #[test]
    fn teams_payload_is_an_adaptive_card() {
        let payload = teams_payload(Some("Release"), "v1.2.3\nshipped");
        assert!(payload.starts_with(r#"{"type":"message","attachments":[{"contentType":"application/vnd.microsoft.card.adaptive""#), "{payload}");
        assert!(payload.contains(r#"{"type":"TextBlock","text":"Release","wrap":true,"weight":"Bolder","size":"Medium"}"#), "{payload}");
        assert!(
            payload.contains(r#"{"type":"TextBlock","text":"v1.2.3\nshipped","wrap":true}"#),
            "{payload}"
        );
        assert!(!teams_payload(None, "x").contains("Bolder"));
    }
}