Skip to content

Commit

Permalink
Use authorization header if provided to auth proxy
Browse files Browse the repository at this point in the history
Signed-off-by: James Rhodes <[email protected]>
  • Loading branch information
jarhodes314 committed Oct 12, 2023
1 parent 15ebabb commit e44677a
Showing 1 changed file with 41 additions and 9 deletions.
50 changes: 41 additions & 9 deletions crates/extensions/c8y_auth_proxy/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ async fn respond_to(
Some(Path(p)) => p.as_str(),
None => "",
};
let auth: fn(reqwest::RequestBuilder, &str) -> reqwest::RequestBuilder =
if headers.contains_key("Authorization") {
|req, _token| req
} else {
|req, token| req.bearer_auth(token)
};

// Cumulocity revokes the device token if we access parts of the frontend UI,
// so deny requests to these proactively
Expand Down Expand Up @@ -152,23 +158,25 @@ async fn respond_to(
}
}

let send_request = |body, token| {
client
.request(method.to_owned(), &destination)
.headers(headers.clone())
.bearer_auth(&token)
.body(body)
.send()
let send_request = |body, token: &str| {
auth(
client
.request(method.to_owned(), &destination)
.headers(headers.clone()),
token,
)
.body(body)
.send()
};
let mut res = send_request(body, token.clone())
let mut res = send_request(body, &token)
.await
.into_diagnostic()
.wrap_err_with(|| format!("making proxied request to {destination}"))?;

if res.status() == StatusCode::UNAUTHORIZED {
token = retrieve_token.not_matching(Some(&token)).await;
if let Some(body) = body_clone {
res = send_request(Body::from(body), token.clone())
res = send_request(Body::from(body), &token)
.await
.into_diagnostic()
.wrap_err_with(|| format!("making proxied request to {destination}"))?;
Expand Down Expand Up @@ -277,6 +285,30 @@ mod tests {
assert_eq!(res.status(), 200);
}

#[tokio::test]
async fn uses_authorization_header_passed_by_user_if_one_is_provided() {
let _ = env_logger::try_init();
let mut server = mockito::Server::new();
let _mock = server
.mock("GET", "/inventory/managedObjects")
.match_header("authorization", "Basic dGVzdDp0ZXN0")
.with_status(200)
.create();

let port = start_server(&server, vec!["test-token"]);

let client = reqwest::Client::new();
let res = client
.get(format!(
"http://localhost:{port}/c8y/inventory/managedObjects"
))
.basic_auth("test", Some("test"))
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
}

#[tokio::test]
async fn retries_requests_with_small_bodies() {
let _ = env_logger::try_init();
Expand Down

0 comments on commit e44677a

Please sign in to comment.