anodizer-stage-release 0.2.0

Release stage for the anodizer release tool — creates GitHub releases and uploads artifacts
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
706
707
708
709
710
711
712
713
//! Gitea release backend — creates releases, uploads assets via the Gitea API.
//!
//! Gitea's release API is simpler than GitLab's: assets are uploaded directly
//! via multipart POST to the release endpoint (no package registry indirection).
//! Draft support is limited (Gitea has it but the GoReleaser client treats
//! `PublishRelease` as a no-op), so we follow that same approach.
//!
//! Reference: GoReleaser `internal/client/gitea.go`.
//!
//! ## Note on commit 4a9d25f (default-branch fallback)
//!
//! GoReleaser commit 4a9d25f fixes a `CreateFile` path that hard-coded
//! `master` when the server-side default-branch lookup failed. Anodizer
//! does not call Gitea's `repos/{owner}/{repo}/contents/{path}` create-file
//! endpoint — every publisher (homebrew, scoop, krew, nix, aur, …) targets
//! Gitea via `git clone` + `git push` over SSH/HTTPS, not via the REST
//! contents API. The `branch`-defaulting bug therefore has no surface in
//! anodizer (n/a-by-construction).

use std::path::Path;

use anodizer_core::redact::redact_bearer_tokens;
use anodizer_core::retry::{RetryPolicy, SuccessClass, retry_http_async};
use anodizer_core::url::percent_encode_path_segment as encode_segment;
use anyhow::{Context as _, Result};
use reqwest::Client;

use crate::release_body::compose_body_for_mode;

// ---------------------------------------------------------------------------
// Backend ctx + per-call specs
// ---------------------------------------------------------------------------
//
// Bundle the long argument lists in `gitea_create_release`,
// `gitea_upload_asset`, and `gitea_delete_asset_by_name` so each function
// signature stays under clippy's 7-argument threshold without an
// `#[allow(clippy::too_many_arguments)]` suppression. Mirrors gitlab.rs's
// `GitlabCtx`/`GitlabReleaseSpec`/`GitlabAssetSpec` shape.

/// Backend identity for a Gitea API call sequence.
///
/// Carries the HTTP client, base API URL, owner/repo coordinates, and retry
/// policy — i.e. everything that's constant for a whole release-publish
/// loop. Per-release fields (tag, name, body, …) live in
/// [`GiteaReleaseSpec`]; per-asset fields live in [`GiteaAssetSpec`].
#[derive(Clone, Copy)]
pub(crate) struct GiteaCtx<'a> {
    pub client: &'a Client,
    pub api_url: &'a str,
    pub owner: &'a str,
    pub repo: &'a str,
    pub policy: &'a RetryPolicy,
}

/// Release metadata used by [`gitea_create_release`].
#[derive(Clone, Copy)]
pub(crate) struct GiteaReleaseSpec<'a> {
    pub tag: &'a str,
    pub commit: &'a str,
    pub name: &'a str,
    pub body: &'a str,
    pub draft: bool,
    pub prerelease: bool,
    pub release_mode: &'a str,
}

/// File-on-disk identity used by every asset-upload call.
#[derive(Clone, Copy)]
pub(crate) struct GiteaAssetSpec<'a> {
    pub file_path: &'a Path,
    pub file_name: &'a str,
}

// ---------------------------------------------------------------------------
// Public helpers
// ---------------------------------------------------------------------------

/// Build the release page URL on the Gitea web UI.
///
/// Returns `{download}/{owner}/{repo}/releases/tag/{tag}`.
pub(crate) fn gitea_release_url(download_url: &str, owner: &str, repo: &str, tag: &str) -> String {
    let base = download_url.trim_end_matches('/');
    format!(
        "{}/{}/{}/releases/tag/{}",
        base,
        encode_segment(owner),
        encode_segment(repo),
        encode_segment(tag)
    )
}

/// Build a [`reqwest::Client`] configured for Gitea API access.
///
/// - `token`: the GITEA_TOKEN value.
/// - `skip_tls_verify`: when true, disable TLS certificate verification.
///
/// Gitea uses `Authorization: token {value}` for all API requests.
pub(crate) fn build_gitea_client(token: &str, skip_tls_verify: bool) -> Result<Client> {
    let mut headers = reqwest::header::HeaderMap::new();
    headers.insert(
        reqwest::header::AUTHORIZATION,
        reqwest::header::HeaderValue::from_str(&format!("token {}", token))
            .context("gitea: invalid token value for Authorization header")?,
    );

    let builder = Client::builder()
        .default_headers(headers)
        .danger_accept_invalid_certs(skip_tls_verify)
        .timeout(std::time::Duration::from_secs(300));

    builder.build().context("gitea: build HTTP client")
}

// ---------------------------------------------------------------------------
// Create / update release
// ---------------------------------------------------------------------------

/// Create or update a Gitea release.
///
/// Checks whether a release already exists for the given tag by listing
/// releases (paginated). If it exists, applies mode-based body composition
/// (keep-existing / append / prepend / replace) and updates via PATCH. If it
/// does not exist, creates via POST.
///
/// Returns the numeric release ID (Gitea uses integer IDs).
///
/// `ctx.policy` is the user-configured `Config.retry` block (or default 10 ×
/// 10s × 5m cap) — every HTTP call routes through [`retry_http_async`] so
/// 5xx / 429 / network-error responses retry with exponential backoff.
pub(crate) async fn gitea_create_release(
    ctx: &GiteaCtx<'_>,
    spec: &GiteaReleaseSpec<'_>,
) -> Result<u64> {
    let GiteaCtx {
        client,
        api_url,
        owner,
        repo,
        policy,
    } = *ctx;
    let GiteaReleaseSpec {
        tag,
        commit,
        name,
        body,
        draft,
        prerelease,
        release_mode,
    } = *spec;
    let api = api_url.trim_end_matches('/');
    let enc_owner = encode_segment(owner);
    let enc_repo = encode_segment(repo);

    // Try to find an existing release by listing all releases and matching tag.
    let existing = find_release_by_tag(client, api, &enc_owner, &enc_repo, tag, policy).await?;

    if let Some((release_id, existing_body)) = existing {
        // Release exists — update it with mode-based body composition.
        let final_body = compose_body_for_mode(release_mode, existing_body.as_deref(), body);

        let update_url = format!(
            "{}/api/v1/repos/{}/{}/releases/{}",
            api, enc_owner, enc_repo, release_id
        );
        let payload = serde_json::json!({
            "tag_name": tag,
            "target_commitish": commit,
            "name": name,
            "body": final_body,
            "draft": draft,
            "prerelease": prerelease,
        });

        retry_http_async(
            "gitea: PATCH update release",
            policy,
            SuccessClass::Strict,
            |_| client.patch(&update_url).json(&payload).send(),
            |status, body| {
                format!(
                    "gitea: update release failed (HTTP {status}): {}",
                    redact_bearer_tokens(body)
                )
            },
        )
        .await?;

        Ok(release_id)
    } else {
        // Release does not exist — create it.
        let create_url = format!("{}/api/v1/repos/{}/{}/releases", api, enc_owner, enc_repo);
        let payload = serde_json::json!({
            "tag_name": tag,
            "target_commitish": commit,
            "name": name,
            "body": body,
            "draft": draft,
            "prerelease": prerelease,
        });

        let resp = retry_http_async(
            "gitea: POST create release",
            policy,
            SuccessClass::Strict,
            |_| client.post(&create_url).json(&payload).send(),
            |status, body| {
                format!(
                    "gitea: create release failed (HTTP {status}): {}",
                    redact_bearer_tokens(body)
                )
            },
        )
        .await?;

        let json: serde_json::Value = resp
            .json()
            .await
            .context("gitea: parse create release response JSON")?;

        let release_id = json["id"]
            .as_u64()
            .ok_or_else(|| anyhow::anyhow!("gitea: create release response missing 'id' field"))?;

        Ok(release_id)
    }
}

/// Find an existing release by tag name.
///
/// Iterates through paginated release listings (capped at 10 pages to avoid
/// runaway pagination on repos with very long release histories). This is
/// an intentional improvement over GoReleaser, which does not paginate
/// and only checks the first page of results.
///
/// Returns `Some((release_id, body))` if found, `None` otherwise.
async fn find_release_by_tag(
    client: &Client,
    api: &str,
    enc_owner: &str,
    enc_repo: &str,
    tag: &str,
    policy: &RetryPolicy,
) -> Result<Option<(u64, Option<String>)>> {
    const MAX_PAGES: u32 = 10;
    const PAGE_SIZE: u32 = 50;

    for page in 1..=MAX_PAGES {
        let url = format!(
            "{}/api/v1/repos/{}/{}/releases?page={}&limit={}",
            api, enc_owner, enc_repo, page, PAGE_SIZE
        );

        let resp = retry_http_async(
            &format!("gitea: GET releases page {page}"),
            policy,
            SuccessClass::Strict,
            |_| client.get(&url).send(),
            |status, body| {
                format!(
                    "gitea: list releases failed (HTTP {status}): {}",
                    redact_bearer_tokens(body)
                )
            },
        )
        .await?;

        let releases: Vec<serde_json::Value> = resp
            .json()
            .await
            .context("gitea: parse releases list JSON")?;

        for release in &releases {
            if release["tag_name"].as_str() == Some(tag) {
                let id = release["id"]
                    .as_u64()
                    .ok_or_else(|| anyhow::anyhow!("gitea: release missing 'id' field"))?;
                let body = release["body"].as_str().map(|s| s.to_string());
                return Ok(Some((id, body)));
            }
        }

        // If we got fewer results than the page size, there are no more pages.
        if releases.len() < PAGE_SIZE as usize {
            break;
        }
    }

    Ok(None)
}

// ---------------------------------------------------------------------------
// Upload asset
// ---------------------------------------------------------------------------

/// Upload a file as a release attachment via Gitea's multipart API.
///
/// ```text
/// POST {api}/api/v1/repos/{owner}/{repo}/releases/{id}/assets?name={filename}
/// Content-Type: multipart/form-data
/// ```
///
/// The file is sent as the `attachment` form field.
pub(crate) async fn gitea_upload_asset(
    ctx: &GiteaCtx<'_>,
    release_id: u64,
    asset: &GiteaAssetSpec<'_>,
) -> Result<()> {
    let GiteaCtx {
        client,
        api_url,
        owner,
        repo,
        policy,
    } = *ctx;
    let GiteaAssetSpec {
        file_path,
        file_name,
    } = *asset;
    let api = api_url.trim_end_matches('/');
    let enc_owner = encode_segment(owner);
    let enc_repo = encode_segment(repo);
    let enc_filename = encode_segment(file_name);

    let upload_url = format!(
        "{}/api/v1/repos/{}/{}/releases/{}/assets?name={}",
        api, enc_owner, enc_repo, release_id, enc_filename
    );

    let data = tokio::fs::read(file_path)
        .await
        .with_context(|| format!("gitea: read file {}", file_path.display()))?;

    // Multipart Form is move-only — rebuild per attempt from the cloned
    // body bytes. `mime_str("application/octet-stream")` is structurally
    // infallible (a valid RFC-2045 token); same pattern as gitlab.rs and
    // cloudsmith.rs::retry_request.
    retry_http_async(
        "gitea: POST upload asset",
        policy,
        SuccessClass::Strict,
        |_| {
            let file_part = match reqwest::multipart::Part::bytes(data.clone())
                .file_name(file_name.to_string())
                .mime_str("application/octet-stream")
            {
                Ok(p) => p,
                Err(_) => unreachable!("application/octet-stream is a valid MIME type"),
            };
            let form = reqwest::multipart::Form::new().part("attachment", file_part);
            client.post(&upload_url).multipart(form).send()
        },
        |status, body| {
            format!(
                "gitea: upload asset '{}' to release {} failed (HTTP {status}): {}",
                file_name,
                release_id,
                redact_bearer_tokens(body)
            )
        },
    )
    .await?;

    Ok(())
}

/// Delete an existing release attachment by name.
///
/// Lists the release's attachments, finds one matching `file_name`, and
/// deletes it. Used for `replace_existing_artifacts` support.
pub(crate) async fn gitea_delete_asset_by_name(
    ctx: &GiteaCtx<'_>,
    release_id: u64,
    file_name: &str,
) -> Result<bool> {
    let GiteaCtx {
        client,
        api_url,
        owner,
        repo,
        policy,
    } = *ctx;
    let api = api_url.trim_end_matches('/');
    let enc_owner = encode_segment(owner);
    let enc_repo = encode_segment(repo);

    // List attachments for the release.
    let list_url = format!(
        "{}/api/v1/repos/{}/{}/releases/{}/assets",
        api, enc_owner, enc_repo, release_id
    );

    let resp = retry_http_async(
        "gitea: GET release assets",
        policy,
        SuccessClass::Strict,
        |_| client.get(&list_url).send(),
        |status, body| {
            format!(
                "gitea: list release assets failed (HTTP {status}): {}",
                redact_bearer_tokens(body)
            )
        },
    )
    .await?;

    let assets: Vec<serde_json::Value> = resp
        .json()
        .await
        .context("gitea: parse release assets JSON")?;

    for asset in &assets {
        if asset["name"].as_str() == Some(file_name) {
            let asset_id = asset["id"]
                .as_u64()
                .ok_or_else(|| anyhow::anyhow!("gitea: asset missing 'id' field"))?;

            let delete_url = format!(
                "{}/api/v1/repos/{}/{}/releases/{}/assets/{}",
                api, enc_owner, enc_repo, release_id, asset_id
            );

            retry_http_async(
                "gitea: DELETE asset",
                policy,
                SuccessClass::Strict,
                |_| client.delete(&delete_url).send(),
                |status, body| {
                    format!(
                        "gitea: delete asset '{}' (id={}) from release {} failed (HTTP {status}): {}",
                        file_name,
                        asset_id,
                        release_id,
                        redact_bearer_tokens(body)
                    )
                },
            )
            .await?;

            return Ok(true);
        }
    }

    Ok(false)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- gitea_release_url --------------------------------------------------

    #[test]
    fn release_url_basic() {
        let url = gitea_release_url("https://gitea.example.com", "myorg", "myapp", "v1.0.0");
        assert_eq!(
            url,
            "https://gitea.example.com/myorg/myapp/releases/tag/v1.0.0"
        );
    }

    #[test]
    fn release_url_trailing_slash_stripped() {
        let url = gitea_release_url("https://gitea.example.com/", "org", "repo", "v2.0.0");
        assert_eq!(
            url,
            "https://gitea.example.com/org/repo/releases/tag/v2.0.0"
        );
    }

    #[test]
    fn release_url_special_chars_in_tag() {
        let url = gitea_release_url(
            "https://gitea.example.com",
            "myorg",
            "myapp",
            "v1.0.0+build.1",
        );
        assert_eq!(
            url,
            "https://gitea.example.com/myorg/myapp/releases/tag/v1.0.0%2Bbuild.1"
        );
    }

    #[test]
    fn release_url_special_chars_in_owner_and_repo() {
        let url = gitea_release_url("https://gitea.example.com", "my org", "my repo", "v1.0.0");
        assert!(url.contains("my%20org"), "owner should be percent-encoded");
        assert!(url.contains("my%20repo"), "repo should be percent-encoded");
    }

    // -- encode_segment -----------------------------------------------------

    #[test]
    fn encode_segment_simple() {
        assert_eq!(encode_segment("v1.0.0"), "v1.0.0");
    }

    #[test]
    fn encode_segment_with_plus() {
        assert_eq!(encode_segment("v1.0.0+build.1"), "v1.0.0%2Bbuild.1");
    }

    #[test]
    fn encode_segment_with_special_chars() {
        assert_eq!(encode_segment("v1 beta#2?rc"), "v1%20beta%232%3Frc");
    }

    #[test]
    fn encode_segment_preserves_dots_dashes_underscores() {
        assert_eq!(encode_segment("my-project_v2.0"), "my-project_v2.0");
    }

    // -- build_gitea_client -------------------------------------------------

    #[test]
    fn build_client_normal() {
        let client = build_gitea_client("giteatok-xxxx", false);
        assert!(client.is_ok());
    }

    #[test]
    fn build_client_skip_tls() {
        let client = build_gitea_client("giteatok-xxxx", true);
        assert!(client.is_ok());
    }

    // -- Gitea auth header format -------------------------------------------

    #[test]
    fn gitea_auth_header_format() {
        // Verify the Authorization header uses the `token {value}` format.
        let token = "my-gitea-token";
        let expected_header = format!("token {}", token);

        // Build the client and verify the default headers contain the correct auth.
        let client = build_gitea_client(token, false).unwrap();

        // We can't directly inspect reqwest's default headers, but we can verify
        // the format by testing the construction doesn't fail with the token format.
        // The real verification is that the header value "token my-gitea-token" is valid.
        let header_value = reqwest::header::HeaderValue::from_str(&expected_header).unwrap();
        assert_eq!(
            header_value.to_str().unwrap(),
            "token my-gitea-token",
            "Gitea auth header must use 'token {{value}}' format"
        );

        // Ensure client was built successfully (implies headers are valid)
        drop(client);
    }

    // -- gitea_create_release retry behaviour (P1.4) -------------------------
    //
    // Pin: a 503 on the find-release-by-tag GET must retry through
    // `retry_http_async` rather than fast-fail. Mirrors the gitlab equivalent
    // and the core retry::tests::retry_http_async_retries_5xx_then_succeeds
    // test, but exercises the policy plumbing end-to-end at the publisher.

    fn spawn_oneshot_http_responder(
        responses: Vec<&'static str>,
    ) -> (
        std::net::SocketAddr,
        std::sync::Arc<std::sync::atomic::AtomicU32>,
    ) {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::sync::atomic::{AtomicU32, Ordering};
        use std::time::Duration;

        let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
        let addr = listener.local_addr().expect("local_addr");
        let counter = std::sync::Arc::new(AtomicU32::new(0));
        let counter_inner = counter.clone();
        std::thread::spawn(move || {
            for (i, resp) in responses.iter().enumerate() {
                let (mut stream, _) = match listener.accept() {
                    Ok(pair) => pair,
                    Err(_) => return,
                };
                counter_inner.fetch_add(1, Ordering::SeqCst);
                let mut buf = [0u8; 8192];
                let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
                let _ = stream.read(&mut buf);
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
                let _ = stream.shutdown(std::net::Shutdown::Both);
                if i == responses.len() - 1 {
                    break;
                }
            }
        });
        (addr, counter)
    }

    #[tokio::test]
    async fn gitea_create_release_retries_5xx_on_list_releases() {
        use std::sync::atomic::Ordering;
        use std::time::Duration;

        // Sequence: 503 on the GET releases list, then 200 with an empty
        // array (release does not exist), then 201 on the POST create with
        // a fake id. The retry helper should retry past the 503 and the
        // create succeeds.
        let (addr, calls) = spawn_oneshot_http_responder(vec![
            "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n[]",
            "HTTP/1.1 201 Created\r\nContent-Type: application/json\r\nContent-Length: 9\r\n\r\n{\"id\":42}",
        ]);

        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(2))
            .build()
            .expect("client");
        let policy = RetryPolicy {
            max_attempts: 3,
            base_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(2),
        };
        let api_url = format!("http://{addr}");

        let ctx = GiteaCtx {
            client: &client,
            api_url: &api_url,
            owner: "myorg",
            repo: "myrepo",
            policy: &policy,
        };
        let spec = GiteaReleaseSpec {
            tag: "v1.0.0",
            commit: "abc123",
            name: "Release v1.0.0",
            body: "release body",
            draft: false,
            prerelease: false,
            release_mode: "replace",
        };
        let result = gitea_create_release(&ctx, &spec).await;

        match result {
            Ok(id) => assert_eq!(id, 42, "release id should be parsed from create response"),
            Err(e) => panic!("expected success after 5xx retry, got: {e:#}"),
        }
        assert_eq!(
            calls.load(Ordering::SeqCst),
            3,
            "expected 3 connections (503-retry GET, 200 GET, 201 POST)"
        );
    }

    /// Defense-in-depth: a Gitea API 4xx response that echoes our
    /// `Authorization: Bearer <PAT>` header back must not leak the token
    /// into the user-visible error chain. Exercises the
    /// `find_release_by_tag` GET error path on the 401-fast-fail path.
    /// All gitea.rs body-interpolation sites share the same redaction wrap.
    #[tokio::test]
    async fn gitea_create_release_redacts_bearer_in_error_body() {
        use std::time::Duration;

        let leaky = r#"{"message":"401 Unauthorized: Authorization: Bearer ghp_FAKETOKEN1234567890abcdefg"}"#;
        let body_len = leaky.len();
        let resp: &'static str = Box::leak(
            format!(
                "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json\r\nContent-Length: {body_len}\r\n\r\n{leaky}"
            )
            .into_boxed_str(),
        );
        let (addr, _calls) = spawn_oneshot_http_responder(vec![resp]);

        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(2))
            .build()
            .expect("client");
        let policy = RetryPolicy {
            max_attempts: 3,
            base_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(2),
        };
        let api_url = format!("http://{addr}");

        let ctx = GiteaCtx {
            client: &client,
            api_url: &api_url,
            owner: "myorg",
            repo: "myrepo",
            policy: &policy,
        };
        let spec = GiteaReleaseSpec {
            tag: "v1.0.0",
            commit: "abc123",
            name: "Release v1.0.0",
            body: "release body",
            draft: false,
            prerelease: false,
            release_mode: "replace",
        };
        let err = gitea_create_release(&ctx, &spec)
            .await
            .expect_err("401 must fast-fail");
        let chain = format!("{err:#}");
        assert!(
            !chain.contains("ghp_FAKETOKEN1234567890abcdefg"),
            "bearer token leaked into error chain: {chain}"
        );
        assert!(
            chain.contains("<redacted>"),
            "expected `<redacted>` marker in error chain: {chain}"
        );
    }
}