Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass HTTP method to AuthChallenge #152

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 32 additions & 17 deletions ocipkg/src/distribution/auth.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, bail, Context, Result};

Check failure on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / clippy

unused import: `anyhow`

error: unused import: `anyhow` --> ocipkg/src/distribution/auth.rs:1:14 | 1 | use anyhow::{anyhow, bail, Context, Result}; | ^^^^^^ | = note: `-D unused-imports` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(unused_imports)]`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / doc

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / test

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / with-registry

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / pack

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / load

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / rust-lib

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / get

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / push

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / rust-exe

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / rust-exe

unused import: `anyhow`

Check warning on line 1 in ocipkg/src/distribution/auth.rs

View workflow job for this annotation

GitHub Actions / cpp-lib

unused import: `anyhow`
use base64::engine::{general_purpose::STANDARD, Engine};
use oci_spec::distribution::ErrorResponse;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -70,7 +70,7 @@
let test_url = url.join("/v2/").unwrap();
let challenge = match ureq::get(test_url.as_str()).call() {
Ok(_) => return Ok(None),
Err(e) => AuthChallenge::try_from(e)?,
Err(e) => AuthChallenge::from_err(e, "GET")?,
};
self.challenge(&challenge).map(Some)
}
Expand Down Expand Up @@ -162,6 +162,7 @@
///
/// let auth = AuthChallenge::from_header(
/// r#"Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:termoshtt/ocipkg/rust-lib:pull""#,
/// "GET"
/// ).unwrap();
///
/// assert_eq!(auth, AuthChallenge {
Expand All @@ -177,13 +178,15 @@
pub scope: String,
}

impl TryFrom<ureq::Error> for AuthChallenge {
type Error = anyhow::Error;
fn try_from(res: ureq::Error) -> Result<Self> {
match res {
impl AuthChallenge {
pub fn from_err(err: ureq::Error, http_method: &str) -> Result<Self> {
match err {
ureq::Error::Status(status, res) => {
if status == 401 && res.has("www-authenticate") {
Self::from_header(res.header("www-authenticate").unwrap())
Self::from_header(
res.header("www-authenticate").expect("Already checked"),
http_method,
)
} else {
let err = res.into_json::<ErrorResponse>()?;
Err(err.into())
Expand All @@ -192,21 +195,23 @@
ureq::Error::Transport(e) => Err(e.into()),
}
}
}

impl AuthChallenge {
pub fn from_header(header: &str) -> Result<Self> {
let err = || anyhow!("Unsupported WWW-Authenticate header: {}", header);
let (ty, realm) = header.split_once(' ').ok_or_else(err)?;
pub fn from_header(header: &str, http_method: &str) -> Result<Self> {
let (ty, realm) = header
.split_once(' ')
.with_context(|| format!("Invalid WWW-Authenticate header: {header}"))?;

if ty != "Bearer" {
return Err(err());
bail!("Only Bearer authentication method is supported, required={ty}");
}

let mut url = None;
let mut service = None;
let mut scope = None;
for param in realm.split(',') {
let (key, value) = param.split_once('=').ok_or_else(err)?;
let (key, value) = param
.split_once('=')
.with_context(|| format!("Invalid param in WWW-Authenticate header: {param}"))?;
let value = value.trim_matches('"').to_string();
match key {
"realm" => url = Some(value),
Expand All @@ -215,10 +220,20 @@
_ => continue,
}
}
let url = url.context("realm is absent in WWW-Authenticate header")?;
let service = service.context("service is absent in WWW-Authenticate header")?;
let mut scope = scope.context("scope is absent in WWW-Authenticate header")?;
if http_method.to_lowercase() != "get" {
// ghcr.io returns `pull` scope even for POST and PUT requests
if scope.ends_with("pull") {
scope = format!("{}push", scope.trim_end_matches("pull"));
}
}
dbg!(&url, &service, &scope);
Ok(Self {
url: url.ok_or_else(err)?,
service: service.ok_or_else(err)?,
scope: scope.ok_or_else(err)?,
url,
service,
scope,
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion ocipkg/src/distribution/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl Client {
let try_req = req.clone();
let challenge = match try_req.call() {
Ok(res) => return Ok(res),
Err(e) => AuthChallenge::try_from(e)?,
Err(e) => AuthChallenge::from_err(e, req.method())?,
};
self.token = Some(self.auth.challenge(&challenge)?);
}
Expand Down
Loading