greentic-runner-host 1.2.2

Host runtime shim for Greentic runner: config, pack loading, activity handling
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
use anyhow::{Context, Result, anyhow, bail};
use base64::Engine as _;
use greentic_types::TenantCtx;
use reqwest::Url;
use serde::Deserialize;
use serde_json::{Value, json};

use crate::oauth::{OAuthBrokerConfig, ResourceTokenRequest, build_resource_token_request};

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum EmailProviderKind {
    MsGraph,
    Gmail,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct EmailOauthHint {
    pub provider_id: String,
    pub flow: String,
    #[serde(default)]
    pub scopes: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct EmailSendRequest {
    pub provider: EmailProviderKind,
    pub payload: Value,
    pub oauth: Option<EmailOauthHint>,
    #[serde(default)]
    pub secret_events: Vec<Value>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailHttpExecution {
    pub method: &'static str,
    pub url: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailExecutionPlan {
    pub token_request: ResourceTokenRequest,
    pub http: EmailHttpExecution,
}

pub fn parse_email_send_request(value: &Value) -> Result<EmailSendRequest> {
    serde_json::from_value(value.clone()).context("invalid email send request payload")
}

pub fn build_email_http_execution(request: &EmailSendRequest) -> Result<EmailHttpExecution> {
    match request.provider {
        EmailProviderKind::MsGraph => {
            let sender = request
                .payload
                .get("message")
                .and_then(|m| m.get("from"))
                .and_then(|from| from.get("emailAddress"))
                .and_then(|addr| addr.get("address"))
                .and_then(Value::as_str)
                .filter(|value| !value.trim().is_empty())
                .ok_or_else(|| {
                    anyhow!(
                        "msgraph email host execution requires message.from.emailAddress.address"
                    )
                })?;
            if sender.contains(['/', '?', '#']) {
                bail!(
                    "msgraph sender address must not contain '/', '?' or '#': {}",
                    sender
                );
            }
            // The sender becomes ONE path segment. `\` and `%` are read as
            // separators or escapes by some URL parsers, `.`/`..` collapse the
            // segment, and whitespace/control characters have no business in a
            // mailbox address.
            let sender = sender.trim();
            if sender.contains(['\\', '%'])
                || sender.chars().any(|c| c.is_whitespace() || c.is_control())
                || sender == "."
                || sender == ".."
            {
                bail!("msgraph sender address is not a valid mailbox path segment");
            }
            let mut url = Url::parse("https://graph.microsoft.com/v1.0/users/")
                .context("msgraph base url")?;
            url.path_segments_mut()
                .map_err(|_| anyhow!("msgraph base url cannot carry path segments"))?
                .pop_if_empty()
                .push(sender)
                .push("sendMail");
            Ok(EmailHttpExecution {
                method: "POST",
                url: url.to_string(),
            })
        }
        EmailProviderKind::Gmail => Ok(EmailHttpExecution {
            method: "POST",
            url: "https://gmail.googleapis.com/gmail/v1/users/me/messages/send".into(),
        }),
    }
}

pub fn required_oauth_hint(request: &EmailSendRequest) -> Result<&EmailOauthHint> {
    let hint = request
        .oauth
        .as_ref()
        .ok_or_else(|| anyhow!("email send request missing oauth hint"))?;
    match request.provider {
        EmailProviderKind::MsGraph => {
            if hint.provider_id != "msgraph-email" {
                bail!("msgraph email request must use provider_id `msgraph-email`");
            }
        }
        EmailProviderKind::Gmail => {
            if hint.provider_id != "gmail-email" {
                bail!("gmail email request must use provider_id `gmail-email`");
            }
        }
    }
    Ok(hint)
}

pub fn build_email_execution_plan(
    config: &OAuthBrokerConfig,
    tenant: &TenantCtx,
    request: &EmailSendRequest,
) -> Result<EmailExecutionPlan> {
    let hint = required_oauth_hint(request)?;
    let token_request =
        build_resource_token_request(config, tenant, &hint.provider_id, &hint.scopes)?;
    let http = build_email_http_execution(request)?;
    Ok(EmailExecutionPlan {
        token_request,
        http,
    })
}

pub fn build_email_http_payload(request: &EmailSendRequest) -> Result<Value> {
    match request.provider {
        EmailProviderKind::MsGraph => Ok(request.payload.clone()),
        EmailProviderKind::Gmail => {
            let message = request
                .payload
                .get("message")
                .and_then(Value::as_object)
                .ok_or_else(|| anyhow!("gmail email request missing `message` object"))?;
            let subject = message
                .get("subject")
                .and_then(Value::as_str)
                .ok_or_else(|| anyhow!("gmail email request missing `message.subject`"))?;
            let body = message
                .get("body")
                .and_then(Value::as_str)
                .ok_or_else(|| anyhow!("gmail email request missing `message.body`"))?;
            let to = string_list(message.get("to"), "message.to")?;
            let cc = optional_string_list(message.get("cc"));
            let bcc = optional_string_list(message.get("bcc"));
            let from = message.get("from").and_then(Value::as_str);
            let raw = build_gmail_raw_message(from, &to, &cc, &bcc, subject, body)?;
            // The Gmail API requires base64url (RFC 4648 section 5), not the
            // standard alphabet.
            Ok(json!({
                "raw": base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes())
            }))
        }
    }
}

pub async fn execute_email_request(
    client: &reqwest::Client,
    access_token: &str,
    request: &EmailSendRequest,
) -> Result<()> {
    let plan = build_email_http_execution(request)?;
    let url = Url::parse(&plan.url).context("invalid email provider URL")?;
    if url.scheme() != "https" {
        bail!(
            "email provider URL must use https, got scheme `{}`",
            url.scheme()
        );
    }
    if !url.username().is_empty() || url.password().is_some() {
        bail!("email provider URL must not include URL credentials");
    }
    if url.query().is_some() || url.fragment().is_some() {
        bail!("email provider URL must not include query or fragment components");
    }
    let payload = build_email_http_payload(request)?;
    client
        .post(url)
        .bearer_auth(access_token)
        .json(&payload)
        .send()
        .await?
        .error_for_status()?;
    Ok(())
}

fn string_list(value: Option<&Value>, field: &str) -> Result<Vec<String>> {
    value
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(ToOwned::to_owned))
                .collect::<Vec<_>>()
        })
        .filter(|items| !items.is_empty())
        .ok_or_else(|| anyhow!("gmail email request missing `{field}`"))
}

fn optional_string_list(value: Option<&Value>) -> Vec<String> {
    value
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(ToOwned::to_owned))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default()
}

/// Reject CR/LF in a header value: they would let a caller-supplied field
/// inject extra headers (or a body) into the message.
fn checked_header_value<'a>(field: &str, value: &'a str) -> Result<&'a str> {
    if value.contains(['\r', '\n']) {
        bail!("gmail email request field `{field}` must not contain CR or LF");
    }
    Ok(value)
}

/// RFC 2047 encoded-word form (`=?UTF-8?B?...?=`) for a non-ASCII subject;
/// ASCII subjects pass through unchanged. Long subjects are split into several
/// encoded words, each within the 75-character limit.
fn encode_subject(subject: &str) -> String {
    if subject.is_ascii() {
        return subject.to_string();
    }
    // 45 raw bytes -> 60 base64 chars; + 12 chars of framing = 72 <= 75.
    const MAX_CHUNK_BYTES: usize = 45;
    let mut words = Vec::new();
    let mut chunk = String::new();
    for ch in subject.chars() {
        if chunk.len() + ch.len_utf8() > MAX_CHUNK_BYTES {
            words.push(encode_word(&chunk));
            chunk.clear();
        }
        chunk.push(ch);
    }
    if !chunk.is_empty() {
        words.push(encode_word(&chunk));
    }
    words.join("\r\n ")
}

fn encode_word(chunk: &str) -> String {
    format!(
        "=?UTF-8?B?{}?=",
        base64::engine::general_purpose::STANDARD.encode(chunk.as_bytes())
    )
}

fn build_gmail_raw_message(
    from: Option<&str>,
    to: &[String],
    cc: &[String],
    bcc: &[String],
    subject: &str,
    body: &str,
) -> Result<String> {
    let join_checked = |field: &str, values: &[String]| -> Result<String> {
        for value in values {
            checked_header_value(field, value)?;
        }
        Ok(values.join(", "))
    };
    let mut lines = vec!["MIME-Version: 1.0".to_string()];
    if let Some(from) = from.filter(|value| !value.trim().is_empty()) {
        lines.push(format!("From: {}", checked_header_value("from", from)?));
    }
    lines.push(format!("To: {}", join_checked("to", to)?));
    if !cc.is_empty() {
        lines.push(format!("Cc: {}", join_checked("cc", cc)?));
    }
    if !bcc.is_empty() {
        lines.push(format!("Bcc: {}", join_checked("bcc", bcc)?));
    }
    lines.push(format!(
        "Subject: {}",
        encode_subject(checked_header_value("subject", subject)?)
    ));
    lines.push("Content-Type: text/plain; charset=utf-8".into());
    lines.push("Content-Transfer-Encoding: 8bit".into());
    lines.push(String::new());
    lines.push(body.to_string());
    Ok(lines.join("\r\n"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::oauth::OAuthBrokerConfig;
    use greentic_types::{EnvId, TeamId, TenantId};
    use serde_json::json;
    use std::str::FromStr;

    fn sample_tenant() -> TenantCtx {
        TenantCtx::new(
            EnvId::from_str("dev").unwrap(),
            TenantId::from_str("acme").unwrap(),
        )
        .with_team(Some(TeamId::from_str("core").unwrap()))
    }

    #[test]
    fn parses_msgraph_request_and_builds_execution_target() {
        let value = json!({
            "provider": "msgraph",
            "payload": {
                "message": {
                    "subject": "Hello",
                    "body": { "contentType": "HTML", "content": "<p>Hi</p>" },
                    "toRecipients": [{ "emailAddress": { "address": "to@example.com" } }],
                    "from": { "emailAddress": { "address": "sender@example.com" } }
                },
                "saveToSentItems": false
            },
            "oauth": {
                "provider_id": "msgraph-email",
                "flow": "client_credentials",
                "scopes": ["https://graph.microsoft.com/.default"]
            },
            "secret_events": []
        });

        let request = parse_email_send_request(&value).expect("parse request");
        let hint = required_oauth_hint(&request).expect("oauth hint");
        let execution = build_email_http_execution(&request).expect("execution");

        assert_eq!(hint.provider_id, "msgraph-email");
        assert_eq!(execution.method, "POST");
        assert_eq!(
            execution.url,
            "https://graph.microsoft.com/v1.0/users/sender@example.com/sendMail"
        );
    }

    #[test]
    fn gmail_request_uses_me_send_endpoint() {
        let value = json!({
            "provider": "gmail",
            "payload": {
                "message": {
                    "subject": "Hello",
                    "body": "Hi",
                    "to": ["to@example.com"]
                }
            },
            "oauth": {
                "provider_id": "gmail-email",
                "flow": "refresh_token",
                "scopes": ["https://www.googleapis.com/auth/gmail.send"]
            },
            "secret_events": []
        });

        let request = parse_email_send_request(&value).expect("parse request");
        let hint = required_oauth_hint(&request).expect("oauth hint");
        let execution = build_email_http_execution(&request).expect("execution");

        assert_eq!(hint.provider_id, "gmail-email");
        assert_eq!(execution.method, "POST");
        assert_eq!(
            execution.url,
            "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
        );
    }

    #[test]
    fn builds_msgraph_execution_plan() {
        let value = json!({
            "provider": "msgraph",
            "payload": {
                "message": {
                    "subject": "Hello",
                    "body": { "contentType": "HTML", "content": "<p>Hi</p>" },
                    "toRecipients": [{ "emailAddress": { "address": "to@example.com" } }],
                    "from": { "emailAddress": { "address": "sender@example.com" } }
                },
                "saveToSentItems": false
            },
            "oauth": {
                "provider_id": "msgraph-email",
                "flow": "client_credentials",
                "scopes": ["https://graph.microsoft.com/.default"]
            },
            "secret_events": []
        });

        let request = parse_email_send_request(&value).expect("parse request");
        let cfg = OAuthBrokerConfig::new("https://oauth.example", "nats://localhost:4222");
        let tenant = sample_tenant();
        let plan = build_email_execution_plan(&cfg, &tenant, &request).expect("plan");

        assert_eq!(plan.token_request.http_base_url, "https://oauth.example");
        assert_eq!(plan.token_request.resource_id, "msgraph-email");
        assert_eq!(
            plan.token_request.scopes,
            vec!["https://graph.microsoft.com/.default".to_string()]
        );
        assert_eq!(plan.http.method, "POST");
        assert_eq!(
            plan.http.url,
            "https://graph.microsoft.com/v1.0/users/sender@example.com/sendMail"
        );
    }

    #[test]
    fn msgraph_payload_is_forwarded_as_is() {
        let value = json!({
            "provider": "msgraph",
            "payload": {
                "message": {
                    "subject": "Hello",
                    "body": { "contentType": "HTML", "content": "<p>Hi</p>" },
                    "toRecipients": [{ "emailAddress": { "address": "to@example.com" } }],
                    "from": { "emailAddress": { "address": "sender@example.com" } }
                },
                "saveToSentItems": false
            },
            "oauth": {
                "provider_id": "msgraph-email",
                "flow": "client_credentials",
                "scopes": ["https://graph.microsoft.com/.default"]
            },
            "secret_events": []
        });
        let request = parse_email_send_request(&value).expect("parse request");
        let payload = build_email_http_payload(&request).expect("payload");
        assert_eq!(payload, request.payload);
    }

    #[test]
    fn gmail_raw_is_base64url_without_standard_alphabet_characters() {
        // `>>>???` encodes to `Pj4-Pz8_` in base64url (`+`/`/` in standard).
        let raw = build_gmail_raw_message(
            None,
            &["to@example.com".to_string()],
            &[],
            &[],
            "s",
            ">>>???~~~",
        )
        .unwrap();
        let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes());
        assert!(!encoded.contains(['+', '/', '=']));
        assert!(encoded.contains(['-', '_']) || !encoded.is_empty());
    }

    #[test]
    fn header_values_with_crlf_are_rejected() {
        let to = vec!["a@example.com".to_string()];
        let injected = build_gmail_raw_message(None, &to, &[], &[], "hi\r\nBcc: evil@x.com", "b");
        assert!(injected.is_err());
        let bad_to = vec!["a@example.com\nBcc: evil@x.com".to_string()];
        assert!(build_gmail_raw_message(None, &bad_to, &[], &[], "s", "b").is_err());
        assert!(build_gmail_raw_message(Some("x\ry"), &to, &[], &[], "s", "b").is_err());
    }

    #[test]
    fn non_ascii_subject_is_rfc2047_encoded() {
        assert_eq!(encode_subject("Hello"), "Hello");
        let encoded = encode_subject("Halo dunia \u{1F30F} caf\u{e9}");
        assert!(encoded.starts_with("=?UTF-8?B?") && encoded.ends_with("?="));
        assert!(encoded.is_ascii());
        let long = encode_subject(&"\u{e9}".repeat(100));
        for word in long.split("\r\n ") {
            assert!(word.len() <= 75, "encoded word too long: {}", word.len());
        }
    }

    #[test]
    fn gmail_payload_is_encoded_as_raw_message() {
        let value = json!({
            "provider": "gmail",
            "payload": {
                "message": {
                    "subject": "Hello",
                    "body": "Hi there",
                    "to": ["to@example.com"],
                    "cc": ["cc@example.com"],
                    "bcc": ["bcc@example.com"],
                    "from": "sender@example.com"
                }
            },
            "oauth": {
                "provider_id": "gmail-email",
                "flow": "refresh_token",
                "scopes": ["https://www.googleapis.com/auth/gmail.send"]
            },
            "secret_events": []
        });

        let request = parse_email_send_request(&value).expect("parse request");
        let payload = build_email_http_payload(&request).expect("payload");
        let raw = payload
            .get("raw")
            .and_then(Value::as_str)
            .expect("raw field");
        let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(raw.as_bytes())
            .expect("valid base64");
        let decoded = String::from_utf8(decoded).expect("utf8");

        assert!(decoded.contains("From: sender@example.com"));
        assert!(decoded.contains("To: to@example.com"));
        assert!(decoded.contains("Cc: cc@example.com"));
        assert!(decoded.contains("Bcc: bcc@example.com"));
        assert!(decoded.contains("Subject: Hello"));
        assert!(decoded.ends_with("Hi there"));
    }

    #[test]
    fn msgraph_requires_sender_identity() {
        let value = json!({
            "provider": "msgraph",
            "payload": {
                "message": {
                    "subject": "Hello"
                }
            },
            "oauth": {
                "provider_id": "msgraph-email",
                "flow": "client_credentials",
                "scopes": ["https://graph.microsoft.com/.default"]
            }
        });

        let request = parse_email_send_request(&value).expect("parse request");
        let err = build_email_http_execution(&request).expect_err("missing sender should fail");
        assert!(
            err.to_string()
                .contains("message.from.emailAddress.address")
        );
    }

    #[test]
    fn msgraph_rejects_sender_with_url_delimiters() {
        let value = json!({
            "provider": "msgraph",
            "payload": {
                "message": {
                    "subject": "Hello",
                    "from": { "emailAddress": { "address": "sender@example.com?debug=1" } }
                }
            },
            "oauth": {
                "provider_id": "msgraph-email",
                "flow": "client_credentials",
                "scopes": ["https://graph.microsoft.com/.default"]
            }
        });

        let request = parse_email_send_request(&value).expect("parse request");
        let err = build_email_http_execution(&request).expect_err("invalid sender should fail");
        assert!(err.to_string().contains("must not contain '/', '?' or '#'"));
    }

    #[test]
    fn msgraph_rejects_sender_path_tricks() {
        for bad in [
            "..",
            ".",
            "a\\b@example.com",
            "a%2fb@example.com",
            "a b@example.com",
        ] {
            let value = json!({
                "provider": "msgraph",
                "payload": { "message": { "from": { "emailAddress": { "address": bad } } } },
                "oauth": {
                    "provider_id": "msgraph-email",
                    "flow": "client_credentials",
                    "scopes": []
                }
            });
            let request = parse_email_send_request(&value).expect("parse request");
            assert!(
                build_email_http_execution(&request).is_err(),
                "sender {bad:?} must be rejected"
            );
        }
    }
}