Skip to content
Merged
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
5 changes: 5 additions & 0 deletions THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,11 @@ uses `x-goog-content-sha256` if supplied and `UNSIGNED-PAYLOAD` otherwise. For
IAM `signBlob`, the OAuth token must cover the signing RPC. The resulting URL
has its own expiration.

Cloud Storage V4 POST policies sign the standard Base64 representation of the
UTF-8 JSON bytes supplied by the caller. The caller selects the policy
conditions, expiration, and multipart upload target. Signed policy fields
carry upload authority and are redacted from Reqsign's `Debug` output.

Provider-side acceptance or rejection is not by itself the security boundary.
A compatibility bug that causes a legitimate request to fail may be a normal
bug. It becomes security-relevant when it grants unintended authority, signs a
Expand Down
22 changes: 17 additions & 5 deletions services/google/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ Google Cloud Platform signing implementation for reqsign.
The default Application Default Credentials chain checks
`GOOGLE_APPLICATION_CREDENTIALS`, the well-known gcloud credentials file, and
the Compute Engine metadata service. `RequestSigner` supports OAuth access
tokens, GCS V4 signed URLs, and opt-in credentials for ID token, direct JWT,
and API key authentication.
tokens, GCS V4 signed URLs and POST policies, and opt-in credentials for ID
token, direct JWT, and API key authentication.

> Service-account JWTs and GCS V4 signatures need a `CryptoProvider` from the
> `Context`. Bind one with `Context::with_crypto`, install a process-wide default,
> Service-account JWTs, GCS V4 signed URLs, and locally signed POST policies
> need a `CryptoProvider` from the `Context`. Bind one with
> `Context::with_crypto`, install a process-wide default,
> or use a facade
> `default_context()`, which binds RustCrypto when the global slot is empty. See
> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md).
Expand Down Expand Up @@ -66,13 +67,24 @@ For a complete runnable example that mocks the STS exchange and calls
[`ClientSideCredentialAccessBoundaryGranter`](https://docs.rs/reqsign-google/latest/reqsign_google/struct.ClientSideCredentialAccessBoundaryGranter.html)
rustdoc.

For remote GCS V4 URL signing via IAM Credentials `signBlob`, an email set
For remote GCS V4 signing via IAM Credentials `signBlob`, an email set
with `RequestSigner::with_signer_email` takes precedence over the credential's
known identity. When neither is available, remote signing uses the credential's
issuing metadata source to fetch the email and caches a successful lookup on
that credential. A refreshed credential resolves the email on its first remote
signing request. OAuth bearer authentication makes no email lookup.

## GCS V4 POST policies

For browser uploads, use `RequestSigner::new("storage")` and choose a
signing time. Use `post_policy_signing_fields` to obtain the values for the
policy's `x-goog-algorithm`, `x-goog-credential`, and `x-goog-date` conditions.
Pass the same credential and time to `sign_post_policy` with the serialized
UTF-8 policy JSON. Use `SignedPostPolicy::into_fields` to add the five
authentication fields to the form. The application chooses the upload URL,
policy expiration and conditions, and constructs the multipart body.
[Cloud Storage POST form fields](https://cloud.google.com/storage/docs/xml-api/post-object-forms#form_fields)

## Select a header credential

Use `IdTokenCredentialProvider` to acquire an ID token for a fixed audience and
Expand Down
2 changes: 1 addition & 1 deletion services/google/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub use service_account_impersonation::{
};

mod sign_request;
pub use sign_request::RequestSigner;
pub use sign_request::{RequestSigner, SignedPostPolicy};

mod provide_credential;
pub use provide_credential::{
Expand Down
167 changes: 96 additions & 71 deletions services/google/src/sign_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ use crate::jwt::{Purpose, sign_service_account_jwt};
use crate::provide_credential::oauth::{
OAUTH_TOKEN_ENDPOINT, bearer_header, checked_expiration, exchange_jwt_bearer, resolve_scope,
};
use crate::provide_credential::vm_metadata::MetadataSource;

mod post_policy;
pub use post_policy::SignedPostPolicy;

const GCS_V4_ALGORITHM: &str = "GOOG4-RSA-SHA256";
const GOOGLE_CLOUD_QUOTA_PROJECT: &str = "GOOGLE_CLOUD_QUOTA_PROJECT";
const USER_PROJECT_HEADER: &str = "x-goog-user-project";
const API_KEY_HEADER: &str = "x-goog-api-key";
Expand Down Expand Up @@ -167,6 +172,28 @@ impl Drop for RefreshLockLease {
}
}

enum GcsV4SigningKey<'a> {
Local(&'a ServiceAccount),
Remote {
token: &'a Token,
signer_email: SignerEmail<'a>,
},
}

enum SignerEmail<'a> {
Known(&'a str),
FromMetadata(&'a MetadataSource),
}

impl<'a> SignerEmail<'a> {
async fn resolve(&self) -> Result<Cow<'a, str>> {
match self {
Self::Known(email) => Ok(Cow::Borrowed(email)),
Self::FromMetadata(source) => Ok(Cow::Owned(source.signer_email().await?)),
}
}
}

/// RequestSigner for Google service requests.
///
/// When signing requests for header authentication with a [`ServiceAccount`] credential,
Expand Down Expand Up @@ -225,11 +252,10 @@ impl RequestSigner {
self
}

/// Set the signer service account email used for query signing via IAMCredentials `signBlob`.
/// Set the service-account email for signing GCS V4 URLs and POST policies via IAM `signBlob`.
///
/// This explicitly configured email takes precedence over a signer email discovered by the
/// credential provider. It is required when generating signed URLs from a token whose provider
/// cannot determine the signer identity.
/// credential provider. Set it when the token's provider cannot determine the signer identity.
pub fn with_signer_email(mut self, signer_email: impl Into<String>) -> Self {
self.signer_email = Some(signer_email.into());
self
Expand Down Expand Up @@ -423,6 +449,31 @@ impl RequestSigner {
Ok((header::AUTHORIZATION, bearer_header(token.access_token())?))
}

fn gcs_v4_signing_key<'a>(&'a self, credential: &'a Credential) -> Option<GcsV4SigningKey<'a>> {
if let Some(key) = credential.service_account().filter(|key| key.is_valid()) {
return Some(GcsV4SigningKey::Local(key));
}

let token = credential.token()?;
let signer_email = match self.signer_email.as_deref().or(credential.signer_email()) {
Some(email) => SignerEmail::Known(email),
None => SignerEmail::FromMetadata(credential.metadata_source()?),
};
Some(GcsV4SigningKey::Remote {
token,
signer_email,
})
}

fn gcs_v4_scope(&self, time: Timestamp) -> String {
format!(
"{}/{}/{}/goog4_request",
time.format_date(),
self.region,
self.service
)
}

fn build_string_to_sign(
&self,
provider: &dyn crypto::CryptoProvider,
Expand All @@ -433,30 +484,18 @@ impl RequestSigner {
) -> Result<(String, Vec<(String, String)>)> {
ensure_host_header(req)?;

let authentication_query = authentication_query(
req,
client_email,
now,
expires_seconds,
&self.service,
&self.region,
);
let scope = self.gcs_v4_scope(now);
let authentication_query =
authentication_query(req, client_email, now, expires_seconds, &scope);
let canonical_query = canonicalize_query(req, &authentication_query);

let creq = canonical_request_string(req, &canonical_query)?;
let encoded_req = hex_sha256(provider, creq.as_bytes())?;

let scope = format!(
"{}/{}/{}/goog4_request",
now.format_date(),
self.region,
self.service
);
debug!("calculated scope: {scope}");

let string_to_sign = {
let mut f = String::new();
f.push_str("GOOG4-RSA-SHA256");
f.push_str(GCS_V4_ALGORITHM);
f.push('\n');
f.push_str(&now.format_iso8601());
f.push('\n');
Expand All @@ -473,10 +512,9 @@ impl RequestSigner {
fn sign_with_service_account(
provider: &dyn crypto::CryptoProvider,
private_key_pem: &str,
string_to_sign: &str,
payload: &[u8],
) -> Result<String> {
let signature = provider
.rsa_pkcs1v15_sha256_sign(private_key_pem.as_bytes(), string_to_sign.as_bytes())?;
let signature = provider.rsa_pkcs1v15_sha256_sign(private_key_pem.as_bytes(), payload)?;

Ok(hex::encode(signature))
}
Expand All @@ -502,7 +540,7 @@ impl RequestSigner {
let signature = Self::sign_with_service_account(
provider,
service_account.private_key(),
&string_to_sign,
string_to_sign.as_bytes(),
)?;

let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?;
Expand All @@ -512,6 +550,15 @@ impl RequestSigner {
Ok((req, final_uri))
}

fn validate_sign_blob_token(&self, token: &Token) -> Result<()> {
if !token.is_valid_at(self.token_required_until()) {
return Err(Error::credential_invalid(
"IAM Credentials signBlob requires an OAuth token valid for the RPC",
));
}
Ok(())
}

async fn sign_via_iamcredentials(
&self,
ctx: &Context,
Expand Down Expand Up @@ -549,11 +596,7 @@ impl RequestSigner {
.body(body.into())
.map_err(|_| Error::unexpected("failed to build signBlob request"))?;

if !token.is_valid_at(self.token_required_until()) {
return Err(Error::credential_invalid(
"IAM Credentials signBlob requires an OAuth token valid for the RPC",
));
}
self.validate_sign_blob_token(token)?;
let resp = ctx.http_send(req).await.map_err(|err| {
Error::new(err.kind(), "IAM Credentials signBlob request failed")
.set_retryable(err.is_retryable())
Expand Down Expand Up @@ -650,44 +693,33 @@ impl SignRequest for RequestSigner {
return self.sign_headers(ctx, req, credential).await;
};

let (signing_req, uri) = if let Some(key) =
credential.service_account().filter(|key| key.is_valid())
{
let expires_seconds = query_expiration_seconds(expires)?;
self.build_signed_query_with_service_account(
let key = self.gcs_v4_signing_key(credential).ok_or_else(|| {
Error::credential_invalid(
"GCS V4 URL signing requires a local service-account key or an OAuth token with signer identity",
)
})?;
let expires_seconds = query_expiration_seconds(expires)?;
let (signing_req, uri) = match key {
GcsV4SigningKey::Local(key) => self.build_signed_query_with_service_account(
ctx.crypto_provider()?,
req,
key,
expires_seconds,
)?
} else {
let missing_credential = || {
Error::credential_invalid(
"GCS V4 URL signing requires a local service-account key or an OAuth token with signer identity",
)
};
let token = credential.token().ok_or_else(missing_credential)?;
let signer_email = self
.signer_email
.as_deref()
.or_else(|| credential.signer_email());
let (signer_email, expires_seconds) = match (signer_email, credential.metadata_source())
{
(Some(email), _) => (Cow::Borrowed(email), query_expiration_seconds(expires)?),
(None, Some(source)) => {
let expires_seconds = query_expiration_seconds(expires)?;
(Cow::Owned(source.signer_email().await?), expires_seconds)
}
(None, None) => return Err(missing_credential()),
};
self.build_signed_query_via_iamcredentials(
ctx,
req,
)?,
GcsV4SigningKey::Remote {
token,
&signer_email,
expires_seconds,
)
.await?
signer_email,
} => {
let signer_email = signer_email.resolve().await?;
self.build_signed_query_via_iamcredentials(
ctx,
req,
token,
&signer_email,
expires_seconds,
)
.await?
}
};
signing_req.apply(req)?;
req.uri = uri;
Expand Down Expand Up @@ -790,20 +822,13 @@ fn authentication_query(
client_email: &str,
now: Timestamp,
expires_seconds: u64,
service: &str,
region: &str,
scope: &str,
) -> Vec<(String, String)> {
vec![
("X-Goog-Algorithm".into(), "GOOG4-RSA-SHA256".into()),
("X-Goog-Algorithm".into(), GCS_V4_ALGORITHM.into()),
(
"X-Goog-Credential".into(),
format!(
"{}/{}/{}/{}/goog4_request",
client_email,
now.format_date(),
region,
service
),
format!("{client_email}/{scope}"),
),
("X-Goog-Date".into(), now.format_iso8601()),
("X-Goog-Expires".into(), expires_seconds.to_string()),
Expand Down
Loading
Loading