use super::response::CredentialPartition;
use crate::error::{DepsError, Result};
use crate::net_policy::TrustedPrefix;
use crate::rate_limit::QuotaMeter;
use crate::redact::RedactedUrl;
use crate::secret::{AuthorizationValue, Redacted, auth_digest};
use reqwest::{Url, header};
use std::sync::Arc;
#[derive(Debug, Clone, Copy)]
pub enum RequestHeader {
Accept(&'static str),
}
#[derive(Debug, Clone, Copy)]
pub enum CredentialHeader<'a> {
Authorization(&'a AuthorizationValue),
GitlabPrivateToken(&'a Redacted),
}
impl CredentialHeader<'_> {
fn expose_secret(&self) -> &str {
match self {
Self::Authorization(value) => value.expose_secret(),
Self::GitlabPrivateToken(token) => token.expose_secret(),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RateLimitRevocation {
#[default]
Revokes,
Throttles,
}
impl RateLimitRevocation {
pub(super) fn revokes_credential(self, error: &DepsError) -> bool {
match error {
DepsError::HttpStatus {
status: 401 | 403, ..
} => true,
DepsError::RateLimited {
source_status: Some(401 | 403),
..
} => match self {
Self::Revokes => true,
Self::Throttles => false,
},
DepsError::HttpStatus { .. }
| DepsError::RateLimited { .. }
| DepsError::ParseError { .. }
| DepsError::RegistryError { .. }
| DepsError::InsecureScheme { .. }
| DepsError::BudgetExceeded(_)
| DepsError::RecentlyFailed
| DepsError::PackageNotFound { .. }
| DepsError::ApiResponse { .. }
| DepsError::ResponseTooLarge { .. }
| DepsError::InvalidVersionReq(_)
| DepsError::InvalidPackageName(_)
| DepsError::Io(_)
| DepsError::Json(_)
| DepsError::UnsupportedEcosystem(_)
| DepsError::AmbiguousEcosystem(_)
| DepsError::InvalidUri(_)
| DepsError::Offline { .. }
| DepsError::ChainResolutionHalted
| DepsError::PaginatedListIncomplete { .. }
| DepsError::CredentialOutsideTrustedPrefix { .. }
| DepsError::HostBlockedByPolicy { .. } => false,
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum RequestAuth<'a> {
Anonymous {
partition: Option<CredentialPartition>,
quota: Option<&'a Arc<QuotaMeter>>,
},
Credential {
header: CredentialHeader<'a>,
partition: CredentialPartition,
on_rate_limit: RateLimitRevocation,
quota: Option<&'a Arc<QuotaMeter>>,
},
}
impl<'a> RequestAuth<'a> {
pub const ANONYMOUS: Self = Self::anonymous(None);
#[must_use]
pub const fn anonymous(partition: Option<CredentialPartition>) -> Self {
Self::Anonymous {
partition,
quota: None,
}
}
#[must_use]
pub fn credential(header: CredentialHeader<'a>, prefix: &TrustedPrefix) -> Self {
Self::credential_in(
header,
CredentialPartition::new(auth_digest_of(prefix.as_str(), header.expose_secret())),
)
}
#[must_use]
pub const fn credential_in(
header: CredentialHeader<'a>,
partition: CredentialPartition,
) -> Self {
Self::Credential {
header,
partition,
on_rate_limit: RateLimitRevocation::Revokes,
quota: None,
}
}
#[must_use]
pub const fn with_rate_limit(self, on_rate_limit: RateLimitRevocation) -> Self {
match self {
Self::Credential {
header,
partition,
quota,
..
} => Self::Credential {
header,
partition,
on_rate_limit,
quota,
},
Self::Anonymous { .. } => self,
}
}
#[must_use]
pub const fn with_quota_meter(self, meter: &'a Arc<QuotaMeter>) -> Self {
match self {
Self::Anonymous { partition, .. } => Self::Anonymous {
partition,
quota: Some(meter),
},
Self::Credential {
header,
partition,
on_rate_limit,
..
} => Self::Credential {
header,
partition,
on_rate_limit,
quota: Some(meter),
},
}
}
pub(super) const fn quota(&self) -> Option<&'a Arc<QuotaMeter>> {
match *self {
Self::Anonymous { quota, .. } | Self::Credential { quota, .. } => quota,
}
}
pub(super) fn key_auth(&self) -> KeyAuth {
match *self {
Self::Anonymous { partition, .. } => KeyAuth::Anonymous(partition),
Self::Credential { partition, .. } => KeyAuth::Credential(partition),
}
}
pub(super) fn ensure_within(&self, url: &str, prefix: &TrustedPrefix) -> Result<()> {
match self {
Self::Anonymous { .. } => Ok(()),
Self::Credential { .. } => {
if Url::parse(url).is_ok_and(|parsed| prefix.permits(&parsed)) {
Ok(())
} else {
Err(DepsError::CredentialOutsideTrustedPrefix {
url: RedactedUrl::new(url),
})
}
}
}
}
pub(super) fn rate_limit(&self) -> RateLimitRevocation {
match *self {
Self::Anonymous { .. } => RateLimitRevocation::default(),
Self::Credential { on_rate_limit, .. } => on_rate_limit,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum KeyAuth {
Anonymous(Option<CredentialPartition>),
Credential(CredentialPartition),
}
impl KeyAuth {
pub(super) const ANONYMOUS: Self = Self::Anonymous(None);
pub(super) const fn is_credentialed(self) -> bool {
matches!(self, Self::Credential(_))
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum WireHeader<'a> {
Accept(&'static str),
Credential(CredentialHeader<'a>),
}
impl From<RequestHeader> for WireHeader<'_> {
fn from(header: RequestHeader) -> Self {
match header {
RequestHeader::Accept(value) => Self::Accept(value),
}
}
}
pub(super) fn wire_headers<'a>(
accept: &[RequestHeader],
auth: &RequestAuth<'a>,
) -> Vec<WireHeader<'a>> {
let mut headers: Vec<WireHeader<'a>> = wire_accept_headers(accept);
match auth {
RequestAuth::Credential { header, .. } => headers.push(WireHeader::Credential(*header)),
RequestAuth::Anonymous { .. } => {}
}
headers
}
pub(super) fn wire_accept_headers(accept: &[RequestHeader]) -> Vec<WireHeader<'static>> {
accept.iter().copied().map(WireHeader::from).collect()
}
pub(super) fn accept_headers(accept: Option<&'static str>) -> Vec<RequestHeader> {
accept.map(RequestHeader::Accept).into_iter().collect()
}
fn auth_digest_of(origin: &str, secret: &str) -> u64 {
auth_digest(origin, Some(secret)).unwrap_or_default()
}
fn sensitive_header(
request: reqwest::RequestBuilder,
name: header::HeaderName,
secret: &str,
) -> reqwest::RequestBuilder {
match header::HeaderValue::from_str(secret) {
Ok(mut value) => {
value.set_sensitive(true);
request.header(name, value)
}
Err(_) => request.header(name, secret),
}
}
pub(super) fn apply_request_headers(
mut request: reqwest::RequestBuilder,
headers: &[WireHeader<'_>],
) -> reqwest::RequestBuilder {
for header in headers {
request = match header {
WireHeader::Accept(value) => request.header(header::ACCEPT, *value),
WireHeader::Credential(CredentialHeader::Authorization(value)) => {
sensitive_header(request, header::AUTHORIZATION, value.expose_secret())
}
WireHeader::Credential(CredentialHeader::GitlabPrivateToken(token)) => {
sensitive_header(
request,
header::HeaderName::from_static("private-token"),
token.expose_secret(),
)
}
};
}
request
}