Skip to main content

lux_lib/upload/
mod.rs

1use crate::package;
2use std::{env, io};
3
4use crate::operations::download;
5use crate::package::db::PackageDB;
6use crate::package::SpecRevIterator;
7use crate::rockspec;
8use crate::rockspec::Rockspec;
9use crate::{config::Config, project::Project};
10
11use bon::Builder;
12use itertools::Itertools;
13use miette::Diagnostic;
14use reqwest::multipart::{Form, Part};
15use reqwest::StatusCode;
16use serde::Deserialize;
17use serde_enum_str::Serialize_enum_str;
18use thiserror::Error;
19use url::Url;
20
21#[cfg(feature = "gpgme")]
22use gpgme::{Context, Data};
23#[cfg(feature = "gpgme")]
24use std::io::Read;
25#[cfg(feature = "gpgme")]
26use strum_macros::EnumIter;
27
28const TFA_TOKEN_HEADER: &str = "X-TFA-Token";
29
30pub mod check;
31
32/// WARNING: This function is unsafe,
33/// because it adds the unmasked API key to the URL.
34/// When using URLs created by this function,
35/// pay attention not to leak the API key in errors.
36pub(crate) unsafe fn url_for_method(
37    server_url: &Url,
38    api_key: &ApiKey,
39    endpoint: &str,
40) -> Result<Url, url::ParseError> {
41    server_url
42        .join("api/1/")?
43        .join(&format!("{}/", api_key.get()))?
44        .join(endpoint)
45}
46
47/// Whether to perform the upload or only report what would be uploaded.
48#[derive(Clone, Copy, Debug, Default)]
49pub enum Mode {
50    #[default]
51    Upload,
52    DryRun,
53}
54
55/// A rocks package uploader, providing fine-grained control
56/// over how a package should be uploaded.
57#[derive(Builder)]
58#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
59pub struct ProjectUpload<'a> {
60    project: &'a Project,
61    api_key: Option<ApiKey>,
62    tfa_code: Option<String>,
63    #[cfg(feature = "gpgme")]
64    sign_protocol: SignatureProtocol,
65    config: &'a Config,
66    package_db: &'a PackageDB,
67    #[builder(default)]
68    mode: Mode,
69}
70
71impl<State> ProjectUploadBuilder<'_, State>
72where
73    State: project_upload_builder::State + project_upload_builder::IsComplete,
74{
75    /// Upload a package to a luarocks server.
76    pub async fn upload_to_luarocks(self) -> Result<PreparedRockspec, Error> {
77        let args = self._build();
78        upload_from_project(args).await
79    }
80}
81
82/// An uploader for an existing `.rockspec` file.
83#[derive(Builder)]
84#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
85pub struct RockspecUpload<'a> {
86    rockspec: &'a rockspec::lua::Remote,
87    api_key: Option<ApiKey>,
88    tfa_code: Option<String>,
89    #[cfg(feature = "gpgme")]
90    sign_protocol: SignatureProtocol,
91    config: &'a Config,
92    #[builder(default)]
93    mode: Mode,
94}
95
96impl<State> RockspecUploadBuilder<'_, State>
97where
98    State: rockspec_upload_builder::State + rockspec_upload_builder::IsComplete,
99{
100    /// Upload a rockspec to a luarocks server.
101    pub async fn upload_to_luarocks(self) -> Result<PreparedRockspec, Error> {
102        let args = self._build();
103        upload_from_rockspec(args).await
104    }
105}
106
107#[derive(Error, Debug, Diagnostic)]
108#[non_exhaustive]
109#[error(transparent)]
110pub enum Error {
111    #[error("error parsing upload URL")]
112    #[diagnostic(help("check your server configuration"))]
113    ParseError(#[from] url::ParseError),
114    #[error("HTPP request error while uploading")]
115    #[diagnostic(help(
116        r#"check your network connection and server configuration.
117if the issue persists, the server may be temporarily unavailable."#
118    ))]
119    Request(#[from] crate::reqwest::Error),
120    #[error("server '{0}' responded with error status: '{1}'")]
121    #[diagnostic(help("the server may be temporarily unavailable"))]
122    Server(Url, StatusCode),
123    #[error("client error when requesting {0}:\n{1}")]
124    #[diagnostic(help(
125        r#"check your network connection and server configuration.
126if the issue persists, the server may be temporarily unavailable."#
127    ))]
128    Client(Url, String),
129    #[diagnostic(transparent)]
130    RockCheck(#[from] check::rock::Error),
131    #[error("a package with the same rockspec content already exists on the server: '{0}'")]
132    #[diagnostic(help("try uploading a rockspec with a different version"))]
133    RockExists(Url),
134    #[error("unable to read rockspec")]
135    #[diagnostic(help("check that the rockspec exists and is readable"))]
136    RockspecRead(#[from] std::io::Error),
137    #[cfg(feature = "gpgme")]
138    #[error("GPG signing failed")]
139    #[diagnostic(help(
140        r#"ensure that a GPG agent is running and that a valid GPG signing key is registered.
141          if you'd like to skip the signing step, supply `--sign-protocol=none`
142        "#
143    ))]
144    Signature(#[from] gpgme::Error),
145    #[error(transparent)]
146    #[diagnostic(transparent)]
147    ToolCheck(#[from] check::tool::Error),
148    #[error(transparent)]
149    #[diagnostic(transparent)]
150    UserCheck(#[from] check::user::Error),
151    #[error(transparent)]
152    #[diagnostic(transparent)]
153    ApiKeyUnspecified(#[from] ApiKeyUnspecified),
154    #[error(transparent)]
155    #[diagnostic(transparent)]
156    ValidationError(#[from] rockspec::toml::Error),
157    #[error("unsupported version: '{0}'")]
158    #[diagnostic(help("Lux can upload packages with a SemVer version, 'dev' or 'scm'"))]
159    UnsupportedVersion(String),
160    #[error(transparent)]
161    #[diagnostic(transparent)]
162    Rockspec(#[from] rockspec::Error),
163    #[error("the maximum supported number of rockspec revisions per version has been exceeded")]
164    #[diagnostic(help("bump the version to a version that has not yet been published"))]
165    MaxSpecRevsExceeded,
166    #[error("rock already exists on server. Error downloading existing rockspec")]
167    #[diagnostic(forward(0))]
168    SearchAndDownload(#[from] Box<download::Error>),
169    #[error("error computing rockspec hash")]
170    Hash(io::Error),
171    #[error("the 2FA code '{0}' was rejected by the server: {1}")]
172    #[diagnostic(help("it may have expired; try again with a new code."))]
173    TfaCodeRejected(String, String),
174}
175
176impl From<download::Error> for Error {
177    fn from(source: download::Error) -> Self {
178        Self::SearchAndDownload(Box::new(source))
179    }
180}
181
182pub struct ApiKey(String);
183
184#[derive(Error, Debug, Diagnostic)]
185#[non_exhaustive]
186#[error("no API key provided")]
187#[diagnostic(help("please set the $LUX_API_KEY environment variable"))]
188pub struct ApiKeyUnspecified;
189
190impl ApiKey {
191    /// Retrieves the rocks API key from the `$LUX_API_KEY` environment
192    /// variable and seals it in this struct.
193    pub fn new() -> Result<Self, ApiKeyUnspecified> {
194        Ok(Self(
195            env::var("LUX_API_KEY").map_err(|_| ApiKeyUnspecified)?,
196        ))
197    }
198
199    /// Creates an API key from a [`String`].
200    ///
201    /// # Safety
202    ///
203    /// This struct is designed to be sealed without a [`Display`](std::fmt::Display) implementation
204    /// so that it can never accidentally be printed.
205    ///
206    /// Ensure that you do not do anything else with the API key string prior to sealing it in this
207    /// struct.
208    pub fn from(str: &str) -> Self {
209        Self(str.to_string())
210    }
211
212    /// Retrieves the underlying API key as a [`String`].
213    ///
214    /// # Safety
215    ///
216    /// Strings may accidentally be printed as part of its [`Display`](std::fmt::Display)
217    /// implementation. Ensure that you never pass this variable somewhere it may be displayed.
218    pub unsafe fn get(&self) -> &str {
219        &self.0
220    }
221}
222
223/// 2FA token.
224/// This struct is designed to be sealed without a [`Display`](std::fmt::Display) implementation
225/// so that it can never accidentally be printed.
226struct TfaToken(String);
227
228impl TfaToken {
229    /// Retrieves the underlying 2FA token as a [`String`].
230    ///
231    /// # Safety
232    ///
233    /// Strings may accidentally be printed as part of its [`Display`](std::fmt::Display)
234    /// implementation. Ensure that you never pass this variable somewhere it may be displayed.
235    unsafe fn get(&self) -> &str {
236        &self.0
237    }
238}
239
240impl<'de> Deserialize<'de> for TfaToken {
241    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
242    where
243        D: serde::Deserializer<'de>,
244    {
245        String::deserialize(deserializer).map(Self)
246    }
247}
248
249#[derive(Deserialize)]
250struct LuarocksTfaVerificationSuccess {
251    tfa_token: TfaToken,
252}
253
254/// Models the response received from luarocks.org
255#[derive(Deserialize)]
256#[serde(untagged)]
257enum LuarocksTfaVerificationResponse {
258    Success(LuarocksTfaVerificationSuccess),
259    Failure(LuarocksErrorResponse),
260}
261
262#[derive(Deserialize)]
263struct LuarocksErrorResponse {
264    errors: Vec<String>,
265}
266
267#[derive(Serialize_enum_str, Clone, PartialEq, Eq)]
268#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
269#[cfg_attr(feature = "clap", clap(rename_all = "lowercase"))]
270#[serde(rename_all = "lowercase")]
271#[derive(Default)]
272#[cfg(not(feature = "gpgme"))]
273pub enum SignatureProtocol {
274    #[default]
275    None,
276}
277
278#[derive(Serialize_enum_str, Clone, PartialEq, Eq, EnumIter)]
279#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
280#[cfg_attr(feature = "clap", clap(rename_all = "lowercase"))]
281#[serde(rename_all = "lowercase")]
282#[derive(Default)]
283#[cfg(feature = "gpgme")]
284pub enum SignatureProtocol {
285    None,
286    Assuan,
287    CMS,
288    G13,
289    GPGConf,
290    #[default]
291    OpenPGP,
292    Spawn,
293    UIServer,
294}
295
296#[cfg(feature = "gpgme")]
297impl From<SignatureProtocol> for gpgme::Protocol {
298    fn from(val: SignatureProtocol) -> Self {
299        match val {
300            SignatureProtocol::OpenPGP => gpgme::Protocol::OpenPgp,
301            SignatureProtocol::CMS => gpgme::Protocol::Cms,
302            SignatureProtocol::GPGConf => gpgme::Protocol::GpgConf,
303            SignatureProtocol::Assuan => gpgme::Protocol::Assuan,
304            SignatureProtocol::G13 => gpgme::Protocol::G13,
305            SignatureProtocol::UIServer => gpgme::Protocol::UiServer,
306            SignatureProtocol::Spawn => gpgme::Protocol::Spawn,
307            SignatureProtocol::None => {
308                unreachable!("cannot convert SignatureProtocol::None to a gpgme::Protocol")
309            }
310        }
311    }
312}
313
314#[tracing::instrument(
315    name = "Uploading",
316    level = "info",
317    skip_all,
318    fields(project = args.project.toml().package().to_string()),
319)]
320async fn upload_from_project(args: ProjectUpload<'_>) -> Result<PreparedRockspec, Error> {
321    let project = args.project;
322    let api_key = args.api_key.unwrap_or(ApiKey::new()?);
323    let config = args.config;
324    let package_db = args.package_db;
325
326    let client = config.https_client()?;
327
328    check::tool::ensure_version(client, config.server()).await?;
329    check::user::ensure(client, &api_key, config.server()).await?;
330
331    let (rockspec, rockspec_content) =
332        helpers::generate_rockspec(project, client, &api_key, config, package_db).await?;
333
334    #[cfg(feature = "gpgme")]
335    let protocol = args.sign_protocol;
336    #[cfg(not(feature = "gpgme"))]
337    let protocol = SignatureProtocol::None;
338
339    let signed = sign_rockspec(&rockspec_content, protocol)?;
340
341    upload_rockspec_content(
342        config,
343        client,
344        &api_key,
345        PreparedRockspec {
346            package: rockspec.package().clone(),
347            version: rockspec.version().clone(),
348            content: rockspec_content,
349        },
350        signed,
351        args.tfa_code,
352        args.mode,
353    )
354    .await
355}
356
357#[tracing::instrument(
358    name = "Uploading",
359    level = "info",
360    skip_all,
361    fields(package = args.rockspec.package().to_string()),
362)]
363async fn upload_from_rockspec(args: RockspecUpload<'_>) -> Result<PreparedRockspec, Error> {
364    let rockspec = args.rockspec;
365    let api_key = args.api_key.unwrap_or(ApiKey::new()?);
366    #[cfg(feature = "gpgme")]
367    let protocol = args.sign_protocol;
368    #[cfg(not(feature = "gpgme"))]
369    let protocol = SignatureProtocol::None;
370    let config = args.config;
371
372    let client = config.https_client()?;
373
374    check::tool::ensure_version(client, config.server()).await?;
375    check::user::ensure(client, &api_key, config.server()).await?;
376
377    if let package::Version::StringVer(ver) = rockspec.version() {
378        return Err(Error::UnsupportedVersion(ver.to_string()));
379    }
380
381    if check::rock::exists(
382        client,
383        &api_key,
384        rockspec.package(),
385        rockspec.version(),
386        config.server(),
387    )
388    .await?
389    {
390        return Err(Error::RockExists(config.server().clone()));
391    }
392
393    let rockspec_content = rockspec.to_lua_remote_rockspec_string()?;
394    let signed = sign_rockspec(&rockspec_content, protocol)?;
395
396    upload_rockspec_content(
397        config,
398        client,
399        &api_key,
400        PreparedRockspec {
401            package: rockspec.package().clone(),
402            version: rockspec.version().clone(),
403            content: rockspec_content,
404        },
405        signed,
406        args.tfa_code,
407        args.mode,
408    )
409    .await
410}
411
412/// The rockspec that was or would have been uploaded.
413#[derive(Debug)]
414pub struct PreparedRockspec {
415    pub package: package::Name,
416    pub version: package::Version,
417    pub content: String,
418}
419
420async fn upload_rockspec_content(
421    config: &Config,
422    client: &reqwest::Client,
423    api_key: &ApiKey,
424    rockspec: PreparedRockspec,
425    signed: Option<String>,
426    tfa_code: Option<String>,
427    mode: Mode,
428) -> Result<PreparedRockspec, Error> {
429    let request =
430        prepare_upload_request(config, client, api_key, &rockspec, signed, tfa_code).await?;
431    if matches!(mode, Mode::Upload) {
432        send_upload_request(config, request).await?;
433    }
434    Ok(rockspec)
435}
436
437async fn prepare_upload_request(
438    config: &Config,
439    client: &reqwest::Client,
440    api_key: &ApiKey,
441    rockspec: &PreparedRockspec,
442    signed: Option<String>,
443    tfa_code: Option<String>,
444) -> Result<reqwest::RequestBuilder, Error> {
445    let part = Part::text(rockspec.content.clone())
446        .file_name(format!(
447            "{}-{}.rockspec",
448            rockspec.package, rockspec.version
449        ))
450        .mime_str("application/octet-stream")?;
451
452    let multipart = {
453        let multipart = Form::new().part("rockspec_file", part);
454
455        match signed {
456            Some(signature) => {
457                let part = Part::text(signature).file_name("project.rockspec.sig");
458                multipart.part("rockspec_sig", part)
459            }
460            None => multipart,
461        }
462    };
463
464    let mut request = client
465        .post(unsafe { url_for_method(config.server(), api_key, "upload")? })
466        .multipart(multipart);
467
468    if let Some(code) = tfa_code {
469        let token = helpers::verify_tfa_code(client, config.server(), api_key, &code).await?;
470        request = request.header(TFA_TOKEN_HEADER, unsafe { token.get() });
471    }
472
473    Ok(request)
474}
475
476async fn send_upload_request(
477    config: &Config,
478    request: reqwest::RequestBuilder,
479) -> Result<(), Error> {
480    let response = request.send().await?;
481
482    let status = response.status();
483    if status.is_server_error() {
484        Err(Error::Server(config.server().clone(), status))
485    } else if status.is_success() {
486        Ok(())
487    } else {
488        let response = response.json::<LuarocksErrorResponse>().await?;
489        let errors = response.errors.into_iter().join("\n");
490        Err(Error::Client(config.server().clone(), errors))
491    }
492}
493
494#[cfg(feature = "gpgme")]
495fn sign_rockspec(
496    rockspec_content: &str,
497    protocol: SignatureProtocol,
498) -> Result<Option<String>, Error> {
499    if let SignatureProtocol::None = protocol {
500        return Ok(None);
501    }
502
503    let mut ctx = Context::from_protocol(protocol.into())?;
504    let mut signature = Data::new()?;
505
506    ctx.set_armor(true);
507    ctx.sign_detached(rockspec_content.to_owned(), &mut signature)?;
508
509    let mut signature_str = String::new();
510    signature.read_to_string(&mut signature_str)?;
511
512    Ok(Some(signature_str))
513}
514
515#[cfg(not(feature = "gpgme"))]
516fn sign_rockspec(
517    _rockspec_content: &str,
518    _protocol: SignatureProtocol,
519) -> Result<Option<String>, Error> {
520    Ok(None)
521}
522
523mod helpers {
524    use super::*;
525    use crate::hash::HasIntegrity;
526    use itertools::Itertools;
527    use reqwest::Client;
528    use rockspec::toml;
529    use ssri::Integrity;
530    use url::Url;
531
532    #[tracing::instrument(level = "trace", skip(client, api_key))]
533    pub(crate) async fn verify_tfa_code(
534        client: &Client,
535        server_url: &Url,
536        api_key: &ApiKey,
537        tfa_code: &str,
538    ) -> Result<TfaToken, Error> {
539        let response = client
540            .get(unsafe { url_for_method(server_url, api_key, "verify_tfa")? })
541            .query(&[("code", tfa_code)])
542            .send()
543            .await?;
544        let status = response.status();
545        if status.is_server_error() {
546            Err(Error::Server(server_url.clone(), status))
547        } else {
548            match response.json::<LuarocksTfaVerificationResponse>().await? {
549                LuarocksTfaVerificationResponse::Success(LuarocksTfaVerificationSuccess {
550                    tfa_token,
551                }) => Ok(tfa_token),
552                LuarocksTfaVerificationResponse::Failure(LuarocksErrorResponse { errors }) => Err(
553                    Error::TfaCodeRejected(tfa_code.to_string(), errors.into_iter().join("\n")),
554                ),
555            }
556        }
557    }
558
559    #[tracing::instrument(level = "trace", skip_all)]
560    pub(crate) async fn generate_rockspec(
561        project: &Project,
562        client: &Client,
563        api_key: &ApiKey,
564        config: &Config,
565        package_db: &PackageDB,
566    ) -> Result<(toml::Remote, String), Error> {
567        for specrev in SpecRevIterator::new() {
568            let rockspec = project.toml().into_remote(Some(specrev))?;
569
570            let rockspec_content = rockspec.to_lua_remote_rockspec_string()?;
571
572            if let package::Version::StringVer(ver) = rockspec.version() {
573                return Err(Error::UnsupportedVersion(ver.to_string()));
574            }
575            if check::rock::exists(
576                client,
577                api_key,
578                rockspec.package(),
579                rockspec.version(),
580                config.server(),
581            )
582            .await?
583            {
584                let package =
585                    package::Spec::new(rockspec.package().clone(), rockspec.version().clone());
586                let existing_rockspec = download::exact_rockspec(&package, package_db, config)
587                    .await?
588                    .rockspec;
589                let existing_rockspec_hash = existing_rockspec.hash().await.map_err(Error::Hash)?;
590                if existing_rockspec_hash
591                    .matches(&Integrity::from(&rockspec_content))
592                    .is_some()
593                {
594                    return Err(Error::RockExists(config.server().clone()));
595                }
596            } else {
597                return Ok((rockspec, rockspec_content));
598            }
599        }
600        Err(Error::MaxSpecRevsExceeded)
601    }
602}
603
604impl From<reqwest::Error> for Error {
605    fn from(err: reqwest::Error) -> Self {
606        Self::Request(err.into())
607    }
608}
609
610#[cfg(test)]
611mod test {
612    use crate::TOOL_VERSION;
613
614    use super::*;
615
616    use crate::config;
617    use crate::lua;
618    use assert_fs::prelude::*;
619    use httptest::matchers::{contains, request};
620    use httptest::responders::{json_encoded, status_code, Responder};
621    use httptest::{Expectation, Server};
622    use serial_test::serial;
623
624    #[cfg(feature = "gpgme")]
625    #[test]
626    fn signature_protocols_are_accepted_by_gpgme() {
627        use strum::IntoEnumIterator;
628
629        for protocol in SignatureProtocol::iter().filter(|p| p != &SignatureProtocol::None) {
630            let _ = gpgme::Context::from_protocol(protocol.into()).unwrap();
631        }
632    }
633
634    #[test]
635    fn test_deserialize_tfa_success() {
636        let response_str = r#"{
637    "success": true,
638    "expires": 1782939987,
639    "tfa_token": "dummy_token"
640}
641"#;
642        let result = serde_json::from_str(response_str).unwrap();
643        assert!(matches!(
644            result,
645            LuarocksTfaVerificationResponse::Success(LuarocksTfaVerificationSuccess { .. })
646        ));
647    }
648
649    #[test]
650    fn test_deserialize_tfa_failure() {
651        let response_str = r#"{
652    "errors": [
653        "Invalid verification code"
654    ]
655}
656"#;
657        let result = serde_json::from_str(response_str).unwrap();
658        assert!(matches!(
659            result,
660            LuarocksTfaVerificationResponse::Failure(LuarocksErrorResponse { .. })
661        ));
662    }
663
664    #[test]
665    fn test_deserialize_luarocks_error_response() {
666        let response_str = r#"{
667    "errors": [
668        "Invalid verification code"
669    ]
670}
671"#;
672        let result = serde_json::from_str(response_str).unwrap();
673        assert!(matches!(result, LuarocksErrorResponse { .. }));
674    }
675
676    const API_KEY: &str = "test-api-key";
677    const TOOL_VERSION_PATH: &str = "/api/tool_version";
678    const STATUS_PATH: &str = "/api/1/test-api-key/status";
679    const CHECK_ROCKSPEC_PATH: &str = "/api/1/test-api-key/check_rockspec";
680    const VERIFY_TFA_PATH: &str = "/api/1/test-api-key/verify_tfa";
681    const UPLOAD_PATH: &str = "/api/1/test-api-key/upload";
682
683    async fn ready(
684        server: &Server,
685    ) -> (
686        assert_fs::TempDir,
687        assert_fs::TempDir,
688        Project,
689        Config,
690        PackageDB,
691    ) {
692        std::env::set_var("LUX_API_KEY", API_KEY);
693        let project_dir = assert_fs::TempDir::new().unwrap();
694        project_dir
695            .child("lux.toml")
696            .write_str(
697                r#"
698package = "foo"
699version = "1.0.0"
700lua = ">=5.1"
701
702[source]
703url = "https://example.com/foo.zip"
704
705[build]
706type = "builtin"
707"#,
708            )
709            .unwrap();
710        let project = Project::from_exact(project_dir.path()).unwrap().unwrap();
711
712        let config_dir = assert_fs::TempDir::new().unwrap();
713        let config = config::Builder::default()
714            .server(Some(Url::parse(&server.url_str("/")).unwrap()))
715            .data_dir(Some(config_dir.path().to_path_buf()))
716            .cache_dir(Some(config_dir.path().to_path_buf()))
717            .lua_version(Some(lua::Version::Lua51))
718            .build()
719            .unwrap();
720        let package_db = PackageDB::from_config(&config).await.unwrap();
721
722        (project_dir, config_dir, project, config, package_db)
723    }
724
725    fn expect_tool_version(server: &Server, version: &str) {
726        server.expect(
727            Expectation::matching(request::path(TOOL_VERSION_PATH))
728                .respond_with(json_encoded(serde_json::json!({ "version": version }))),
729        );
730    }
731
732    fn expect_status(server: &Server, status: u16) {
733        server.expect(
734            Expectation::matching(request::path(STATUS_PATH)).respond_with(status_code(status)),
735        );
736    }
737
738    fn expect_rock_missing(server: &Server) {
739        server.expect(
740            Expectation::matching(request::path(CHECK_ROCKSPEC_PATH))
741                .respond_with(json_encoded(serde_json::json!({}))),
742        );
743    }
744
745    fn expect_upload(server: &Server, responder: impl Responder + 'static) {
746        server.expect(Expectation::matching(request::path(UPLOAD_PATH)).respond_with(responder));
747    }
748
749    async fn upload(
750        project: &Project,
751        config: &Config,
752        package_db: &PackageDB,
753        tfa_code: Option<String>,
754    ) -> Result<PreparedRockspec, Error> {
755        let upload = ProjectUpload::new()
756            .project(project)
757            .config(config)
758            .api_key(ApiKey::from(API_KEY))
759            .maybe_tfa_code(tfa_code)
760            .package_db(package_db);
761        #[cfg(feature = "gpgme")]
762        let upload = upload.sign_protocol(SignatureProtocol::None);
763        upload.upload_to_luarocks().await
764    }
765
766    #[tokio::test]
767    #[serial]
768    async fn test_upload_to_mock_server() {
769        let server = Server::run();
770        expect_tool_version(&server, TOOL_VERSION);
771        expect_status(&server, 200);
772        expect_rock_missing(&server);
773        expect_upload(&server, status_code(200));
774
775        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
776        upload(&project, &config, &package_db, None).await.unwrap();
777    }
778
779    #[tokio::test]
780    #[serial]
781    async fn test_generate_rockspec_auto_specrev_increment() {
782        let server = Server::run();
783        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
784
785        for revision in 1..3 {
786            server.expect(
787                Expectation::matching(httptest::matchers::all_of![
788                    request::path(CHECK_ROCKSPEC_PATH),
789                    request::query(httptest::matchers::url_decoded(contains((
790                        "version",
791                        format!("1.0.0-{revision}"),
792                    )))),
793                ])
794                .respond_with(json_encoded(serde_json::json!({
795                    "module": {},
796                    "version": {},
797                }))),
798            );
799        }
800        server.expect(
801            Expectation::matching(httptest::matchers::all_of![
802                request::path(CHECK_ROCKSPEC_PATH),
803                request::query(httptest::matchers::url_decoded(contains((
804                    "version", "1.0.0-3",
805                )))),
806            ])
807            .respond_with(json_encoded(serde_json::json!({
808                "module": null,
809                "version": null,
810            }))),
811        );
812        server.expect(
813            Expectation::matching(request::path("/manifest-5.1.zip"))
814                .respond_with(status_code(404)),
815        );
816        server.expect(
817            Expectation::matching(request::path("/manifest-5.1")).respond_with(
818                status_code(200)
819                    .body(r#"repository = { foo = { ["1.0.0-2"] = { { arch = "rockspec" } } } }"#),
820            ),
821        );
822        for revision in 1u16..=2 {
823            let content = project
824                .toml()
825                .into_remote(Some(revision.into()))
826                .unwrap()
827                .to_lua_remote_rockspec_string()
828                .unwrap()
829                .replace("https://example.com/foo.zip", "https://example.com/old.zip");
830            server.expect(
831                Expectation::matching(request::path(format!("/foo-1.0.0-{revision}.rockspec")))
832                    .respond_with(status_code(200).body(content)),
833            );
834        }
835
836        let (rockspec, _) = helpers::generate_rockspec(
837            &project,
838            &reqwest::Client::new(),
839            &ApiKey::from(API_KEY),
840            &config,
841            &package_db,
842        )
843        .await
844        .unwrap();
845
846        assert_eq!(rockspec.version().to_string(), "1.0.0-3");
847    }
848
849    #[tokio::test]
850    #[serial]
851    async fn test_upload_forwards_tfa_token_header() {
852        let server = Server::run();
853        expect_tool_version(&server, TOOL_VERSION);
854        expect_status(&server, 200);
855        expect_rock_missing(&server);
856        server.expect(
857            Expectation::matching(request::path(VERIFY_TFA_PATH)).respond_with(json_encoded(
858                serde_json::json!({ "success": true, "tfa_token": "tfa-token-123" }),
859            )),
860        );
861        server.expect(
862            Expectation::matching(request::headers(contains(("x-tfa-token", "tfa-token-123"))))
863                .respond_with(status_code(200)),
864        );
865
866        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
867        upload(&project, &config, &package_db, Some("123456".into()))
868            .await
869            .unwrap();
870    }
871
872    #[tokio::test]
873    #[serial]
874    async fn test_upload_rejected_tfa_code() {
875        let server = Server::run();
876        expect_tool_version(&server, TOOL_VERSION);
877        expect_status(&server, 200);
878        expect_rock_missing(&server);
879        server.expect(
880            Expectation::matching(request::path(VERIFY_TFA_PATH)).respond_with(json_encoded(
881                serde_json::json!({ "errors": ["Invalid verification code"] }),
882            )),
883        );
884
885        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
886        let err = upload(&project, &config, &package_db, Some("000000".into()))
887            .await
888            .unwrap_err();
889        assert!(matches!(err, Error::TfaCodeRejected(..)));
890    }
891
892    #[tokio::test]
893    #[serial]
894    async fn test_upload_server_error() {
895        let server = Server::run();
896        expect_tool_version(&server, TOOL_VERSION);
897        expect_status(&server, 200);
898        expect_rock_missing(&server);
899        expect_upload(&server, status_code(500));
900
901        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
902        let err = upload(&project, &config, &package_db, None)
903            .await
904            .unwrap_err();
905        assert!(matches!(
906            err,
907            Error::Server(_, StatusCode::INTERNAL_SERVER_ERROR)
908        ));
909    }
910
911    #[tokio::test]
912    #[serial]
913    async fn test_upload_client_error() {
914        let server = Server::run();
915        expect_tool_version(&server, TOOL_VERSION);
916        expect_status(&server, 200);
917        expect_rock_missing(&server);
918        expect_upload(
919            &server,
920            status_code(400)
921                .append_header("Content-Type", "application/json")
922                .body(r#"{"errors":["invalid rockspec"]}"#),
923        );
924
925        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
926        let err = upload(&project, &config, &package_db, None)
927            .await
928            .unwrap_err();
929        match err {
930            Error::Client(_, message) => assert_eq!(message, "invalid rockspec"),
931            other => panic!("unexpected error: {other:?}"),
932        }
933    }
934
935    #[tokio::test]
936    #[serial]
937    async fn test_upload_outdated_tool_version() {
938        let server = Server::run();
939        expect_tool_version(&server, "0.0.1");
940
941        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
942        let err = upload(&project, &config, &package_db, None)
943            .await
944            .unwrap_err();
945        assert!(matches!(
946            err,
947            Error::ToolCheck(check::tool::Error::ToolOutdated(..))
948        ));
949    }
950
951    #[tokio::test]
952    #[serial]
953    async fn test_upload_unknown_user() {
954        let server = Server::run();
955        expect_tool_version(&server, TOOL_VERSION);
956        expect_status(&server, 401);
957
958        let (_project_dir, _config_dir, project, config, package_db) = ready(&server).await;
959        let err = upload(&project, &config, &package_db, None)
960            .await
961            .unwrap_err();
962        assert!(matches!(
963            err,
964            Error::UserCheck(check::user::Error::UserNotFound)
965        ));
966    }
967}