Skip to content
Open
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ tokio-stream = { default-features = false, version = "0.1.16" }
# Local packages used as dependencies.
google-cloud-auth = { default-features = false, version = "1.9.0", path = "src/auth" }
google-cloud-gax = { default-features = false, version = "1.10.0", path = "src/gax" }
gaxi = { default-features = false, version = "0.7.12", path = "src/gax-internal", package = "google-cloud-gax-internal" }
gaxi = { default-features = false, version = "0.7.13", path = "src/gax-internal", package = "google-cloud-gax-internal" }
wkt = { default-features = false, version = "1.3.0", path = "src/wkt", package = "google-cloud-wkt" }
google-cloud-wkt = { default-features = false, version = "1.3.0", path = "src/wkt", package = "google-cloud-wkt" }
google-cloud-api = { default-features = false, version = "1.5.0", path = "src/generated/api/types" }
Expand Down
2 changes: 1 addition & 1 deletion src/gax-internal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

[package]
name = "google-cloud-gax-internal"
version = "0.7.12"
version = "0.7.13"
description = "Google Cloud Client Libraries for Rust - Implementation Details"
build = "build.rs"
# Inherit other attributes from the workspace.
Expand Down
18 changes: 13 additions & 5 deletions src/gax-internal/src/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ use std::time::Duration;

// A tonic::transport::Channel always has a Buffer layer.
const DEFAULT_REQUEST_BUFFER_CAPACITY: usize = 1024;
const X_GOOG_USER_PROJECT: &str = "x-goog-user-project";

pub type GrpcService = Channel;

Expand Down Expand Up @@ -529,19 +530,20 @@ impl Client {
.map_err(BuilderError::cred)
}

async fn add_auth_headers(&self, mut headers: http::HeaderMap) -> Result<http::HeaderMap> {
async fn add_auth_headers(&self, headers: http::HeaderMap) -> Result<http::HeaderMap> {
let h = self
.credentials
.headers(http::Extensions::new())
.await
.map_err(Error::authentication)?;

let CacheableResource::New { data, .. } = h else {
let CacheableResource::New { mut data, .. } = h else {
unreachable!("headers are not cached");
};

headers.extend(data);
Ok(headers)
// Note that client headers override credential headers (e.g. for `x-goog-user-project`).
data.extend(headers);
Ok(data)
}

async fn make_headers(
Expand All @@ -551,11 +553,17 @@ impl Client {
) -> Result<http::header::HeaderMap> {
let mut headers = HeaderMap::new();
if let Some(user_agent) = options.user_agent() {
headers.append(
headers.insert(
http::header::USER_AGENT,
http::header::HeaderValue::from_str(user_agent).map_err(Error::ser)?,
);
}
if let Some(user_project) = options.user_project() {
headers.insert(
http::header::HeaderName::from_static(X_GOOG_USER_PROJECT),
http::header::HeaderValue::from_str(user_project).map_err(Error::ser)?,
);
}
headers.append(
http::header::HeaderName::from_static("x-goog-api-client"),
http::header::HeaderValue::from_static(api_client_header),
Expand Down
32 changes: 21 additions & 11 deletions src/gax-internal/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ use std::sync::Arc;
use std::time::Duration;
use tracing::Instrument;

const X_GOOG_USER_PROJECT: &str = "x-goog-user-project";

#[derive(Clone, Debug)]
pub struct ReqwestClient {
inner: ::reqwest::Client,
Expand Down Expand Up @@ -386,24 +388,32 @@ impl ReqwestClient {
options: &RequestOptions,
remaining_time: Option<std::time::Duration>,
) -> Result<reqwest::Request> {
builder = if let Some(user_agent) = options.user_agent() {
builder.header(
reqwest::USER_AGENT,
reqwest::HeaderValue::from_str(user_agent).map_err(Error::ser)?,
)
} else {
builder
};

builder = effective_timeout(options, remaining_time)
.into_iter()
.fold(builder, |b, t| b.timeout(t));

builder = match self.cred.headers(Extensions::new()).await {
let mut headers = match self.cred.headers(Extensions::new()).await {
Err(e) => return Err(Error::authentication(e)),
Ok(CacheableResource::New { data, .. }) => builder.headers(data),
Ok(CacheableResource::New { data, .. }) => data,
Ok(CacheableResource::NotModified) => unreachable!("headers are not cached"),
};

if let Some(user_agent) = options.user_agent() {
headers.insert(
http::header::USER_AGENT,
http::header::HeaderValue::from_str(user_agent).map_err(Error::ser)?,
);
}

if let Some(user_project) = options.user_project() {
headers.insert(
http::header::HeaderName::from_static(X_GOOG_USER_PROJECT),
http::header::HeaderValue::from_str(user_project).map_err(Error::ser)?,
);
}

builder = builder.headers(headers);

builder.build().map_err(map_send_error)
Copy link
Copy Markdown
Contributor

@alvarowolfx alvarowolfx Apr 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as @dbolduc, I think we should add a method to the builder to allow overriding request level quota/user project. And maybe some similar code can be used in the gRPC part.

builder = quota_project(options)
            .into_iter()
            .fold(builder, |b, qp| b.header(X_GOOG_USER_PROJECT, qp));

fn quota_project(options: &crate::options::RequestOptions){
   options.get_extension::<UserProject>()
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

}

Expand Down
1 change: 0 additions & 1 deletion src/gax-internal/src/http/reqwest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ pub use reqwest::Request;
pub use reqwest::RequestBuilder;
pub use reqwest::Response;
pub use reqwest::StatusCode;
pub(crate) use reqwest::header::USER_AGENT;
pub use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
#[cfg(feature = "_internal-http-multipart")]
pub use reqwest::multipart;
143 changes: 143 additions & 0 deletions src/gax-internal/tests/grpc_user_project.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod mock_credentials;

#[cfg(all(test, feature = "_internal-grpc-client"))]
mod tests {
use super::mock_credentials::{MockCredentials, mock_credentials};
use google_cloud_auth::credentials::{CacheableResource, Credentials, EntityTag};
use google_cloud_gax::Result;
use google_cloud_gax::options::RequestOptions;
use google_cloud_gax_internal::grpc;
use grpc_server::{builder, google, start_echo_server};
use http::{HeaderMap, HeaderValue};

const X_GOOG_USER_PROJECT: &str = "x-goog-user-project";
const CRED_QUOTA_PROJECT: &str = "cred_quota_project";
const USER_PROJECT_NAME: &str = "project_lazy_dog";

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_project_emits_header() -> anyhow::Result<()> {
let (endpoint, _server) = start_echo_server().await?;
let client = builder(endpoint)
.with_credentials(mock_credentials())
.build()
.await?;

let mut options = RequestOptions::default();
options.set_user_project(USER_PROJECT_NAME);
let response = send_request(client, options).await?;
assert_eq!(
response
.metadata
.get(X_GOOG_USER_PROJECT)
.map(String::as_str),
Some(USER_PROJECT_NAME)
);
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn no_user_project_no_header() -> anyhow::Result<()> {
let (endpoint, _server) = start_echo_server().await?;
let client = builder(endpoint)
.with_credentials(mock_credentials())
.build()
.await?;

let response = send_request(client, RequestOptions::default()).await?;
assert!(
!response.metadata.contains_key(X_GOOG_USER_PROJECT),
"{:?}",
response.metadata
);
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_project_strips_credential_quota_project() -> anyhow::Result<()> {
let (endpoint, _server) = start_echo_server().await?;

let mut mock = MockCredentials::new();
mock.expect_headers().returning(|_exts| {
let mut map = HeaderMap::new();
map.insert(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer test-token"),
);
map.insert(
X_GOOG_USER_PROJECT,
HeaderValue::from_static(CRED_QUOTA_PROJECT),
);
Ok(CacheableResource::New {
data: map,
entity_tag: EntityTag::default(),
})
});
mock.expect_universe_domain().returning(|| None);

let client = builder(endpoint)
.with_credentials(Credentials::from(mock))
.build()
.await?;

let mut options = RequestOptions::default();
options.set_user_project(USER_PROJECT_NAME);
let response = send_request(client, options).await?;

assert_eq!(
response
.metadata
.get(X_GOOG_USER_PROJECT)
.map(String::as_str),
Some(USER_PROJECT_NAME)
);
assert!(
!response.metadata.values().any(|v| v == CRED_QUOTA_PROJECT),
"credential's quota_project value leaked onto the wire: {:?}",
response.metadata
);
Ok(())
}

async fn send_request(
client: grpc::Client,
options: RequestOptions,
) -> Result<google::test::v1::EchoResponse> {
let extensions = {
let mut e = tonic::Extensions::new();
e.insert(tonic::GrpcMethod::new(
"google.test.v1.EchoServices",
"Echo",
));
e
};
let request = google::test::v1::EchoRequest {
message: "message".into(),
..google::test::v1::EchoRequest::default()
};
client
.execute(
extensions,
http::uri::PathAndQuery::from_static("/google.test.v1.EchoService/Echo"),
request,
options,
"test-only-api-client/1.0",
"",
)
.await
.map(tonic::Response::into_inner)
}
}
Loading
Loading