You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@reqsign.apache.org by xu...@apache.org on 2026/10/05 07:26:51 UTC
(reqsign) branch main updated: feat(google): support caller-defined CAB rules (#901)
This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/reqsign.git
The following commit(s) were added to refs/heads/main by this push:
new 615d858 feat(google): support caller-defined CAB rules (#901)
615d858 is described below
commit 615d858a03dd54d1ccb89c3f1e32f915bc5ed90d
Author: Xuanwo <gi...@xuanwo.io>
AuthorDate: Mon Oct 5 15:26:47 2026 +0800
feat(google): support caller-defined CAB rules (#901)
Callers can now supply explicit CAB rules with IAM role identifiers and
CEL availability conditions to the existing server-side token exchange.
This preserves policies that combine
`legacyObjectReader`/`objectViewer`,
`legacyBucketWriter`/`objectCreator` (including overwrite and delete),
and an additional `objectAdmin` rule. It also preserves the exact
`table` list-prefix case while keeping object access restricted to
`table/`.
The typed convenience constructors retain their existing behavior.
Explicit rules share bucket, rule-count, and size validation; reqsign
validates role structure and preserves expressions verbatim, leaving
role existence and CEL semantics to Google. Arbitrary CEL expressions
require server-side exchange: the client-side granter rejects them
before I/O because its existing compiler only supports generated prefix
conditions.
Public-API tests capture the outgoing STS request for each caller policy
and check exact role sets, conditions, form encoding, expiration bounds,
and rejection before I/O. These tests use mock STS and do not establish
live Google authorization for the new policies.
Fixes #896.
---
services/google/src/credential_access_boundary.rs | 265 +++++++++++++++++++--
.../src/credential_access_boundary/client_side.rs | 24 +-
services/google/src/lib.rs | 2 +-
.../tests/explicit_credential_access_boundary.rs | 265 +++++++++++++++++++++
4 files changed, 517 insertions(+), 39 deletions(-)
diff --git a/services/google/src/credential_access_boundary.rs b/services/google/src/credential_access_boundary.rs
index 244798b..7424086 100644
--- a/services/google/src/credential_access_boundary.rs
+++ b/services/google/src/credential_access_boundary.rs
@@ -50,7 +50,8 @@ const ALL_ROLES: u8 =
/// individual `storage.objects.*` permission names. It accepts IAM role
/// identifiers prefixed with `inRole:`. These constants deliberately expose only
/// the well-known predefined Cloud Storage object roles, preventing callers from
-/// injecting raw role identifiers or binding a grant to a mutable custom role.
+/// supplying arbitrary roles through this convenience API. Use
+/// [`CredentialAccessBoundaryRule::new`] for caller-selected IAM roles.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct CredentialAccessBoundaryPermissions(u8);
@@ -118,21 +119,105 @@ impl BitOrAssign for CredentialAccessBoundaryPermissions {
}
}
+/// A caller-defined Cloud Storage Credential Access Boundary rule.
+///
+/// The caller owns the authorization policy, including any changes to custom
+/// roles. Reqsign checks bucket names, role identifier structure, non-empty
+/// conditions, and size/rule limits before granting. Google validates role
+/// existence, permissions, and CEL syntax and semantics.
+///
+/// Use [`CredentialAccessBoundaryGrant::new`] and
+/// [`CredentialAccessBoundaryGrant::with_rule`] to combine explicit rules with
+/// the existing typed convenience constructors. Rules are evaluated as a union.
#[derive(Clone)]
-struct CredentialAccessBoundaryRule {
+pub struct CredentialAccessBoundaryRule {
bucket: String,
- object_prefix: Option<String>,
- permissions: CredentialAccessBoundaryPermissions,
+ permissions: RulePermissions,
+ condition: Option<RuleCondition>,
+}
+
+#[derive(Clone)]
+enum RulePermissions {
+ Typed(CredentialAccessBoundaryPermissions),
+ Explicit(Vec<String>),
+}
+
+#[derive(Clone)]
+enum RuleCondition {
+ ObjectPrefix(String),
+ Expression(String),
+}
+
+impl Debug for CredentialAccessBoundaryRule {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("CredentialAccessBoundaryRule")
+ .finish_non_exhaustive()
+ }
}
-/// A typed, bound Google Cloud Storage Credential Access Boundary.
+impl CredentialAccessBoundaryRule {
+ /// Create a bucket-wide rule with caller-selected IAM role identifiers.
+ ///
+ /// Each role must include `inRole:` followed by `roles/ROLE`,
+ /// `projects/PROJECT/roles/ROLE`, or `organizations/ORGANIZATION/roles/ROLE`.
+ /// Individual permission names are not accepted. Role order and spelling
+ /// are preserved; no roles are added or substituted.
+ /// Validation is deferred until the grant is used, as with typed grants.
+ pub fn new(
+ bucket: impl Into<String>,
+ roles: impl IntoIterator<Item = impl Into<String>>,
+ ) -> Self {
+ Self {
+ bucket: bucket.into(),
+ permissions: RulePermissions::Explicit(roles.into_iter().map(Into::into).collect()),
+ condition: None,
+ }
+ }
+
+ /// Set a caller-authored CEL availability condition, preserved verbatim.
+ ///
+ /// The caller must escape literals and choose the intended authorization
+ /// semantics. Reqsign checks only that the expression is non-empty and
+ /// within the size limit; it does not parse or evaluate arbitrary CEL.
+ /// `objectListPrefix` conditions authorize list requests, not individual
+ /// results within a listing.
+ ///
+ /// Explicit expressions require [`ServerSideCredentialAccessBoundaryGranter`].
+ /// The client-side granter cannot compile arbitrary CEL and rejects these
+ /// rules before I/O rather than omitting their conditions.
+ pub fn with_condition(mut self, expression: impl Into<String>) -> Self {
+ self.condition = Some(RuleCondition::Expression(expression.into()));
+ self
+ }
+}
+
+/// A bound Google Cloud Storage Credential Access Boundary.
///
/// Use [`CredentialAccessBoundaryGrant::for_bucket`] for bucket-wide access or
/// [`CredentialAccessBoundaryGrant::for_object_prefix`] for a non-empty object
/// prefix. Prefix grants generate the CEL expression internally, including the
-/// `objectListPrefix` check required for safely listing objects. Bucket and
+/// `objectListPrefix` check that authorizes list requests. Bucket and
/// prefix values are never normalized.
///
+/// Use [`CredentialAccessBoundaryGrant::new`] with an explicit
+/// [`CredentialAccessBoundaryRule`] for other roles or conditions. For example,
+/// this policy accepts the exact list prefix `table` while restricting object
+/// access to `table/` (excluding sibling object prefixes such as `table-other/`):
+///
+/// ```
+/// use reqsign_google::{CredentialAccessBoundaryGrant, CredentialAccessBoundaryRule};
+///
+/// let condition = "resource.name.startsWith('projects/_/buckets/example-bucket/objects/table/') || \
+/// api.getAttribute('storage.googleapis.com/objectListPrefix', '') == 'table' || \
+/// api.getAttribute('storage.googleapis.com/objectListPrefix', '').startsWith('table/')";
+/// let grant = CredentialAccessBoundaryGrant::new(
+/// CredentialAccessBoundaryRule::new("example-bucket", [
+/// "inRole:roles/storage.legacyObjectReader",
+/// "inRole:roles/storage.objectViewer",
+/// ]).with_condition(condition),
+/// );
+/// ```
+///
/// Additional rules can be added explicitly. Google evaluates CAB rules as a
/// union and allows at most ten rules.
#[derive(Clone)]
@@ -149,6 +234,17 @@ impl Debug for CredentialAccessBoundaryGrant {
}
impl CredentialAccessBoundaryGrant {
+ /// Create a Credential Access Boundary from a caller-defined rule.
+ pub fn new(rule: CredentialAccessBoundaryRule) -> Self {
+ Self { rules: vec![rule] }
+ }
+
+ /// Add a caller-defined rule. All rules are evaluated as a union.
+ pub fn with_rule(mut self, rule: CredentialAccessBoundaryRule) -> Self {
+ self.rules.push(rule);
+ self
+ }
+
/// Create a bucket-wide Credential Access Boundary.
pub fn for_bucket(
bucket: impl Into<String>,
@@ -157,8 +253,8 @@ impl CredentialAccessBoundaryGrant {
Self {
rules: vec![CredentialAccessBoundaryRule {
bucket: bucket.into(),
- object_prefix: None,
- permissions,
+ condition: None,
+ permissions: RulePermissions::Typed(permissions),
}],
}
}
@@ -175,8 +271,8 @@ impl CredentialAccessBoundaryGrant {
Self {
rules: vec![CredentialAccessBoundaryRule {
bucket: bucket.into(),
- object_prefix: Some(object_prefix.into()),
- permissions,
+ condition: Some(RuleCondition::ObjectPrefix(object_prefix.into())),
+ permissions: RulePermissions::Typed(permissions),
}],
}
}
@@ -191,8 +287,8 @@ impl CredentialAccessBoundaryGrant {
) -> Self {
self.rules.push(CredentialAccessBoundaryRule {
bucket: bucket.into(),
- object_prefix: None,
- permissions,
+ condition: None,
+ permissions: RulePermissions::Typed(permissions),
});
self
}
@@ -208,8 +304,8 @@ impl CredentialAccessBoundaryGrant {
) -> Self {
self.rules.push(CredentialAccessBoundaryRule {
bucket: bucket.into(),
- object_prefix: Some(object_prefix.into()),
- permissions,
+ condition: Some(RuleCondition::ObjectPrefix(object_prefix.into())),
+ permissions: RulePermissions::Typed(permissions),
});
self
}
@@ -267,16 +363,46 @@ impl CredentialAccessBoundaryGrant {
impl CredentialAccessBoundaryRule {
fn to_wire(&self) -> Result<AccessBoundaryRule> {
validate_bucket_name(&self.bucket)?;
- let available_permissions = self.permissions.roles()?;
+ let available_permissions = match &self.permissions {
+ RulePermissions::Typed(permissions) => permissions
+ .roles()?
+ .into_iter()
+ .map(str::to_owned)
+ .collect(),
+ RulePermissions::Explicit(roles) => {
+ if roles.is_empty() {
+ return Err(Error::request_invalid(
+ "credential access boundary roles must not be empty",
+ ));
+ }
+ for role in roles {
+ validate_role(role)?;
+ }
+ roles.clone()
+ }
+ };
let available_resource = format!(
"//storage.googleapis.com/projects/_/buckets/{}",
self.bucket
);
let availability_condition = self
- .object_prefix
- .as_deref()
- .map(|prefix| build_prefix_condition(&self.bucket, prefix))
+ .condition
+ .as_ref()
+ .map(|condition| match condition {
+ RuleCondition::ObjectPrefix(prefix) => build_prefix_condition(&self.bucket, prefix),
+ RuleCondition::Expression(expression) => {
+ if expression.trim().is_empty() {
+ return Err(Error::request_invalid(
+ "credential access boundary condition must not be empty",
+ ));
+ }
+ validate_condition_size(expression)?;
+ Ok(AvailabilityCondition {
+ expression: expression.clone(),
+ })
+ }
+ })
.transpose()?;
Ok(AccessBoundaryRule {
@@ -303,7 +429,7 @@ struct AccessBoundary {
#[serde(rename_all = "camelCase")]
struct AccessBoundaryRule {
available_resource: String,
- available_permissions: Vec<&'static str>,
+ available_permissions: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
availability_condition: Option<AvailabilityCondition>,
}
@@ -313,6 +439,38 @@ struct AvailabilityCondition {
expression: String,
}
+fn validate_role(role: &str) -> Result<()> {
+ let valid = role.strip_prefix("inRole:").is_some_and(|identifier| {
+ let parts: Vec<_> = identifier.split('/').collect();
+ let valid_shape = matches!(
+ parts.as_slice(),
+ ["roles", _] | ["projects" | "organizations", _, "roles", _]
+ );
+ valid_shape
+ && parts.iter().all(|part| {
+ !part.is_empty()
+ && part
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
+ })
+ });
+ if !valid {
+ return Err(Error::request_invalid(
+ "credential access boundary role identifier is invalid",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_condition_size(expression: &str) -> Result<()> {
+ if expression.chars().count() > MAX_CONDITION_CHARACTERS {
+ return Err(Error::request_invalid(
+ "credential access boundary condition exceeds the size limit",
+ ));
+ }
+ Ok(())
+}
+
fn validate_bucket_name(bucket: &str) -> Result<()> {
let length = bucket.len();
let valid_length = if bucket.contains('.') {
@@ -383,11 +541,7 @@ fn build_prefix_condition(bucket: &str, prefix: &str) -> Result<AvailabilityCond
api.getAttribute(\"storage.googleapis.com/objectListPrefix\", \"\")\
.startsWith({list_prefix_literal})"
);
- if expression.chars().count() > MAX_CONDITION_CHARACTERS {
- return Err(Error::request_invalid(
- "credential access boundary condition exceeds the size limit",
- ));
- }
+ validate_condition_size(&expression)?;
Ok(AvailabilityCondition { expression })
}
@@ -506,6 +660,69 @@ mod tests {
assert!(expression.ends_with(r#".startsWith("/leading//nested/")"#));
}
+ #[test]
+ fn explicit_rules_preserve_expressions_and_redact_debug() {
+ let expression = r#"resource.name.endsWith("quote\\\"/雪&suffix")"#;
+ let rule = CredentialAccessBoundaryRule::new(
+ "sensitive-bucket",
+ ["inRole:projects/sensitive-project/roles/custom_role"],
+ )
+ .with_condition(expression);
+ let grant = CredentialAccessBoundaryGrant::new(rule.clone());
+ let options: serde_json::Value =
+ serde_json::from_str(&grant.options_json().unwrap()).unwrap();
+ assert_eq!(
+ options["accessBoundary"]["accessBoundaryRules"][0]["availabilityCondition"]["expression"],
+ expression
+ );
+ for debug in [format!("{rule:?}"), format!("{grant:?}")] {
+ assert!(!debug.contains("sensitive"));
+ assert!(!debug.contains(expression));
+ }
+ }
+
+ #[test]
+ fn explicit_rules_retain_rule_and_size_limits() {
+ let rule = CredentialAccessBoundaryRule::new(
+ "example-bucket",
+ ["inRole:roles/storage.objectViewer"],
+ );
+ let mut grant = CredentialAccessBoundaryGrant::new(rule.clone());
+ for _ in 1..MAX_ACCESS_BOUNDARY_RULES {
+ grant = grant.with_rule(rule.clone());
+ }
+ grant
+ .validate()
+ .expect("ten explicit rules must be accepted");
+ assert_eq!(
+ grant.with_rule(rule.clone()).validate().unwrap_err().kind(),
+ ErrorKind::RequestInvalid
+ );
+
+ let empty_expression_size = serde_json::to_string(&AccessBoundary {
+ access_boundary_rules: vec![AccessBoundaryRule {
+ availability_condition: Some(AvailabilityCondition {
+ expression: String::new(),
+ }),
+ ..rule.to_wire().unwrap()
+ }],
+ })
+ .unwrap()
+ .chars()
+ .count();
+ let remaining = MAX_ACCESS_BOUNDARY_CHARACTERS - empty_expression_size;
+ CredentialAccessBoundaryGrant::new(rule.clone().with_condition("x".repeat(remaining)))
+ .validate()
+ .expect("explicit boundary at the size limit must be accepted");
+ assert_eq!(
+ CredentialAccessBoundaryGrant::new(rule.with_condition("x".repeat(remaining + 1)))
+ .validate()
+ .unwrap_err()
+ .kind(),
+ ErrorKind::RequestInvalid
+ );
+ }
+
#[test]
fn enforces_access_boundary_size_limit() {
let permissions = CredentialAccessBoundaryPermissions::OBJECT_VIEWER;
diff --git a/services/google/src/credential_access_boundary/client_side.rs b/services/google/src/credential_access_boundary/client_side.rs
index 0e00896..55225a9 100644
--- a/services/google/src/credential_access_boundary/client_side.rs
+++ b/services/google/src/credential_access_boundary/client_side.rs
@@ -871,20 +871,16 @@ fn serialize_restrictions(grant: &CredentialAccessBoundaryGrant) -> Result<Vec<u
.rules
.iter()
.map(|rule| {
- let available_resource = format!(
- "//storage.googleapis.com/projects/_/buckets/{}",
- rule.bucket
- );
- let available_permissions = rule
- .permissions
- .roles()?
- .into_iter()
- .map(str::to_owned)
- .collect();
- let compiled_availability_condition = rule
- .object_prefix
- .as_deref()
- .map(|prefix| prefix_condition_expr(&rule.bucket, prefix));
+ let wire = rule.to_wire()?;
+ let available_resource = wire.available_resource;
+ let available_permissions = wire.available_permissions;
+ let compiled_availability_condition = match &rule.condition {
+ None => None,
+ Some(super::RuleCondition::ObjectPrefix(prefix)) => Some(prefix_condition_expr(&rule.bucket, prefix)),
+ Some(super::RuleCondition::Expression(_)) => return Err(Error::request_invalid(
+ "explicit CEL conditions require server-side credential access boundary exchange",
+ )),
+ };
Ok(ClientSideAccessBoundaryRule {
available_resource,
available_permissions,
diff --git a/services/google/src/lib.rs b/services/google/src/lib.rs
index 6ec36ce..9231bb9 100644
--- a/services/google/src/lib.rs
+++ b/services/google/src/lib.rs
@@ -35,7 +35,7 @@ mod credential_access_boundary;
pub use credential_access_boundary::ClientSideCredentialAccessBoundaryGranter;
pub use credential_access_boundary::{
CredentialAccessBoundaryGrant, CredentialAccessBoundaryPermissions,
- ServerSideCredentialAccessBoundaryGranter,
+ CredentialAccessBoundaryRule, ServerSideCredentialAccessBoundaryGranter,
};
mod service_account_impersonation;
diff --git a/services/google/tests/explicit_credential_access_boundary.rs b/services/google/tests/explicit_credential_access_boundary.rs
new file mode 100644
index 0000000..122217c
--- /dev/null
+++ b/services/google/tests/explicit_credential_access_boundary.rs
@@ -0,0 +1,265 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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
+//
+// http://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.
+
+use std::collections::BTreeMap;
+use std::fmt::{self, Debug};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use bytes::Bytes;
+use reqsign_core::{Context, ErrorKind, Granter, HttpSend, Result, time::Timestamp};
+use reqsign_google::{
+ CredentialAccessBoundaryGrant, CredentialAccessBoundaryPermissions,
+ CredentialAccessBoundaryRule, ServerSideCredentialAccessBoundaryGranter,
+ TokenCredentialProvider,
+};
+use serde_json::{Value, json};
+
+#[derive(Clone, Default)]
+struct MockSts(Arc<Mutex<Vec<http::Request<Bytes>>>>);
+
+impl Debug for MockSts {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("MockSts").finish_non_exhaustive()
+ }
+}
+
+impl HttpSend for MockSts {
+ async fn http_send(&self, request: http::Request<Bytes>) -> Result<http::Response<Bytes>> {
+ self.0.lock().unwrap().push(request);
+ Ok(http::Response::new(Bytes::from_static(
+ br#"{
+ "access_token": "downscoped-token",
+ "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
+ "token_type": "Bearer",
+ "expires_in": 3600
+ }"#,
+ )))
+ }
+}
+
+fn source(expires_at: Timestamp) -> TokenCredentialProvider {
+ TokenCredentialProvider::new("source+token&options=other").with_expires_at(expires_at)
+}
+
+const CONDITION: &str = "resource.name.startsWith('projects/_/buckets/example-bucket/objects/table/') ||\n\
+api.getAttribute('storage.googleapis.com/objectListPrefix', '') == 'table' ||\n\
+api.getAttribute('storage.googleapis.com/objectListPrefix', '').startsWith('table/')";
+
+#[tokio::test]
+async fn exchanges_caller_policy_without_changing_roles_or_prefixes() -> Result<()> {
+ let http = MockSts::default();
+ let expires_at = Timestamp::now() + Duration::from_secs(600);
+ // These mappings belong to the caller, including overwrite and delete via
+ // legacyBucketWriter. The library must not substitute objectCreator alone
+ // or broaden the write policy to objectAdmin.
+ let roles = [
+ vec![
+ "inRole:roles/storage.legacyObjectReader",
+ "inRole:roles/storage.objectViewer",
+ ],
+ vec![
+ "inRole:roles/storage.legacyBucketWriter",
+ "inRole:roles/storage.objectCreator",
+ ],
+ vec!["inRole:roles/storage.objectAdmin"],
+ ];
+ let mut grant = CredentialAccessBoundaryGrant::new(
+ CredentialAccessBoundaryRule::new("example-bucket", roles[0].clone())
+ .with_condition(CONDITION),
+ );
+ for count in 1..=roles.len() {
+ if count > 1 {
+ grant = grant.with_rule(
+ CredentialAccessBoundaryRule::new("example-bucket", roles[count - 1].clone())
+ .with_condition(CONDITION),
+ );
+ }
+ let output = Granter::new(
+ Context::new().with_http_send(http.clone()),
+ source(expires_at),
+ ServerSideCredentialAccessBoundaryGranter::new(grant.clone()),
+ )
+ .grant(None)
+ .await?;
+ let token = output.token.unwrap();
+ assert_eq!(token.access_token, "downscoped-token");
+ // The returned token may never outlive its source.
+ assert_eq!(token.expires_at, Some(expires_at));
+
+ let requests = http.0.lock().unwrap();
+ assert_eq!(requests.len(), count);
+ let request = &requests[count - 1];
+ assert_eq!(request.method(), http::Method::POST);
+ assert_eq!(request.uri(), "https://sts.googleapis.com/v1/token");
+ assert_eq!(
+ request.headers()[http::header::CONTENT_TYPE],
+ "application/x-www-form-urlencoded"
+ );
+ let fields: BTreeMap<_, _> = form_urlencoded::parse(request.body())
+ .into_owned()
+ .collect();
+ assert_eq!(fields.len(), 5);
+ assert_eq!(
+ fields["grant_type"],
+ "urn:ietf:params:oauth:grant-type:token-exchange"
+ );
+ assert_eq!(
+ fields["requested_token_type"],
+ "urn:ietf:params:oauth:token-type:access_token"
+ );
+ assert_eq!(
+ fields["subject_token_type"],
+ "urn:ietf:params:oauth:token-type:access_token"
+ );
+ assert_eq!(fields["subject_token"], "source+token&options=other");
+ let options: Value = serde_json::from_str(&fields["options"]).unwrap();
+ let expected: Vec<_> = roles[..count].iter().map(|roles| json!({
+ "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket",
+ "availablePermissions": roles,
+ "availabilityCondition": {"expression": CONDITION},
+ })).collect();
+ assert_eq!(
+ options,
+ json!({"accessBoundary": {"accessBoundaryRules": expected}})
+ );
+ // The exact list prefix must survive alongside a distinct object prefix.
+ let expression = options["accessBoundary"]["accessBoundaryRules"][0]
+ ["availabilityCondition"]["expression"].as_str().unwrap();
+ assert!(expression.contains("objects/table/')"));
+ assert!(expression.contains("== 'table'"));
+ assert!(expression.contains(".startsWith('table/')"));
+ assert!(!expression.contains("objects/table')"));
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn rejects_invalid_explicit_rules_before_sts_io() {
+ let valid = || {
+ CredentialAccessBoundaryRule::new("example-bucket", ["inRole:roles/storage.objectViewer"])
+ };
+ let mut invalid = vec![
+ CredentialAccessBoundaryGrant::new(CredentialAccessBoundaryRule::new(
+ "bad/bucket",
+ ["inRole:roles/storage.objectViewer"],
+ )),
+ CredentialAccessBoundaryGrant::new(CredentialAccessBoundaryRule::new(
+ "example-bucket",
+ Vec::<String>::new(),
+ )),
+ CredentialAccessBoundaryGrant::new(valid().with_condition(" \n\t")),
+ CredentialAccessBoundaryGrant::new(valid().with_condition("x".repeat(2049))),
+ // The expression itself fits, but the complete boundary exceeds 2048 characters.
+ CredentialAccessBoundaryGrant::new(valid().with_condition("x".repeat(2000))),
+ ];
+ for role in [
+ "",
+ "roles/storage.objectViewer",
+ "storage.objects.get",
+ "inRole:storage.objects.get",
+ "inRole:roles/",
+ "inRole:roles/a/b",
+ "inRole:projects//roles/a",
+ "inRole:organizations/123/roles/",
+ "inRole:roles/storage.objectViewer\n",
+ "inRole:roles/a b",
+ ] {
+ invalid.push(CredentialAccessBoundaryGrant::new(
+ CredentialAccessBoundaryRule::new("example-bucket", [role]),
+ ));
+ }
+ let mut too_many = CredentialAccessBoundaryGrant::new(valid());
+ for _ in 0..10 {
+ too_many = too_many.with_rule(valid());
+ }
+ invalid.push(too_many);
+ let http = MockSts::default();
+ for grant in invalid {
+ let err = Granter::new(
+ Context::new().with_http_send(http.clone()),
+ source(Timestamp::now() + Duration::from_secs(600)),
+ ServerSideCredentialAccessBoundaryGranter::new(grant),
+ )
+ .grant(None)
+ .await
+ .expect_err("invalid explicit policy must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ }
+ assert!(http.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn combines_custom_roles_and_typed_rules_without_normalization() -> Result<()> {
+ let http = MockSts::default();
+ let roles = [
+ "inRole:projects/example-project/roles/custom_role",
+ "inRole:organizations/123/roles/customRole",
+ ];
+ let grant = CredentialAccessBoundaryGrant::for_object_prefix(
+ "example-bucket",
+ "table/",
+ CredentialAccessBoundaryPermissions::OBJECT_VIEWER,
+ )
+ .with_rule(CredentialAccessBoundaryRule::new("example-bucket", roles));
+ Granter::new(
+ Context::new().with_http_send(http.clone()),
+ source(Timestamp::now() + Duration::from_secs(600)),
+ ServerSideCredentialAccessBoundaryGranter::new(grant),
+ )
+ .grant(None)
+ .await?;
+ let requests = http.0.lock().unwrap();
+ let fields: BTreeMap<_, _> = form_urlencoded::parse(requests[0].body())
+ .into_owned()
+ .collect();
+ let options: Value = serde_json::from_str(&fields["options"]).unwrap();
+ let rules = &options["accessBoundary"]["accessBoundaryRules"];
+ assert_eq!(rules[1]["availablePermissions"], json!(roles));
+ assert!(rules[1].get("availabilityCondition").is_none());
+ assert_eq!(
+ rules[0]["availabilityCondition"]["expression"],
+ r#"resource.name.startsWith("projects/_/buckets/example-bucket/objects/table/") || api.getAttribute("storage.googleapis.com/objectListPrefix", "").startsWith("table/")"#
+ );
+ Ok(())
+}
+
+#[cfg(feature = "credential-access-boundary-client-side")]
+#[tokio::test]
+async fn client_side_rejects_explicit_conditions_before_io() {
+ use reqsign_google::ClientSideCredentialAccessBoundaryGranter;
+
+ let http = MockSts::default();
+ let grant = CredentialAccessBoundaryGrant::new(
+ CredentialAccessBoundaryRule::new("example-bucket", ["inRole:roles/storage.objectViewer"])
+ .with_condition(CONDITION),
+ );
+ let err = Granter::new(
+ Context::new().with_http_send(http.clone()),
+ source(Timestamp::now() + Duration::from_secs(3600)),
+ ClientSideCredentialAccessBoundaryGranter::new(grant),
+ )
+ .grant(None)
+ .await
+ .expect_err("client-side must not drop explicit conditions");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ assert!(
+ err.to_string()
+ .contains("explicit CEL conditions require server-side")
+ );
+ assert!(http.0.lock().unwrap().is_empty());
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@reqsign.apache.org
For additional commands, e-mail: commits-help@reqsign.apache.org