wepub-core 0.2.0

Library for publishing browser extensions to Chrome Web Store and Firefox AMO
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
use std::collections::HashMap;
use std::time::{Duration, Instant};

use reqwest::multipart::{Form, Part};
use serde::{Deserialize, Serialize};
use url::Url;

use crate::{Result, WepubError, http::build_client};

use super::auth::generate_jwt;

const DEFAULT_BASE_URL: &str = "https://addons.mozilla.org/api/v5/";
const UPLOAD_FILE_NAME: &str = "addon.zip";
const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(1);
const DEFAULT_POLL_TIMEOUT: Duration = Duration::from_secs(5 * 60);

/// Options that shape how [`FirefoxStore::publish`] creates the new version.
#[derive(Debug, Clone, Default)]
pub struct FirefoxPublishOptions {
    /// Distribution channel for the new version.
    pub channel: Channel,
    /// Application compatibility declarations. `None` falls back to whatever
    /// the manifest's `strict_min_version` / `strict_max_version` declare.
    pub compatibility: Option<Compatibility>,
    /// Release notes keyed by AMO locale code (e.g. `"en-US"`).
    pub release_notes: HashMap<String, String>,
    /// Optional message to AMO reviewers, typically containing build
    /// reproduction steps.
    pub approval_notes: Option<String>,
    /// Optional source archive to attach to the version. AMO requires this
    /// when reviewers cannot reproduce the bundled artefact from the listing.
    pub source: Option<Vec<u8>>,
    /// Polling cadence and overall timeout used while waiting for AMO to
    /// finish validating the upload.
    pub poll: FirefoxPollConfig,
}

/// Polling cadence and budget for [`FirefoxStore::publish`]'s
/// validation-status loop.
///
/// Defaults to 1 second interval and 5 minute timeout.
#[derive(Debug, Clone)]
pub struct FirefoxPollConfig {
    /// Delay between successive polls of the upload status endpoint.
    pub interval: Duration,
    /// Maximum total time to wait before giving up with
    /// [`WepubError::Validation`].
    pub timeout: Duration,
}

impl Default for FirefoxPollConfig {
    fn default() -> Self {
        Self {
            interval: DEFAULT_POLL_INTERVAL,
            timeout: DEFAULT_POLL_TIMEOUT,
        }
    }
}

/// Distribution channel for an AMO version.
#[derive(Debug, Clone, Copy, Default)]
pub enum Channel {
    /// Listed on addons.mozilla.org. Goes through public review (the
    /// default).
    #[default]
    Listed,
    /// Self-distributed signed build. Reviewed but not listed.
    Unlisted,
}

impl Channel {
    fn as_str(self) -> &'static str {
        match self {
            Channel::Listed => "listed",
            Channel::Unlisted => "unlisted",
        }
    }
}

/// Compatibility declaration sent to AMO when creating the version.
///
/// AMO's wire format accepts either a flat list of compatible apps (with
/// versions inferred from the manifest) or an object mapping each app to an
/// explicit version range. `wepub-core` exposes both shapes through this
/// enum.
#[derive(Debug, Clone)]
pub enum Compatibility {
    /// Shorthand form: list compatible apps; min/max come from the manifest.
    Apps(Vec<Application>),
    /// Detailed form: per-app explicit version range. An empty
    /// [`VersionRange`] means "use the value declared in the manifest".
    Detailed(HashMap<Application, VersionRange>),
}

impl Serialize for Compatibility {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        match self {
            Self::Apps(apps) => apps.serialize(serializer),
            Self::Detailed(map) => map.serialize(serializer),
        }
    }
}

/// AMO application identifier used in compatibility declarations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Application {
    /// Desktop Firefox.
    Firefox,
    /// Firefox for Android.
    Android,
}

impl Application {
    fn as_str(self) -> &'static str {
        match self {
            Application::Firefox => "firefox",
            Application::Android => "android",
        }
    }
}

impl Serialize for Application {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// Explicit `min` / `max` application version pair used by
/// [`Compatibility::Detailed`].
///
/// Either bound can be `None`, in which case the corresponding manifest
/// value is used.
#[derive(Debug, Clone, Default, Serialize)]
pub struct VersionRange {
    /// Minimum compatible application version. `None` defers to the
    /// manifest's `strict_min_version`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<String>,
    /// Maximum compatible application version. `None` defers to the
    /// manifest's `strict_max_version`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<String>,
}

// Successful response from creating a new add-on version on AMO.
// Internal-only: the id is echoed via `tracing::info!` from `publish` and
// not surfaced to the caller because the only documented use was logging.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct VersionResponse {
    pub(crate) id: u64,
}

/// Client for the AMO Add-on Versions API (v5).
///
/// The store holds the JWT credential pair and a reusable HTTP client; it
/// is cheap to construct and intended to live for the duration of a single
/// publish run.
// Debug intentionally omitted: holds the AMO JWT secret.
pub struct FirefoxStore {
    addon_id: String,
    issuer: String,
    secret: String,
    base_url: Url,
    client: reqwest::Client,
}

impl FirefoxStore {
    /// Build a store bound to `addon_id`, signing requests with the supplied
    /// HS256 JWT credential pair (issuer + secret).
    ///
    /// Get the credentials from
    /// <https://addons.mozilla.org/developers/addon/api/key/>.
    ///
    /// # Errors
    ///
    /// Fails if the underlying HTTP client cannot be built (e.g. rustls
    /// platform-verifier initialization fails).
    pub fn from_jwt_credentials(
        addon_id: String,
        jwt_issuer: String,
        jwt_secret: String,
    ) -> Result<Self> {
        Ok(Self {
            addon_id,
            issuer: jwt_issuer,
            secret: jwt_secret,
            base_url: Url::parse(DEFAULT_BASE_URL).expect("DEFAULT_BASE_URL is a valid URL"),
            client: build_client()?,
        })
    }

    /// Override the AMO API base URL.
    ///
    /// Defaults to `https://addons.mozilla.org/api/v5/`. Intended for tests
    /// or when pointing at a local `mozilla/addons-server` instance. A
    /// missing trailing slash is added automatically so that relative paths
    /// join correctly.
    ///
    /// # Errors
    ///
    /// Returns [`WepubError::InvalidUrl`] if `base_url` does not parse as a
    /// URL.
    pub fn with_base_url(mut self, base_url: &str) -> Result<Self> {
        let parsed = Url::parse(base_url)
            .map_err(|e| WepubError::InvalidUrl(format!("{base_url:?}: {e}")))?;
        self.base_url = ensure_trailing_slash(parsed);
        Ok(self)
    }

    /// Upload `zip` and create a new version on the bound add-on.
    ///
    /// The call performs four steps internally: upload the archive, poll
    /// AMO until validation finishes, create the version, and (if
    /// `options.source` is set) attach the source archive in a follow-up
    /// PATCH. The polling cadence is controlled by `options.poll`.
    ///
    /// Progress (`uploading...`, `polling AMO upload status`, `published
    /// version id=...`) is emitted through the `tracing` crate; library
    /// consumers configure their own subscriber to render or capture it.
    ///
    /// # Errors
    ///
    /// On failure, returns one of [`WepubError::Network`],
    /// [`WepubError::Api`], [`WepubError::Auth`], [`WepubError::Validation`],
    /// [`WepubError::Json`], [`WepubError::Io`] or [`WepubError::Internal`]
    /// depending on which step failed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn run() -> wepub_core::Result<()> {
    /// use wepub_core::firefox::{FirefoxStore, FirefoxPublishOptions};
    ///
    /// let store = FirefoxStore::from_jwt_credentials(
    ///     "myaddon@example.com".into(),
    ///     "user:12345:6789".into(),
    ///     "jwt-secret".into(),
    /// )?;
    /// let zip = std::fs::read("./addon.zip")?;
    /// store.publish(zip, FirefoxPublishOptions::default()).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn publish(&self, zip: Vec<u8>, options: FirefoxPublishOptions) -> Result<()> {
        let upload = self.upload(zip, options.channel).await?;
        let validated = self
            .wait_until_validated(&upload.uuid, &options.poll)
            .await?;

        let version = self
            .create_version(
                &validated.uuid,
                options.compatibility.as_ref(),
                &options.release_notes,
                options.approval_notes.as_deref(),
            )
            .await?;

        if let Some(source) = options.source {
            self.patch_version_source(version.id, source).await?;
        }

        tracing::info!(version_id = version.id, "published version");
        Ok(())
    }

    pub(crate) fn endpoint(&self, path: &str) -> Result<Url> {
        self.base_url
            .join(path)
            .map_err(|e| WepubError::Internal(format!("invalid endpoint path {path:?}: {e}")))
    }

    pub(crate) async fn upload(&self, zip: Vec<u8>, channel: Channel) -> Result<UploadResponse> {
        let url = self.endpoint("addons/upload/")?;
        let auth = self.auth_header()?;

        let len = zip.len() as u64;
        let part = Part::stream_with_length(reqwest::Body::from(zip), len)
            .file_name(UPLOAD_FILE_NAME)
            .mime_str("application/zip")
            .map_err(|e| WepubError::Internal(format!("invalid MIME literal: {e}")))?;
        let form = Form::new()
            .part("upload", part)
            .text("channel", channel.as_str());

        tracing::info!(addon_id = %self.addon_id, channel = channel.as_str(), "uploading add-on to AMO");

        let resp = self
            .client
            .post(url)
            .header(reqwest::header::AUTHORIZATION, auth)
            .multipart(form)
            .send()
            .await?;

        decode_response(resp).await
    }

    pub(crate) async fn wait_until_validated(
        &self,
        uuid: &str,
        config: &FirefoxPollConfig,
    ) -> Result<UploadResponse> {
        let url = self.endpoint(&format!("addons/upload/{uuid}/"))?;
        let started = Instant::now();

        loop {
            let auth = self.auth_header()?;
            let resp = self
                .client
                .get(url.clone())
                .header(reqwest::header::AUTHORIZATION, auth)
                .send()
                .await?;
            let upload: UploadResponse = decode_response(resp).await?;

            tracing::info!(
                uuid = uuid,
                processed = upload.processed,
                valid = upload.valid,
                "polling AMO upload status"
            );

            if upload.processed {
                if upload.valid {
                    return Ok(upload);
                }
                let body = upload.validation.as_ref().map_or_else(
                    || "validation failed (no detail provided)".to_string(),
                    |v| serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string()),
                );
                return Err(WepubError::Validation {
                    uuid: uuid.to_string(),
                    body,
                });
            }

            if started.elapsed() >= config.timeout {
                return Err(WepubError::Validation {
                    uuid: uuid.to_string(),
                    body: format!("validation timed out after {:?}", config.timeout),
                });
            }

            tokio::time::sleep(config.interval).await;
        }
    }

    pub(crate) async fn create_version(
        &self,
        upload_uuid: &str,
        compatibility: Option<&Compatibility>,
        release_notes: &HashMap<String, String>,
        approval_notes: Option<&str>,
    ) -> Result<VersionResponse> {
        let url = self.endpoint(&format!("addons/addon/{}/versions/", self.addon_id))?;
        let auth = self.auth_header()?;

        let body = VersionCreateBody {
            upload: upload_uuid,
            compatibility,
            release_notes,
            approval_notes,
        };

        tracing::info!(
            addon_id = %self.addon_id,
            uuid = upload_uuid,
            "creating AMO version"
        );

        let resp = self
            .client
            .post(url)
            .header(reqwest::header::AUTHORIZATION, auth)
            .json(&body)
            .send()
            .await?;

        decode_response(resp).await
    }

    pub(crate) async fn patch_version_source(
        &self,
        version_id: u64,
        source: Vec<u8>,
    ) -> Result<VersionResponse> {
        let url = self.endpoint(&format!(
            "addons/addon/{}/versions/{version_id}/",
            self.addon_id
        ))?;
        let auth = self.auth_header()?;

        let len = source.len() as u64;
        let part = Part::stream_with_length(reqwest::Body::from(source), len)
            .file_name("source.zip")
            .mime_str("application/zip")
            .map_err(|e| WepubError::Internal(format!("invalid MIME literal: {e}")))?;
        let form = Form::new().part("source", part);

        tracing::info!(
            addon_id = %self.addon_id,
            version_id,
            "uploading version source to AMO"
        );

        let resp = self
            .client
            .patch(url)
            .header(reqwest::header::AUTHORIZATION, auth)
            .multipart(form)
            .send()
            .await?;

        decode_response(resp).await
    }

    fn auth_header(&self) -> Result<String> {
        let token = generate_jwt(&self.issuer, &self.secret)?;
        Ok(format!("JWT {token}"))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct UploadResponse {
    pub uuid: String,
    pub processed: bool,
    pub valid: bool,
    #[serde(default)]
    pub validation: Option<serde_json::Value>,
}

#[derive(Serialize)]
struct VersionCreateBody<'a> {
    upload: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    compatibility: Option<&'a Compatibility>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    release_notes: &'a HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    approval_notes: Option<&'a str>,
}

async fn decode_response<T: serde::de::DeserializeOwned>(resp: reqwest::Response) -> Result<T> {
    let status = resp.status();
    let body = resp.text().await?;
    tracing::debug!(
        status = status.as_u16(),
        body = %body,
        "received AMO response",
    );
    if !status.is_success() {
        return Err(WepubError::Api {
            status: status.as_u16(),
            body,
        });
    }
    serde_json::from_str(&body).map_err(WepubError::from)
}

fn ensure_trailing_slash(mut url: Url) -> Url {
    if !url.path().ends_with('/') {
        let new_path = format!("{}/", url.path());
        url.set_path(&new_path);
    }
    url
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::matchers::{header_exists, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn upload_posts_multipart_and_parses_response() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/addons/upload/"))
            .and(header_exists("authorization"))
            .respond_with(
                ResponseTemplate::new(201).set_body_json(upload_json("abc-123", false, false)),
            )
            .expect(1)
            .mount(&server)
            .await;

        let store = store_for(&server);
        let resp = store
            .upload(b"fake-zip".to_vec(), Channel::Listed)
            .await
            .unwrap();

        assert_eq!(resp.uuid, "abc-123");
        assert!(!resp.processed);
    }

    #[tokio::test]
    async fn wait_until_validated_returns_when_processed_and_valid() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/addons/upload/uuid-1/"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(upload_json("uuid-1", false, false)),
            )
            .up_to_n_times(1)
            .mount(&server)
            .await;

        Mock::given(method("GET"))
            .and(path("/addons/upload/uuid-1/"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(upload_json("uuid-1", true, true)),
            )
            .mount(&server)
            .await;

        let store = store_for(&server);
        let resp = store
            .wait_until_validated("uuid-1", &fast_poll())
            .await
            .unwrap();

        assert_eq!(resp.uuid, "uuid-1");
        assert!(resp.processed);
        assert!(resp.valid);
    }

    #[tokio::test]
    async fn wait_until_validated_errors_on_invalid_validation() {
        let server = MockServer::start().await;
        let body = json!({
            "uuid": "uuid-2",
            "channel": "listed",
            "processed": true,
            "submitted": false,
            "url": "https://example.com/upload/uuid-2/",
            "valid": false,
            "validation": { "messages": [{ "type": "error", "message": "manifest broken" }] },
            "version": null,
        });
        Mock::given(method("GET"))
            .and(path("/addons/upload/uuid-2/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(body))
            .mount(&server)
            .await;

        let store = store_for(&server);
        let err = store
            .wait_until_validated("uuid-2", &fast_poll())
            .await
            .unwrap_err();

        match err {
            WepubError::Validation { uuid, body } => {
                assert_eq!(uuid, "uuid-2");
                assert!(body.contains("manifest broken"));
            }
            other => panic!("expected WepubError::Validation, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn wait_until_validated_times_out_when_processing_never_completes() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/addons/upload/uuid-3/"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(upload_json("uuid-3", false, false)),
            )
            .mount(&server)
            .await;

        let store = store_for(&server);
        let err = store
            .wait_until_validated("uuid-3", &fast_poll())
            .await
            .unwrap_err();

        match err {
            WepubError::Validation { uuid, body } => {
                assert_eq!(uuid, "uuid-3");
                assert!(body.contains("timed out"));
            }
            other => panic!("expected WepubError::Validation, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn create_version_posts_json_and_parses_id() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/addons/addon/test-addon/versions/"))
            .and(header_exists("authorization"))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 4242 })))
            .expect(1)
            .mount(&server)
            .await;

        let store = store_for(&server);
        let resp = store
            .create_version("uuid-x", None, &HashMap::new(), None)
            .await
            .unwrap();

        assert_eq!(resp.id, 4242);
    }

    #[tokio::test]
    async fn patch_version_source_sends_multipart_patch() {
        let server = MockServer::start().await;
        Mock::given(method("PATCH"))
            .and(path("/addons/addon/test-addon/versions/4242/"))
            .and(header_exists("authorization"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 4242 })))
            .expect(1)
            .mount(&server)
            .await;

        let store = store_for(&server);
        let resp = store
            .patch_version_source(4242, b"source-zip".to_vec())
            .await
            .unwrap();

        assert_eq!(resp.id, 4242);
    }

    #[tokio::test]
    async fn publish_runs_full_flow_when_source_is_provided() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/addons/upload/"))
            .respond_with(
                ResponseTemplate::new(201).set_body_json(upload_json("uuid-pub", false, false)),
            )
            .expect(1)
            .mount(&server)
            .await;

        Mock::given(method("GET"))
            .and(path("/addons/upload/uuid-pub/"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(upload_json("uuid-pub", true, true)),
            )
            .mount(&server)
            .await;

        Mock::given(method("POST"))
            .and(path("/addons/addon/test-addon/versions/"))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 7777 })))
            .expect(1)
            .mount(&server)
            .await;

        Mock::given(method("PATCH"))
            .and(path("/addons/addon/test-addon/versions/7777/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 7777 })))
            .expect(1)
            .mount(&server)
            .await;

        let store = store_for(&server);
        let options = FirefoxPublishOptions {
            source: Some(b"source-zip".to_vec()),
            poll: fast_poll(),
            ..FirefoxPublishOptions::default()
        };
        store.publish(b"zip".to_vec(), options).await.unwrap();
    }

    #[tokio::test]
    async fn publish_skips_source_patch_when_no_source_provided() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/addons/upload/"))
            .respond_with(
                ResponseTemplate::new(201).set_body_json(upload_json("uuid-ns", true, true)),
            )
            .expect(1)
            .mount(&server)
            .await;

        Mock::given(method("GET"))
            .and(path("/addons/upload/uuid-ns/"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(upload_json("uuid-ns", true, true)),
            )
            .mount(&server)
            .await;

        Mock::given(method("POST"))
            .and(path("/addons/addon/test-addon/versions/"))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 9999 })))
            .expect(1)
            .mount(&server)
            .await;

        Mock::given(method("PATCH"))
            .and(path("/addons/addon/test-addon/versions/9999/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 9999 })))
            .expect(0)
            .mount(&server)
            .await;

        let store = store_for(&server);
        let options = FirefoxPublishOptions {
            poll: fast_poll(),
            ..FirefoxPublishOptions::default()
        };
        store.publish(b"zip".to_vec(), options).await.unwrap();
    }

    #[tokio::test]
    async fn publish_propagates_upload_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/addons/upload/"))
            .respond_with(ResponseTemplate::new(401).set_body_string("unauthorized"))
            .expect(1)
            .mount(&server)
            .await;

        let store = store_for(&server);
        let options = FirefoxPublishOptions {
            poll: fast_poll(),
            ..FirefoxPublishOptions::default()
        };
        let err = store.publish(b"zip".to_vec(), options).await.unwrap_err();

        match err {
            WepubError::Api { status, body } => {
                assert_eq!(status, 401);
                assert_eq!(body, "unauthorized");
            }
            other => panic!("expected WepubError::Api, got {other:?}"),
        }
    }

    // ---- Unit tests for serialization and URL helpers ----

    #[test]
    fn channel_serialises_as_amo_expects() {
        assert_eq!(Channel::Listed.as_str(), "listed");
        assert_eq!(Channel::Unlisted.as_str(), "unlisted");
    }

    #[test]
    fn version_create_body_minimal_only_has_upload() {
        let json = body_to_json("uuid-123", None, &HashMap::new(), None);
        assert_eq!(json, serde_json::json!({ "upload": "uuid-123" }));
    }

    #[test]
    fn version_create_body_with_apps_shorthand() {
        let compat = Compatibility::Apps(vec![Application::Firefox, Application::Android]);
        let json = body_to_json("uuid-123", Some(&compat), &HashMap::new(), None);
        assert_eq!(
            json,
            serde_json::json!({
                "upload": "uuid-123",
                "compatibility": ["firefox", "android"],
            })
        );
    }

    #[test]
    fn version_create_body_with_detailed_compatibility_omits_empty_min_max() {
        let mut map = HashMap::new();
        map.insert(
            Application::Firefox,
            VersionRange {
                min: Some("58.0".into()),
                max: Some("120.0".into()),
            },
        );
        map.insert(
            Application::Android,
            VersionRange {
                min: Some("58.0".into()),
                max: None,
            },
        );
        let compat = Compatibility::Detailed(map);
        let json = body_to_json("uuid-123", Some(&compat), &HashMap::new(), None);

        assert_eq!(json["upload"], "uuid-123");
        assert_eq!(
            json["compatibility"]["firefox"],
            serde_json::json!({ "min": "58.0", "max": "120.0" })
        );
        assert_eq!(
            json["compatibility"]["android"],
            serde_json::json!({ "min": "58.0" })
        );
    }

    #[test]
    fn version_create_body_includes_release_notes_and_approval_notes() {
        let mut notes = HashMap::new();
        notes.insert("en-US".into(), "Hello".into());
        notes.insert("ja".into(), "こんにちは".into());

        let json = body_to_json("uuid-123", None, &notes, Some("for reviewers"));

        assert_eq!(json["upload"], "uuid-123");
        assert_eq!(json["release_notes"]["en-US"], "Hello");
        assert_eq!(json["release_notes"]["ja"], "こんにちは");
        assert_eq!(json["approval_notes"], "for reviewers");
    }

    #[test]
    fn endpoint_joins_relative_path() {
        let store = FirefoxStore::from_jwt_credentials(
            "test-addon".into(),
            "issuer".into(),
            "secret".into(),
        )
        .unwrap();
        let url = store.endpoint("addons/upload/").unwrap();
        assert_eq!(
            url.as_str(),
            "https://addons.mozilla.org/api/v5/addons/upload/"
        );
    }

    #[test]
    fn with_base_url_overrides_default() {
        let store = FirefoxStore::from_jwt_credentials(
            "test-addon".into(),
            "issuer".into(),
            "secret".into(),
        )
        .unwrap()
        .with_base_url("http://127.0.0.1:8000/api/v5/")
        .unwrap();
        let url = store.endpoint("addons/upload/").unwrap();
        assert_eq!(url.as_str(), "http://127.0.0.1:8000/api/v5/addons/upload/");
    }

    #[test]
    fn with_base_url_rejects_garbage() {
        let store = FirefoxStore::from_jwt_credentials(
            "test-addon".into(),
            "issuer".into(),
            "secret".into(),
        )
        .unwrap();
        let Err(err) = store.with_base_url("not a url") else {
            panic!("expected with_base_url to reject");
        };
        assert!(matches!(err, WepubError::InvalidUrl(_)), "got {err:?}");
    }

    #[test]
    fn ensure_trailing_slash_appends_when_missing() {
        let url = Url::parse("https://example.com/api/v5").unwrap();
        let result = ensure_trailing_slash(url);
        assert_eq!(result.as_str(), "https://example.com/api/v5/");
    }

    #[test]
    fn ensure_trailing_slash_is_idempotent() {
        let url = Url::parse("https://example.com/api/v5/").unwrap();
        let result = ensure_trailing_slash(url);
        assert_eq!(result.as_str(), "https://example.com/api/v5/");
    }

    fn store_for(server: &MockServer) -> FirefoxStore {
        FirefoxStore::from_jwt_credentials("test-addon".into(), "issuer".into(), "secret".into())
            .unwrap()
            .with_base_url(&server.uri())
            .unwrap()
    }

    fn fast_poll() -> FirefoxPollConfig {
        FirefoxPollConfig {
            interval: Duration::from_millis(10),
            timeout: Duration::from_millis(200),
        }
    }

    fn upload_json(uuid: &str, processed: bool, valid: bool) -> serde_json::Value {
        json!({
            "uuid": uuid,
            "channel": "listed",
            "processed": processed,
            "submitted": false,
            "url": format!("https://example.com/upload/{uuid}/"),
            "valid": valid,
            "validation": null,
            "version": "1.0.0",
        })
    }

    fn body_to_json(
        upload: &str,
        compatibility: Option<&Compatibility>,
        release_notes: &HashMap<String, String>,
        approval_notes: Option<&str>,
    ) -> serde_json::Value {
        serde_json::to_value(VersionCreateBody {
            upload,
            compatibility,
            release_notes,
            approval_notes,
        })
        .unwrap()
    }
}