Debian Codegraph @

src/upload.rs

raw
1 //! The uploading logic was mostly reverse engineered; I wrote it down as
2 //! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api
3
4 use crate::build_context::hash_file;
5 use anyhow::{bail, Context, Result};
6 use base64::engine::general_purpose::STANDARD;
7 use base64::Engine;
8 use bytesize::ByteSize;
9 use configparser::ini::Ini;
10 use fs_err as fs;
11 use fs_err::File;
12 use multipart::client::lazy::Multipart;
13 use regex::Regex;
14 use serde::Deserialize;
15 use std::collections::HashMap;
16 use std::env;
17 #[cfg(any(feature = "native-tls", feature = "rustls"))]
18 use std::ffi::OsString;
19 use std::io;
20 use std::path::{Path, PathBuf};
21 use std::time::Duration;
22 use thiserror::Error;
23 use tracing::debug;
24
25 /// An account with a registry, possibly incomplete
26 #[derive(Debug, clap::Parser)]
27 pub struct PublishOpt {
28 /// The repository (package index) to upload the package to. Should be a section in the config file.
29 ///
30 /// Can also be set via MATURIN_REPOSITORY environment variable.
31 #[arg(short = 'r', long, env = "MATURIN_REPOSITORY", default_value = "pypi")]
32 repository: String,
33 /// The URL of the registry where the wheels are uploaded to. This overrides --repository.
34 ///
35 /// Can also be set via MATURIN_REPOSITORY_URL environment variable.
36 #[arg(long, env = "MATURIN_REPOSITORY_URL", overrides_with = "repository")]
37 repository_url: Option<String>,
38 /// Username for pypi or your custom registry.
39 ///
40 /// Can also be set via MATURIN_USERNAME environment variable.
41 ///
42 /// Set MATURIN_PYPI_TOKEN variable to use token-based authentication instead
43 #[arg(short, long, env = "MATURIN_USERNAME")]
44 username: Option<String>,
45 /// Password for pypi or your custom registry.
46 ///
47 /// Can also be set via MATURIN_PASSWORD environment variable.
48 #[arg(short, long, env = "MATURIN_PASSWORD", hide_env_values = true)]
49 password: Option<String>,
50 /// Continue uploading files if one already exists.
51 /// (Only valid when uploading to PyPI. Other implementations may not support this.)
52 #[arg(long)]
53 skip_existing: bool,
54 /// Do not interactively prompt for username/password if the required credentials are missing.
55 ///
56 /// Can also be set via MATURIN_NON_INTERACTIVE environment variable.
57 #[arg(long, env = "MATURIN_NON_INTERACTIVE")]
58 non_interactive: bool,
59 }
60
61 impl PublishOpt {
62 // Here we omit trailing slashes from the repository URL, which we'll add back in `complete_registry`
63 const DEFAULT_REPOSITORY_URL: &'static str = "https://upload.pypi.org/legacy";
64 const TEST_REPOSITORY_URL: &'static str = "https://test.pypi.org/legacy";
65
66 /// Set to non interactive mode if we're running on CI
67 pub fn non_interactive_on_ci(&mut self) {
68 if !self.non_interactive && env::var("CI").map(|v| v == "true").unwrap_or_default() {
69 eprintln!("🎛️ Running in non-interactive mode on CI");
70 self.non_interactive = true;
71 }
72 }
73 }
74
75 /// Error type for different types of errors that can happen when uploading a
76 /// wheel.
77 ///
78 /// The most interesting type is AuthenticationError because it allows asking
79 /// the user to reenter the password
80 #[derive(Error, Debug)]
81 #[error("Uploading to the registry failed")]
82 pub enum UploadError {
83 /// Any ureq error
84 #[error("Http error")]
85 UreqError(#[source] Box<ureq::Error>),
86 /// The registry returned a "403 Forbidden"
87 #[error("Username or password are incorrect")]
88 AuthenticationError(String),
89 /// Reading the wheel failed
90 #[error("IO Error")]
91 IoError(#[source] io::Error),
92 /// The registry returned something else than 200
93 #[error("Failed to upload the wheel with status {0}: {1}")]
94 StatusCodeError(String, String),
95 /// File already exists
96 #[error("File already exists: {0}")]
97 FileExistsError(String),
98 /// Read package metadata error
99 #[error("Could not read the metadata from the package at {0}")]
100 PkgInfoError(PathBuf, #[source] python_pkginfo::Error),
101 /// TLS error
102 #[cfg(feature = "native-tls")]
103 #[error("TLS Error")]
104 TlsError(#[source] native_tls::Error),
105 }
106
107 impl From<io::Error> for UploadError {
108 fn from(error: io::Error) -> Self {
109 UploadError::IoError(error)
110 }
111 }
112
113 impl From<ureq::Error> for UploadError {
114 fn from(error: ureq::Error) -> Self {
115 UploadError::UreqError(Box::new(error))
116 }
117 }
118
119 #[cfg(feature = "native-tls")]
120 impl From<native_tls::Error> for UploadError {
121 fn from(error: native_tls::Error) -> Self {
122 UploadError::TlsError(error)
123 }
124 }
125
126 /// A pip registry such as pypi or testpypi with associated credentials, used
127 /// for uploading wheels
128 #[derive(Debug, Clone, Eq, PartialEq)]
129 pub struct Registry {
130 /// The username
131 pub username: String,
132 /// The password
133 pub password: String,
134 /// The url endpoint for legacy uploading
135 pub url: String,
136 }
137
138 impl Registry {
139 /// Creates a new registry
140 pub fn new(username: String, password: String, url: String) -> Registry {
141 Registry {
142 username,
143 password,
144 url,
145 }
146 }
147 }
148
149 /// Attempts to fetch the password from the keyring (if enabled)
150 /// and falls back to the interactive password prompt.
151 fn get_password(_username: &str) -> String {
152 #[cfg(feature = "keyring")]
153 {
154 let service = env!("CARGO_PKG_NAME");
155 let keyring = keyring::Entry::new(service, _username);
156 if let Ok(password) = keyring.and_then(|keyring| keyring.get_password()) {
157 return password;
158 };
159 }
160
161 dialoguer::Password::new()
162 .with_prompt("Please enter your password")
163 .interact()
164 .unwrap_or_else(|_| {
165 // So we need this fallback for pycharm on windows
166 let mut password = String::new();
167 io::stdin()
168 .read_line(&mut password)
169 .expect("Failed to read line");
170 password.trim().to_string()
171 })
172 }
173
174 fn get_username() -> String {
175 eprintln!("Please enter your username:");
176 let mut line = String::new();
177 io::stdin().read_line(&mut line).unwrap();
178 line.trim().to_string()
179 }
180
181 fn load_pypirc() -> Ini {
182 let mut config = Ini::new();
183 if let Some(mut config_path) = dirs::home_dir() {
184 config_path.push(".pypirc");
185 if let Ok(pypirc) = fs::read_to_string(config_path.as_path()) {
186 let _ = config.read(pypirc);
187 }
188 }
189 config
190 }
191
192 fn load_pypi_cred_from_config(config: &Ini, registry_name: &str) -> Option<(String, String)> {
193 if let (Some(username), Some(password)) = (
194 config.get(registry_name, "username"),
195 config.get(registry_name, "password"),
196 ) {
197 return Some((username, password));
198 }
199 None
200 }
201
202 /// Gets the PyPI credentials from (in precedence order):
203 ///
204 /// 1. `MATURIN_PYPI_TOKEN` environment variable
205 /// 2. `.pypirc` config file
206 /// 3. maturin command arguments
207 /// 4. `MATURIN_USERNAME` and `MATURIN_PASSWORD` environment variables
208 /// 5. the password keyring
209 /// 6. interactive prompt
210 fn resolve_pypi_cred(
211 opt: &PublishOpt,
212 config: &Ini,
213 registry_name: Option<&str>,
214 registry_url: &str,
215 ) -> Result<(String, String)> {
216 // API token from environment variable takes priority
217 if let Ok(token) = env::var("MATURIN_PYPI_TOKEN") {
218 return Ok(("__token__".to_string(), token));
219 }
220
221 // Try to get a token via OIDC exchange
222 match resolve_pypi_token_via_oidc(registry_url) {
223 Ok(Some(token)) => {
224 eprintln!("🔐 Using trusted publisher for upload");
225 return Ok(("__token__".to_string(), token));
226 }
227 Ok(None) => {}
228 Err(e) => eprintln!("⚠️ Warning: Failed to resolve PyPI token via OIDC: {e}"),
229 }
230
231 if let Some((username, password)) =
232 registry_name.and_then(|name| load_pypi_cred_from_config(config, name))
233 {
234 eprintln!("🔐 Using credential in pypirc for upload");
235 return Ok((username, password));
236 }
237
238 // fallback to username and password
239 if opt.non_interactive && (opt.username.is_none() || opt.password.is_none()) {
240 bail!("Credentials not found and non-interactive mode is enabled");
241 }
242 let username = opt.username.clone().unwrap_or_else(get_username);
243 let password = opt
244 .password
245 .clone()
246 .unwrap_or_else(|| get_password(&username));
247 Ok((username, password))
248 }
249
250 #[derive(Debug, Deserialize)]
251 struct OidcAudienceResponse {
252 audience: String,
253 }
254
255 #[derive(Debug, Deserialize)]
256 struct OidcTokenResponse {
257 value: String,
258 }
259
260 #[derive(Debug, Deserialize)]
261 struct MintTokenResponse {
262 token: String,
263 }
264
265 /// Trusted Publisher support for GitHub Actions
266 fn resolve_pypi_token_via_oidc(registry_url: &str) -> Result<Option<String>> {
267 if env::var_os("GITHUB_ACTIONS").is_none() {
268 return Ok(None);
269 }
270 if let (Ok(req_token), Ok(req_url)) = (
271 env::var("ACTIONS_ID_TOKEN_REQUEST_TOKEN"),
272 env::var("ACTIONS_ID_TOKEN_REQUEST_URL"),
273 ) {
274 let registry_url = url::Url::parse(registry_url)?;
275 let mut audience_url = registry_url.clone();
276 audience_url.set_path("_/oidc/audience");
277 debug!("Requesting OIDC audience from {}", audience_url);
278 let agent = http_agent()?;
279 let audience_res = agent
280 .get(audience_url.as_str())
281 .timeout(Duration::from_secs(30))
282 .call()?;
283 if audience_res.status() == 404 {
284 // OIDC is not enabled/supported on this registry
285 return Ok(None);
286 }
287 let audience = audience_res.into_json::<OidcAudienceResponse>()?.audience;
288
289 debug!("Requesting OIDC token for {} from {}", audience, req_url);
290 let request_token_res: OidcTokenResponse = agent
291 .get(&req_url)
292 .query("audience", &audience)
293 .set("Authorization", &format!("bearer {req_token}"))
294 .timeout(Duration::from_secs(30))
295 .call()?
296 .into_json()?;
297 let oidc_token = request_token_res.value;
298
299 let mut mint_token_url = registry_url;
300 mint_token_url.set_path("_/oidc/github/mint-token");
301 debug!("Requesting API token from {}", mint_token_url);
302 let mut mint_token_req = HashMap::new();
303 mint_token_req.insert("token", oidc_token);
304 let mint_token_res = agent
305 .post(mint_token_url.as_str())
306 .timeout(Duration::from_secs(30))
307 .send_json(mint_token_req)?
308 .into_json::<MintTokenResponse>()?;
309 return Ok(Some(mint_token_res.token));
310 }
311 Ok(None)
312 }
313
314 /// Asks for username and password for a registry account where missing.
315 fn complete_registry(opt: &PublishOpt) -> Result<Registry> {
316 // load creds from pypirc if found
317 let pypirc = load_pypirc();
318 let (registry_name, registry_url) = if let Some(repository_url) = opt.repository_url.as_deref()
319 {
320 // to normalize URLs by removing trailing slashes
321 match repository_url.trim_end_matches('/') {
322 PublishOpt::DEFAULT_REPOSITORY_URL => (
323 Some("pypi"),
324 // Add trailing slash back
325 format!("{}/", PublishOpt::DEFAULT_REPOSITORY_URL),
326 ),
327 PublishOpt::TEST_REPOSITORY_URL => (
328 Some("testpypi"),
329 // Add trailing slash back
330 format!("{}/", PublishOpt::TEST_REPOSITORY_URL),
331 ),
332 _ => (None, repository_url.to_string()),
333 }
334 } else if let Some(url) = pypirc.get(&opt.repository, "repository") {
335 (Some(opt.repository.as_str()), url)
336 } else if opt.repository == "pypi" {
337 (
338 Some("pypi"),
339 // Add trailing slash back
340 format!("{}/", PublishOpt::DEFAULT_REPOSITORY_URL),
341 )
342 } else if opt.repository == "testpypi" {
343 (
344 Some("testpypi"),
345 // Add trailing slash back
346 format!("{}/", PublishOpt::TEST_REPOSITORY_URL),
347 )
348 } else {
349 bail!(
350 "Failed to get registry {} in .pypirc. \
351 Note: Your index didn't start with http:// or https://, \
352 which is required for non-pypirc indices.",
353 opt.repository
354 );
355 };
356 let (username, password) = resolve_pypi_cred(opt, &pypirc, registry_name, &registry_url)?;
357 let registry = Registry::new(username, password, registry_url);
358
359 Ok(registry)
360 }
361
362 /// Port of pip's `canonicalize_name`
363 /// https://github.com/pypa/pip/blob/b33e791742570215f15663410c3ed987d2253d5b/src/pip/_vendor/packaging/utils.py#L18-L25
364 fn canonicalize_name(name: &str) -> String {
365 Regex::new("[-_.]+")
366 .unwrap()
367 .replace_all(name, "-")
368 .to_lowercase()
369 }
370
371 #[cfg(any(feature = "native-tls", feature = "rustls"))]
372 fn tls_ca_bundle() -> Option<OsString> {
373 env::var_os("MATURIN_CA_BUNDLE")
374 .or_else(|| env::var_os("REQUESTS_CA_BUNDLE"))
375 .or_else(|| env::var_os("CURL_CA_BUNDLE"))
376 }
377
378 // Prefer rustls if both native-tls and rustls features are enabled
379 #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
380 #[allow(clippy::result_large_err)]
381 fn http_agent() -> Result<ureq::Agent, UploadError> {
382 use std::sync::Arc;
383
384 let mut builder = ureq::builder().try_proxy_from_env(true);
385 let mut tls_builder = native_tls::TlsConnector::builder();
386 if let Some(ca_bundle) = tls_ca_bundle() {
387 let mut reader = io::BufReader::new(File::open(ca_bundle)?);
388 for cert in rustls_pemfile::certs(&mut reader) {
389 let cert = cert?;
390 tls_builder.add_root_certificate(native_tls::Certificate::from_pem(&cert)?);
391 }
392 }
393 builder = builder.tls_connector(Arc::new(tls_builder.build()?));
394 Ok(builder.build())
395 }
396
397 #[cfg(feature = "rustls")]
398 #[allow(clippy::result_large_err)]
399 fn http_agent() -> Result<ureq::Agent, UploadError> {
400 use std::sync::Arc;
401
402 let builder = ureq::builder().try_proxy_from_env(true);
403 if let Some(ca_bundle) = tls_ca_bundle() {
404 let mut reader = io::BufReader::new(File::open(ca_bundle)?);
405 let certs = rustls_pemfile::certs(&mut reader).collect::<Result<Vec<_>, _>>()?;
406 let mut root_certs = rustls::RootCertStore::empty();
407 root_certs.add_parsable_certificates(certs);
408 let client_config = rustls::ClientConfig::builder()
409 .with_root_certificates(root_certs)
410 .with_no_client_auth();
411 Ok(builder.tls_config(Arc::new(client_config)).build())
412 } else {
413 Ok(builder.build())
414 }
415 }
416
417 #[cfg(not(any(feature = "native-tls", feature = "rustls")))]
418 #[allow(clippy::result_large_err)]
419 fn http_agent() -> Result<ureq::Agent, UploadError> {
420 let builder = ureq::builder().try_proxy_from_env(true);
421 Ok(builder.build())
422 }
423
424 /// Uploads a single wheel to the registry
425 #[allow(clippy::result_large_err)]
426 pub fn upload(registry: &Registry, wheel_path: &Path) -> Result<(), UploadError> {
427 let hash_hex = hash_file(wheel_path)?;
428
429 let dist = python_pkginfo::Distribution::new(wheel_path)
430 .map_err(|err| UploadError::PkgInfoError(wheel_path.to_owned(), err))?;
431 let metadata = dist.metadata();
432
433 let mut api_metadata = vec![
434 (":action", "file_upload".to_string()),
435 ("sha256_digest", hash_hex),
436 ("protocol_version", "1".to_string()),
437 ("metadata_version", metadata.metadata_version.clone()),
438 ("name", canonicalize_name(&metadata.name)),
439 ("version", metadata.version.clone()),
440 ("pyversion", dist.python_version().to_string()),
441 ("filetype", dist.r#type().to_string()),
442 ];
443
444 let mut add_option = |name, value: &Option<String>| {
445 if let Some(some) = value.clone() {
446 api_metadata.push((name, some));
447 }
448 };
449
450 // https://github.com/pypa/warehouse/blob/75061540e6ab5aae3f8758b569e926b6355abea8/warehouse/forklift/legacy.py#L424
451 add_option("summary", &metadata.summary);
452 add_option("description", &metadata.description);
453 add_option(
454 "description_content_type",
455 &metadata.description_content_type,
456 );
457 add_option("author", &metadata.author);
458 add_option("author_email", &metadata.author_email);
459 add_option("maintainer", &metadata.maintainer);
460 add_option("maintainer_email", &metadata.maintainer_email);
461 add_option("license", &metadata.license);
462 add_option("keywords", &metadata.keywords);
463 add_option("home_page", &metadata.home_page);
464 add_option("download_url", &metadata.download_url);
465 add_option("requires_python", &metadata.requires_python);
466
467 if metadata.requires_python.is_none() {
468 // GitLab PyPI repository API implementation requires this metadata field
469 // and twine always includes it in the request, even when it's empty.
470 api_metadata.push(("requires_python", "".to_string()));
471 }
472
473 let mut add_vec = |name, values: &[String]| {
474 for i in values {
475 api_metadata.push((name, i.clone()));
476 }
477 };
478
479 add_vec("classifiers", &metadata.classifiers);
480 add_vec("platform", &metadata.platforms);
481 add_vec("requires_dist", &metadata.requires_dist);
482 add_vec("provides_dist", &metadata.provides_dist);
483 add_vec("obsoletes_dist", &metadata.obsoletes_dist);
484 add_vec("requires_external", &metadata.requires_external);
485 add_vec("project_urls", &metadata.project_urls);
486
487 let wheel = File::open(wheel_path)?;
488 let wheel_name = wheel_path
489 .file_name()
490 .expect("Wheel path has a file name")
491 .to_string_lossy();
492
493 let mut form = Multipart::new();
494 for (key, value) in api_metadata {
495 form.add_text(key, value);
496 }
497
498 form.add_stream("content", &wheel, Some(wheel_name), None);
499 let multipart_data = form.prepare().map_err(|e| e.error)?;
500 let encoded = STANDARD.encode(format!("{}:{}", registry.username, registry.password));
501
502 let agent = http_agent()?;
503
504 let response = agent
505 .post(registry.url.as_str())
506 .set(
507 "Content-Type",
508 &format!(
509 "multipart/form-data; boundary={}",
510 multipart_data.boundary()
511 ),
512 )
513 .set(
514 "User-Agent",
515 &format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
516 )
517 .set("Authorization", &format!("Basic {encoded}"))
518 .send(multipart_data);
519
520 match response {
521 Ok(_) => Ok(()),
522 Err(ureq::Error::Status(status, response)) => {
523 let err_text = response.into_string().unwrap_or_else(|e| {
524 format!(
525 "The registry should return some text, \
526 even in case of an error, but didn't ({e})"
527 )
528 });
529 debug!("Upload error response: {}", err_text);
530 // Detect FileExistsError the way twine does
531 // https://github.com/pypa/twine/blob/87846e5777b380d4704704a69e1f9a7a1231451c/twine/commands/upload.py#L30
532 if status == 403 {
533 if err_text.contains("overwrite artifact") {
534 // Artifactory (https://jfrog.com/artifactory/)
535 Err(UploadError::FileExistsError(err_text))
536 } else {
537 Err(UploadError::AuthenticationError(err_text))
538 }
539 } else {
540 let status_string = status.to_string();
541 if status == 409 // conflict, pypiserver (https://pypi.org/project/pypiserver)
542 // PyPI / TestPyPI
543 || (status == 400 && err_text.contains("already exists"))
544 // Nexus Repository OSS (https://www.sonatype.com/nexus-repository-oss)
545 || (status == 400 && err_text.contains("updating asset"))
546 // # Gitlab Enterprise Edition (https://about.gitlab.com)
547 || (status == 400 && err_text.contains("already been taken"))
548 {
549 Err(UploadError::FileExistsError(err_text))
550 } else {
551 Err(UploadError::StatusCodeError(status_string, err_text))
552 }
553 }
554 }
555 Err(err) => Err(UploadError::UreqError(err.into())),
556 }
557 }
558
559 /// Handles authentication/keyring integration and retrying of the publish subcommand
560 pub fn upload_ui(items: &[PathBuf], publish: &PublishOpt) -> Result<()> {
561 let registry = complete_registry(publish)?;
562
563 eprintln!("🚀 Uploading {} packages", items.len());
564
565 let title_re = regex::Regex::new(r"<title>(.+?)</title>").unwrap();
566 for i in items {
567 let upload_result = upload(&registry, i);
568
569 match upload_result {
570 Ok(()) => (),
571 Err(UploadError::AuthenticationError(msg)) => {
572 let title = title_re
573 .captures(&msg)
574 .and_then(|c| c.get(1))
575 .map(|m| m.as_str());
576 match title {
577 Some(title) => {
578 eprintln!("⛔ {title}");
579 }
580 None => eprintln!("⛔ Username and/or password are wrong"),
581 }
582
583 #[cfg(feature = "keyring")]
584 {
585 // Delete the wrong password from the keyring
586 let old_username = registry.username;
587 match keyring::Entry::new(env!("CARGO_PKG_NAME"), &old_username)
588 .and_then(|keyring| keyring.delete_password())
589 {
590 Ok(()) => {
591 eprintln!("🔑 Removed wrong password from keyring")
592 }
593 Err(keyring::Error::NoEntry)
594 | Err(keyring::Error::NoStorageAccess(_))
595 | Err(keyring::Error::PlatformFailure(_)) => {}
596 Err(err) => {
597 eprintln!("⚠️ Warning: Failed to remove password from keyring: {err}")
598 }
599 }
600 }
601
602 bail!("Username and/or password are possibly wrong");
603 }
604 Err(err) => {
605 let filename = i.file_name().unwrap_or(i.as_os_str());
606 if let UploadError::FileExistsError(_) = err {
607 if publish.skip_existing {
608 eprintln!(
609 "⚠️ Note: Skipping {filename:?} because it appears to already exist"
610 );
611 continue;
612 }
613 }
614 let filesize = fs::metadata(i)
615 .map(|x| ByteSize(x.len()).to_string())
616 .unwrap_or_else(|e| format!("Failed to get the filesize of {:?}: {}", &i, e));
617 return Err(err).context(format!("💥 Failed to upload {filename:?} ({filesize})"));
618 }
619 }
620 }
621
622 eprintln!("✨ Packages uploaded successfully");
623
624 #[cfg(feature = "keyring")]
625 {
626 // We know the password is correct, so we can save it in the keyring
627 let username = registry.username.clone();
628 let password = registry.password;
629 match keyring::Entry::new(env!("CARGO_PKG_NAME"), &username)
630 .and_then(|keyring| keyring.set_password(&password))
631 {
632 Ok(())
633 | Err(keyring::Error::NoStorageAccess(_))
634 | Err(keyring::Error::PlatformFailure(_)) => {}
635 Err(err) => {
636 eprintln!("⚠️ Warning: Failed to store the password in the keyring: {err:?}");
637 }
638 }
639 }
640
641 Ok(())
642 }