atomic-integration-proxy 0.4.1

OAuth/catalog integration proxy (pinned OpenAPI catalog, connections owned by Atomic agents, Atomic v2 request signatures, delegations and frame capabilities) used by Atomic Server and LocalThought
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Minimal, dependency-free HTML rendering. The proxy has no accounts and
//! no login (issue #54): the only pages are the landing page and the
//! per-platform consent screen.
//!
//! Every value that reaches the HTML goes through [`escape`]: the operator
//! name and URL come from the environment, the host from `BASE_URL`, and the
//! platform, destination and CSRF token from the request.

use crate::config::DEFAULT_OPERATOR_NAME;

/// Who runs this proxy and where it lives, as the pages show it:
/// `OPERATOR_NAME`, `OPERATOR_URL`, and the host of `BASE_URL`.
#[derive(Clone, Debug)]
pub(crate) struct Operator {
    name: String,
    url: Option<String>,
    host: String,
}

impl Operator {
    pub(crate) fn new(name: &str, url: Option<&str>, host: &str) -> Self {
        Self {
            name: name.to_owned(),
            url: url.map(str::to_owned),
            host: host.to_owned(),
        }
    }

    pub(crate) fn from_config(config: &crate::Config) -> Self {
        Self::new(
            &crate::config::operator_name(Some(&config.operator_name)),
            config.operator_url.as_deref(),
            &config.public_host(),
        )
    }

    /// Whether `OPERATOR_NAME` named someone, rather than the neutral default.
    fn is_named(&self) -> bool {
        self.name != DEFAULT_OPERATOR_NAME
    }

    /// A heading-sized name, escaped: the operator's, or "Integration proxy".
    fn title(&self) -> String {
        if self.is_named() {
            escape(&self.name)
        } else {
            "Integration proxy".to_owned()
        }
    }

    /// The operator's name, escaped and linked to `OPERATOR_URL` when set.
    fn linked_name(&self) -> String {
        match &self.url {
            Some(url) => format!(
                r#"<a href="{}" rel="noopener noreferrer">{}</a>"#,
                escape(url),
                escape(&self.name)
            ),
            None => escape(&self.name),
        }
    }
}

/// The landing page at `/`.
pub fn render_home(operator: &Operator) -> String {
    let brand = match &operator.url {
        Some(url) => format!(
            r#"<a class="brand" href="{}" rel="noopener noreferrer">{}</a>"#,
            escape(url),
            operator.title()
        ),
        None => format!(r#"<a class="brand" href="/">{}</a>"#, operator.title()),
    };
    let run_by = if operator.is_named() {
        operator.linked_name()
    } else {
        format!(
            "the operator of <strong>{}</strong>",
            escape(&operator.host)
        )
    };
    fill(
        include_str!("../static/index.html"),
        &[
            ("title", &operator.title()),
            ("brand", &brand),
            ("host", &escape(&operator.host)),
            ("operator", &run_by),
        ],
    )
}

/// Replaces each `{{key}}` in `template` with its already-escaped value, in
/// one pass, so a value can never introduce a placeholder of its own. An
/// unknown key is left as it is (the tests look for a leftover `{{`).
fn fill(template: &str, values: &[(&str, &str)]) -> String {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(start) = rest.find("{{") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let found = after.find("}}").and_then(|end| {
            values
                .iter()
                .find(|(key, _)| *key == &after[..end])
                .map(|(_, value)| (end, *value))
        });
        match found {
            Some((end, value)) => {
                out.push_str(value);
                rest = &after[end + 2..];
            }
            None => {
                out.push_str("{{");
                rest = after;
            }
        }
    }
    out.push_str(rest);
    out
}

/// What the consent screen asks for, from the platform's security scheme.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConnectKind<'a> {
    /// Continue to the provider's own authorization.
    OAuth,
    /// Paste an API key here.
    ApiKey(ApiKeyHelp<'a>),
    /// Nothing: the platform's document requires no security.
    NoCredential,
}

/// What the key field says around itself, from the platform's apiKey scheme
/// (`description`, `x-api-key-details.helpUrl`) and the last attempt.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ApiKeyHelp<'a> {
    /// The scheme's `description`, shown as plain text.
    pub description: Option<&'a str>,
    /// An `https` page where the key is made; a link the person may follow,
    /// never a redirect.
    pub help_url: Option<&'a str>,
    /// Why the last key was not accepted, when the page asks again.
    pub problem: Option<&'a str>,
    /// What the pasted secret is called on the page.
    pub secret: SecretName,
    /// For an `http` `basic` scheme whose username the person types
    /// (`basicCredentials.usernameLabel`): that field's label, plain text.
    pub username_label: Option<&'a str>,
}

/// What the consent page calls the secret it asks for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SecretName {
    /// An `apiKey` scheme's key.
    #[default]
    ApiKey,
    /// An `http` `bearer` or `basic` scheme's token.
    ApiToken,
}

impl SecretName {
    fn text(self) -> &'static str {
        match self {
            Self::ApiKey => "API key",
            Self::ApiToken => "API token",
        }
    }
}

/// Renders the consent screen for one selected platform. `destination` is
/// where the browser returns to (an origin, or the app's deep link).
pub fn render_platform_connect(
    operator: &Operator,
    platform: &str,
    destination: &str,
    csrf: &str,
    kind: ConnectKind<'_>,
) -> String {
    let (api_key_field, button_label) = match kind {
        ConnectKind::ApiKey(help) => (
            api_key_field(platform, help),
            format!("Connect {}", escape(&platform_label(platform))),
        ),
        ConnectKind::OAuth | ConnectKind::NoCredential => (
            String::new(),
            format!(
                "Use {} to sync {} with this destination",
                escape(&operator.name),
                escape(&platform_label(platform))
            ),
        ),
    };
    let what = if kind == ConnectKind::NoCredential {
        "{platform} needs no account: this proxy reads it without a credential and stores none. Connecting only records the connection."
    } else {
        "Connecting lets this proxy use your {platform} account on your behalf."
    };
    let run_by = if operator.is_named() {
        operator.linked_name()
    } else {
        "an operator it does not name".to_owned()
    };
    let body = format!(
        r#"
        <div class="card">
          <h1>Connect {platform}</h1>
          <p class="operator">Integration proxy <strong>{host}</strong>, run by {run_by}.</p>
          <p>Destination: <span class="email">{destination}</span></p>
          <p class="secret-help">{what} The destination finishes connecting by signing with your Atomic key; it becomes the connection's owner.</p>
          <form method="post" action="/connect/authorize">
            <input type="hidden" name="csrf" value="{csrf}" />
            {api_key_field}
            <button class="button" type="submit">{button_label}</button>
          </form>
        </div>
        <script>{script}</script>
        "#,
        script = CONSENT_SCRIPT,
        platform = escape(&platform_label(platform)),
        host = escape(&operator.host),
        destination = escape(destination),
        csrf = escape(csrf),
        what = what.replace("{platform}", &escape(&platform_label(platform))),
    );
    page(
        operator,
        &format!("Connect {}", platform_label(platform)),
        "",
        &body,
    )
}

/// The key field and the text around it. The help link opens in a new tab
/// and is never followed for the person (openapi-extensions/spec/api-key-details).
fn api_key_field(platform: &str, help: ApiKeyHelp<'_>) -> String {
    let mut html = String::new();
    if let Some(problem) = help.problem {
        html.push_str(&format!(
            r#"<p class="problem" role="alert">{}</p>"#,
            escape(problem)
        ));
    }
    html.push_str(&format!(
        r#"<p class="secret-help">{}</p>"#,
        escape(
            help.description
                .unwrap_or("Find this in your account settings on the platform's own site.")
        )
    ));
    if let Some(url) = help.help_url {
        html.push_str(&format!(
            r#"<p class="secret-help"><a href="{}" target="_blank" rel="noopener noreferrer">Where to find your {} {}</a> (opens in a new tab)</p>"#,
            escape(url),
            escape(&platform_label(platform)),
            help.secret.text()
        ));
    }
    let (noun, name) = match help.secret {
        SecretName::ApiKey => ("key", "API key"),
        SecretName::ApiToken => ("token", "API token"),
    };
    html.push_str(&format!(
        r#"<p class="secret-help">The {noun} is stored encrypted on this proxy and never sent back to the destination.</p>"#
    ));
    // A typed username is not a secret: a plain text field, before the
    // token, labelled by the scheme's declaration (escaped).
    if let Some(label) = help.username_label {
        html.push_str(&format!(
            r#"
               <input class="button" style="background:white;color:#202124;border:1px solid #ccc" type="text" name="username" autocomplete="off" placeholder="{label}" aria-label="{label}" required />"#,
            label = escape(label)
        ));
    }
    html.push_str(&format!(
        r#"
               <input class="button" style="background:white;color:#202124;border:1px solid #ccc" type="password" name="api_key" autocomplete="off" placeholder="{name}" required />"#
    ));
    html
}

/// The consent page's only script: it disables the approve button once the
/// form is submitted, so a double click cannot send a second approval that
/// would find the first one's single-use consent already spent. A page
/// restored from the back/forward cache gets its button back (approving
/// again then says it was already approved). The consent page's CSP allows
/// exactly this text by hash ([`consent_script_hash`]); nothing else runs.
pub(crate) const CONSENT_SCRIPT: &str = r#"(function(){var f=document.forms[0];if(!f)return;var b=f.querySelector('button[type="submit"]');f.addEventListener('submit',function(e){if(f.getAttribute('data-sent')){e.preventDefault();return;}f.setAttribute('data-sent','1');if(b)b.disabled=true;});window.addEventListener('pageshow',function(e){if(e.persisted){f.removeAttribute('data-sent');if(b)b.disabled=false;}});})();"#;

/// The CSP source (`'sha256-โ€ฆ'`) that allows [`CONSENT_SCRIPT`] and nothing
/// else.
pub(crate) fn consent_script_hash() -> String {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use sha2::{Digest, Sha256};
    format!(
        "'sha256-{}'",
        STANDARD.encode(Sha256::digest(CONSENT_SCRIPT.as_bytes()))
    )
}

/// The page `POST /connect/authorize` answers for an OAuth platform: a
/// `<meta>` refresh to `authorization_url`, with the same address as a
/// button in case the browser does not follow refreshes.
///
/// It is a page rather than a `303` because a form submission's whole
/// redirect chain is held to the consent page's CSP `form-action`: a
/// provider whose authorization endpoint first redirects to another origin
/// of its own (an API host handing over to a separate sign-in host) would be
/// blocked there. A navigation this page starts is not a form submission, so
/// `form-action` does not govern it, and the proxy never needs to know which
/// origins a provider passes through.
pub fn render_oauth_continue(
    operator: &Operator,
    platform: &str,
    authorization_url: &str,
) -> String {
    let destination = url::Url::parse(authorization_url)
        .ok()
        .and_then(|url| url.host_str().map(str::to_owned))
        .unwrap_or_default();
    let head = format!(
        r#"<meta http-equiv="refresh" content="0;url={url}" />
  <meta name="referrer" content="no-referrer" />"#,
        url = escape(authorization_url),
    );
    let body = format!(
        r#"
        <div class="card">
          <h1>Continue to {platform}</h1>
          <p>Taking you to <strong>{destination}</strong> to authorize the connection.</p>
          <a class="button" href="{url}" rel="noreferrer">Continue to {platform}</a>
          <p class="secret-help">If nothing happens, use the button. Approving again on the previous page will not work: each approval is used once.</p>
        </div>
        "#,
        platform = escape(&platform_label(platform)),
        destination = escape(&destination),
        url = escape(authorization_url),
    );
    page(
        operator,
        &format!("Continue to {}", platform_label(platform)),
        &head,
        &body,
    )
}

pub(crate) fn platform_label(platform: &str) -> String {
    platform
        .split('-')
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// `head` is trusted, already-escaped markup for `<head>` (or empty).
fn page(operator: &Operator, heading: &str, head: &str, body: &str) -> String {
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  {head}
  <title>{heading} ยท {host}</title>
  <link rel="icon" type="image/png" href="/logo.png" />
  <style>
    :root {{ color-scheme: light dark; }}
    body {{
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      display: flex;
      min-height: 100vh;
      align-items: center;
      justify-content: center;
      margin: 0;
      background: #f5f5f7;
    }}
    .card {{
      background: white;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12);
      padding: 2.5rem;
      text-align: center;
      max-width: 24rem;
    }}
    .avatar {{
      width: 4rem;
      height: 4rem;
      border-radius: 50%;
      margin-bottom: 1rem;
    }}
    .email {{ color: #666; margin-top: -0.5rem; }}
    .secret-help {{ color: #666; font-size: 0.85rem; }}
    .problem {{ color: #b3261e; font-weight: 600; }}
    .operator {{ overflow-wrap: anywhere; }}
    .operator a {{ color: inherit; }}
    .button {{
      display: inline-block;
      margin-top: 1rem;
      padding: 0.6rem 1.4rem;
      background: #1a73e8;
      color: white;
      text-decoration: none;
      border-radius: 6px;
      font-weight: 600;
      border: none;
      cursor: pointer;
      font-size: 1rem;
    }}
    .button-secondary {{ background: #5f6368; }}
    @media (prefers-color-scheme: dark) {{
      body {{ background: #202124; }}
      .card {{ background: #303134; color: #e8eaed; }}
      .email {{ color: #9aa0a6; }}
      .secret-help {{ color: #9aa0a6; }}
      .problem {{ color: #f2b8b5; }}
    }}
  </style>
</head>
<body>
  <main>
    <a href="/" aria-label="{title} home" style="display:block;text-align:center;margin-bottom:1rem"><img src="/logo.png" alt="" width="80" height="80" style="border-radius:8px" /></a>
    {body}
  </main>
</body>
</html>"#,
        heading = escape(heading),
        head = head,
        host = escape(&operator.host),
        title = operator.title(),
        body = body
    )
}

/// Escapes text for an HTML text node or a double- or single-quoted
/// attribute value.
fn escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

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

    fn unnamed() -> Operator {
        Operator::new(DEFAULT_OPERATOR_NAME, None, "proxy.example.org")
    }

    fn named() -> Operator {
        Operator::new(
            "Atomic Data",
            Some("https://atomic.place/"),
            "integrations.atomic.place",
        )
    }

    #[test]
    fn home_has_no_login() {
        for operator in [unnamed(), named()] {
            let html = render_home(&operator);
            assert!(!html.contains("/auth/login"));
            assert!(!html.contains("{{"));
            assert!(!html.contains("LocalThought"));
        }
    }

    #[test]
    fn home_names_the_operator_and_host() {
        let html = render_home(&named());
        assert!(html.contains("<title>Atomic Data ยท Connect your tools</title>"));
        assert!(html.contains(
            r#"<a class="brand" href="https://atomic.place/" rel="noopener noreferrer">Atomic Data</a>"#
        ));
        assert!(html.contains("Integrations ยท integrations.atomic.place"));
        assert!(html.contains(
            r#"It is run by <a href="https://atomic.place/" rel="noopener noreferrer">Atomic Data</a>."#
        ));
    }

    #[test]
    fn home_without_an_operator_name_stays_neutral() {
        let html = render_home(&unnamed());
        assert!(html.contains("<title>Integration proxy ยท Connect your tools</title>"));
        assert!(html.contains(r#"<a class="brand" href="/">Integration proxy</a>"#));
        assert!(html.contains("It is run by the operator of <strong>proxy.example.org</strong>."));
    }

    #[test]
    fn home_escapes_the_operator_name_url_and_host() {
        let html = render_home(&Operator::new(
            r#"<script>alert("x")</script> & {{host}}"#,
            Some(r#"https://evil.example/"><script>"#),
            "h<o>st",
        ));
        assert!(!html.contains("<script>"));
        assert!(html.contains("&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt; &amp; {{host}}"));
        assert!(html.contains(r#"href="https://evil.example/&quot;&gt;&lt;script&gt;""#));
        assert!(html.contains("h&lt;o&gt;st"));
    }

    #[test]
    fn platform_connect_shows_one_selected_platform_and_escapes_fields() {
        let html = render_platform_connect(
            &unnamed(),
            "google-calendar",
            "https://hub.example/\"><script>alert(1)</script>",
            "csrf&<\"'",
            ConnectKind::OAuth,
        );
        assert!(html.contains("Google Calendar"));
        assert!(html
            .contains("Use this integration proxy to sync Google Calendar with this destination"));
        assert_eq!(html.matches(r#"action="/connect/authorize""#).count(), 1);
        assert!(html.contains("name=\"csrf\" value=\"csrf&amp;&lt;&quot;&#39;\""));
        assert!(!html.contains("<script>alert"));
        assert_eq!(html.matches("<script>").count(), 1, "only CONSENT_SCRIPT");
        assert!(!html.contains("api_key"));
        assert!(!html.contains("LocalThought"));
        assert!(!html.to_lowercase().contains("log in"));
    }

    #[test]
    fn consent_page_shows_the_proxy_host_and_operator() {
        let html = render_platform_connect(
            &named(),
            "google-calendar",
            "https://hub.example",
            "csrf",
            ConnectKind::OAuth,
        );
        assert!(html.contains("<title>Connect Google Calendar ยท integrations.atomic.place</title>"));
        assert!(html.contains(
            r#"Integration proxy <strong>integrations.atomic.place</strong>, run by <a href="https://atomic.place/" rel="noopener noreferrer">Atomic Data</a>."#
        ));
        assert!(html.contains("Use Atomic Data to sync Google Calendar with this destination"));
        assert!(html.contains(r#"aria-label="Atomic Data home""#));
    }

    #[test]
    fn consent_page_without_an_operator_name_still_shows_the_host() {
        let html = render_platform_connect(
            &unnamed(),
            "clockify",
            "https://hub.example",
            "csrf",
            ConnectKind::ApiKey(ApiKeyHelp::default()),
        );
        assert!(html.contains(
            "Integration proxy <strong>proxy.example.org</strong>, run by an operator it does not name."
        ));
        assert!(html.contains(r#"aria-label="Integration proxy home""#));
    }

    #[test]
    fn consent_page_escapes_the_operator_name_url_and_host() {
        let html = render_platform_connect(
            &Operator::new(
                "Evil <img src=x onerror=alert(1)> 'Co'",
                Some(r#"https://evil.example/" onmouseover="alert(1)"#),
                r#"host"><script>"#,
            ),
            "google-calendar",
            "https://hub.example",
            "csrf",
            ConnectKind::OAuth,
        );
        assert_eq!(html.matches("<script>").count(), 1, "only CONSENT_SCRIPT");
        assert!(!html.contains(r#""><script>"#));
        assert!(!html.contains("<img src=x"));
        assert!(!html.contains(r#"" onmouseover="#));
        assert!(html.contains("Evil &lt;img src=x onerror=alert(1)&gt; &#39;Co&#39;"));
        assert!(html.contains(r#"href="https://evil.example/&quot; onmouseover=&quot;alert(1)""#));
        assert!(html.contains("<strong>host&quot;&gt;&lt;script&gt;</strong>"));
        assert!(
            html.contains("<title>Connect Google Calendar ยท host&quot;&gt;&lt;script&gt;</title>")
        );
    }

    #[test]
    fn api_key_platforms_ask_for_the_key_on_the_proxy_page() {
        let html = render_platform_connect(
            &unnamed(),
            "clockify",
            "https://hub.example",
            "csrf",
            ConnectKind::ApiKey(ApiKeyHelp::default()),
        );
        assert!(html.contains(r#"name="api_key""#));
        assert!(html.contains("Connect Clockify"));
        assert!(html.contains("Find this in your account settings"));
        assert!(!html.contains("<a href=\"https://"));
        assert!(!html.contains(r#"class="problem""#));
    }

    #[test]
    fn api_key_page_shows_the_description_help_link_and_problem_escaped() {
        let html = render_platform_connect(
            &unnamed(),
            "clockify",
            "https://hub.example",
            "csrf",
            ConnectKind::ApiKey(ApiKeyHelp {
                description: Some("Made under <b>Preferences</b> & Advanced."),
                help_url: Some(r#"https://help.example/keys?a=1&b="x""#),
                problem: Some("Clockify did not accept that key <again>."),
                ..ApiKeyHelp::default()
            }),
        );
        assert!(html.contains("Made under &lt;b&gt;Preferences&lt;/b&gt; &amp; Advanced."));
        assert!(!html.contains("Find this in your account settings"));
        assert!(html.contains(
            r#"<a href="https://help.example/keys?a=1&amp;b=&quot;x&quot;" target="_blank" rel="noopener noreferrer">Where to find your Clockify API key</a>"#
        ));
        assert!(html.contains(
            r#"<p class="problem" role="alert">Clockify did not accept that key &lt;again&gt;.</p>"#
        ));
        // The link is only a link: no refresh, and still the one script.
        assert!(!html.contains("http-equiv"));
        assert_eq!(html.matches("<script>").count(), 1);
    }

    #[test]
    fn no_credential_platforms_ask_for_nothing_and_say_so() {
        let html = render_platform_connect(
            &unnamed(),
            "pets",
            "https://hub.example",
            "csrf",
            ConnectKind::NoCredential,
        );
        assert!(!html.contains("api_key"));
        assert!(html.contains(
            "Pets needs no account: this proxy reads it without a credential and stores none."
        ));
        assert!(!html.contains("use your Pets account"));
        assert!(!html.contains("{platform}"));
        assert!(html.contains("Use this integration proxy to sync Pets with this destination"));
        assert!(html.contains(&format!("<script>{CONSENT_SCRIPT}</script>")));
    }

    #[test]
    fn oauth_continue_page_refreshes_to_the_provider_and_links_it() {
        let url = "https://api.provider.example/v1/oauth/authorize?client_id=c&state=s&scope=a+b";
        let html = render_oauth_continue(&named(), "notion", url);
        let escaped =
            "https://api.provider.example/v1/oauth/authorize?client_id=c&amp;state=s&amp;scope=a+b";
        assert!(html.contains(&format!(
            r#"<meta http-equiv="refresh" content="0;url={escaped}" />"#
        )));
        assert!(html.contains(&format!(
            r#"<a class="button" href="{escaped}" rel="noreferrer">Continue to Notion</a>"#
        )));
        assert!(html.contains(r#"<meta name="referrer" content="no-referrer" />"#));
        assert!(html.contains("<strong>api.provider.example</strong>"));
        assert!(html.contains("<title>Continue to Notion ยท integrations.atomic.place</title>"));
        assert!(!html.contains("<script"));
        assert!(!html.contains("<form"));
    }

    #[test]
    fn oauth_continue_page_escapes_the_address() {
        let html = render_oauth_continue(
            &unnamed(),
            "x",
            r#"https://auth.example/a?b="><script>alert(1)</script>"#,
        );
        assert!(!html.contains("<script"));
        assert!(html.contains("&quot;&gt;&lt;script&gt;"));
    }

    #[test]
    fn the_consent_script_hash_is_its_sha256() {
        // Independently of the helper: base64 of SHA-256 over the exact text.
        use base64::{engine::general_purpose::STANDARD, Engine as _};
        use sha2::{Digest, Sha256};
        let expected = STANDARD.encode(Sha256::digest(CONSENT_SCRIPT.as_bytes()));
        assert_eq!(consent_script_hash(), format!("'sha256-{expected}'"));
        let html = render_platform_connect(
            &unnamed(),
            "clockify",
            "https://hub.example",
            "csrf",
            ConnectKind::ApiKey(ApiKeyHelp::default()),
        );
        assert!(html.contains(&format!("<script>{CONSENT_SCRIPT}</script>")));
    }

    #[test]
    fn fill_replaces_known_placeholders_once() {
        assert_eq!(
            fill("a {{x}} b {{y}} {{z", &[("x", "{{y}}"), ("y", "2")]),
            "a {{y}} b 2 {{z"
        );
    }
}