Repository navigation
feat(spanner): Add conditional IAM fine-grained access binding sample #14960
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
base: feat/spanner-create-database
Are you sure you want to change the base?
Changes from all commits
381eede
3ea847b
1534a56
4bd34ce
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| # 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 | ||
| # | ||
| # 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. | ||
|
|
||
| # [START spanner_enable_fine_grained_access] | ||
| import sys | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 | ||
|
|
||
|
|
||
| def enable_fine_grained_access( | ||
| project_id: str, | ||
| instance_id: str, | ||
| database_id: str, | ||
| iam_member: str, | ||
| database_role: str, | ||
| ) -> None: | ||
| """Grants a principal fine-grained access to one Spanner database role. | ||
|
|
||
| Two IAM bindings are needed. `roles/spanner.fineGrainedAccessUser` makes the | ||
| principal a fine-grained access control user, and | ||
| `roles/spanner.databaseRoleUser`, with a condition naming the database role, | ||
| grants access to that role. | ||
|
|
||
| Args: | ||
| project_id: The Google Cloud project ID. | ||
| instance_id: The Spanner instance ID. | ||
| database_id: The Spanner database ID. | ||
| iam_member: The IAM principal (for example, 'user:alice@example.com'). | ||
| database_role: The target Spanner database role name. | ||
| """ | ||
| client = spanner_admin_database_v1.DatabaseAdminClient() | ||
| database_path = client.database_path(project_id, instance_id, database_id) | ||
| get_request = { | ||
| "resource": database_path, | ||
| "options": {"requested_policy_version": 3}, | ||
| } | ||
| condition_expr = f'resource.name.endsWith("/databaseRoles/{database_role}")' | ||
|
|
||
| try: | ||
| policy = client.get_iam_policy(request=get_request) | ||
| policy.version = 3 | ||
| policy.bindings.add( | ||
| role="roles/spanner.fineGrainedAccessUser", | ||
| members=[iam_member], | ||
| ) | ||
| role_binding = policy.bindings.add( | ||
| role="roles/spanner.databaseRoleUser", | ||
| members=[iam_member], | ||
| ) | ||
| role_binding.condition.title = f"fgac_{database_role}" | ||
| role_binding.condition.expression = condition_expr | ||
| updated_policy = client.set_iam_policy( | ||
| request={"resource": database_path, "policy": policy} | ||
| ) | ||
| except exceptions.InvalidArgument as err: | ||
| print( | ||
| f"error: invalid IAM principal or conditional binding for role " | ||
| f"'{database_role}' on database '{database_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: failed to enable fine-grained access on database " | ||
| f"'{database_id}' in instance '{instance_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| else: | ||
| print(f"Resource ID: {database_id}") | ||
| print(f"Database Role: {database_role}") | ||
| print(f"Policy Version: {updated_policy.version}") | ||
|
|
||
|
|
||
| # [END spanner_enable_fine_grained_access] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import argparse | ||
| import os | ||
|
|
||
| parser = argparse.ArgumentParser( | ||
| description="Grant conditional IAM access to a Spanner database role." | ||
| ) | ||
| parser.add_argument( | ||
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| ) | ||
| parser.add_argument( | ||
| "--instance-id", | ||
| default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), | ||
| ) | ||
| parser.add_argument( | ||
| "--database-id", | ||
| default=os.environ.get("SPANNER_DATABASE_ID", "example-db"), | ||
| ) | ||
| parser.add_argument( | ||
| "--iam-member", | ||
| default=os.environ.get("SPANNER_FGAC_IAM_MEMBER", "user:alice@example.com"), | ||
| ) | ||
| parser.add_argument( | ||
| "--database-role", | ||
| default="new_parent", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| enable_fine_grained_access( | ||
| project_id=args.project_id, | ||
| instance_id=args.instance_id, | ||
| database_id=args.database_id, | ||
| iam_member=args.iam_member, | ||
| database_role=args.database_role, | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| # 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 | ||
| # | ||
| # 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. | ||
|
|
||
| import os | ||
| import runpy | ||
| from unittest import mock | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 | ||
| from google.iam.v1 import policy_pb2 | ||
| import pytest | ||
| from spanner_database_admin import enable_fine_grained_access | ||
|
|
||
| from . import conftest | ||
|
|
||
| PROJECT_ID = "example-project-id" | ||
| INSTANCE_ID = "example-instance" | ||
| DATABASE_ID = "example-db" | ||
| IAM_MEMBER = "user:alice@example.com" | ||
| DB_ROLE = "new_parent" | ||
| ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" | ||
|
|
||
|
|
||
| @mock.patch(ADMIN_CLIENT, autospec=True) | ||
| def test_enable_fine_grained_access_success( | ||
| mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] | ||
| ) -> None: | ||
| client = mock_client_class.return_value | ||
| client.database_path.return_value = ( | ||
| f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}" | ||
| ) | ||
| client.get_iam_policy.return_value = policy_pb2.Policy() | ||
| client.set_iam_policy.return_value.version = 3 | ||
|
|
||
| enable_fine_grained_access.enable_fine_grained_access( | ||
| PROJECT_ID, INSTANCE_ID, DATABASE_ID, IAM_MEMBER, DB_ROLE | ||
| ) | ||
|
|
||
| client.set_iam_policy.assert_called_once() | ||
| policy = client.set_iam_policy.call_args.kwargs["request"]["policy"] | ||
| assert policy.version == 3 | ||
| user_binding, role_binding = policy.bindings | ||
| assert user_binding.role == "roles/spanner.fineGrainedAccessUser" | ||
| assert list(user_binding.members) == [IAM_MEMBER] | ||
| assert user_binding.condition.expression == "" | ||
| assert role_binding.role == "roles/spanner.databaseRoleUser" | ||
| assert list(role_binding.members) == [IAM_MEMBER] | ||
| assert role_binding.condition.title == "fgac_new_parent" | ||
| assert role_binding.condition.expression == ( | ||
| 'resource.name.endsWith("/databaseRoles/new_parent")' | ||
| ) | ||
| out, err = capsys.readouterr() | ||
| assert f"Resource ID: {DATABASE_ID}" in out | ||
| assert "Database Role: new_parent" in out | ||
| assert "Policy Version: 3" in out | ||
| assert PROJECT_ID not in out | ||
| assert err == "" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "error, expected_prefix", | ||
| [ | ||
| ( | ||
| exceptions.InvalidArgument("bad member"), | ||
| "error: invalid IAM principal or conditional binding", | ||
| ), | ||
| ( | ||
| exceptions.PermissionDenied("denied"), | ||
| "error: failed to enable fine-grained access", | ||
| ), | ||
| ], | ||
| ) | ||
| @mock.patch(ADMIN_CLIENT, autospec=True) | ||
| def test_enable_fine_grained_access_errors( | ||
| mock_client_class: mock.MagicMock, | ||
| capsys: pytest.CaptureFixture[str], | ||
| error: Exception, | ||
| expected_prefix: str, | ||
| ) -> None: | ||
| client = mock_client_class.return_value | ||
| client.database_path.return_value = ( | ||
| f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}" | ||
| ) | ||
| client.get_iam_policy.side_effect = error | ||
|
|
||
| enable_fine_grained_access.enable_fine_grained_access( | ||
| PROJECT_ID, INSTANCE_ID, DATABASE_ID, IAM_MEMBER, DB_ROLE | ||
| ) | ||
|
|
||
| _out, err = capsys.readouterr() | ||
| assert err.startswith(expected_prefix) | ||
| assert PROJECT_ID not in err | ||
|
|
||
|
|
||
| @mock.patch(ADMIN_CLIENT, autospec=True) | ||
| def test_enable_fine_grained_access_cli_entrypoint( | ||
| mock_client_class: mock.MagicMock, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| capsys: pytest.CaptureFixture[str], | ||
| ) -> None: | ||
| client = mock_client_class.return_value | ||
| client.database_path.return_value = ( | ||
| f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}" | ||
| ) | ||
| client.set_iam_policy.return_value.version = 3 | ||
| monkeypatch.setattr( | ||
| "sys.argv", | ||
| [ | ||
| "enable_fine_grained_access.py", | ||
| "--project-id", | ||
| PROJECT_ID, | ||
| "--instance-id", | ||
| INSTANCE_ID, | ||
| "--database-id", | ||
| DATABASE_ID, | ||
| "--iam-member", | ||
| IAM_MEMBER, | ||
| "--database-role", | ||
| DB_ROLE, | ||
| ], | ||
| ) | ||
|
|
||
| runpy.run_module( | ||
| "spanner_database_admin.enable_fine_grained_access", run_name="__main__" | ||
| ) | ||
|
|
||
| assert "Policy Version: 3" in capsys.readouterr().out | ||
|
|
||
|
|
||
| # Live integration test: skipped unless RUN_INTEGRATION_TESTS=true is set along with | ||
| # GOOGLE_CLOUD_PROJECT, SPANNER_INSTANCE_ID, SPANNER_DATABASE_ID, and | ||
| # SPANNER_FGAC_IAM_MEMBER. | ||
| @conftest.live_only | ||
| def test_enable_fine_grained_access_live(capsys: pytest.CaptureFixture[str]) -> None: | ||
| required = ("SPANNER_FGAC_IAM_MEMBER",) | ||
| missing = [name for name in required if not os.environ.get(name)] | ||
| if missing: | ||
| pytest.skip(f"Set {', '.join(missing)} to run this live test.") | ||
| iam_member = os.environ["SPANNER_FGAC_IAM_MEMBER"] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If iam_member = os.environ.get("SPANNER_FGAC_IAM_MEMBER")
if not iam_member:
pytest.skip("SPANNER_FGAC_IAM_MEMBER environment variable not set.")
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch, done: the live test now checks for its required environment variables up front and skips with a clear message when one is missing, instead of failing with a |
||
| admin = spanner_admin_database_v1.DatabaseAdminClient() | ||
| db_path = admin.database_path( | ||
| conftest.LIVE_PROJECT_ID, | ||
| conftest.LIVE_INSTANCE_ID, | ||
| conftest.LIVE_DATABASE_ID, | ||
| ) | ||
| policy_request = {"resource": db_path, "options": {"requested_policy_version": 3}} | ||
| fgac_role = "roles/spanner.fineGrainedAccessUser" | ||
| # Remember whether the principal already had the unconditioned grant, so the | ||
| # cleanup only removes what this test added. | ||
| had_fgac_user = any( | ||
| b.role == fgac_role and not b.condition.expression and iam_member in b.members | ||
| for b in admin.get_iam_policy(request=policy_request).bindings | ||
| ) | ||
| try: | ||
| enable_fine_grained_access.enable_fine_grained_access( | ||
| conftest.LIVE_PROJECT_ID, | ||
| conftest.LIVE_INSTANCE_ID, | ||
| conftest.LIVE_DATABASE_ID, | ||
| iam_member, | ||
| "new_parent", | ||
| ) | ||
| out, err = capsys.readouterr() | ||
| assert err == "" | ||
| assert conftest.LIVE_PROJECT_ID not in out | ||
| assert "Database Role: new_parent" in out | ||
| assert "Policy Version: 3" in out | ||
| granted = admin.get_iam_policy(request=policy_request) | ||
| assert any( | ||
| b.role == "roles/spanner.databaseRoleUser" | ||
| and iam_member in b.members | ||
| and b.condition.title == "fgac_new_parent" | ||
| for b in granted.bindings | ||
| ) | ||
| assert any( | ||
| b.role == fgac_role | ||
| and iam_member in b.members | ||
| and not b.condition.expression | ||
| for b in granted.bindings | ||
| ) | ||
| finally: | ||
| cur_policy = admin.get_iam_policy(request=policy_request) | ||
| cur_policy.version = 3 | ||
| kept = [] | ||
| for b in cur_policy.bindings: | ||
| if b.condition.title == "fgac_new_parent": | ||
| continue | ||
| if b.role == fgac_role and not b.condition.expression and not had_fgac_user: | ||
| while iam_member in b.members: | ||
| b.members.remove(iam_member) | ||
| if not b.members: | ||
| continue | ||
| kept.append(b) | ||
| del cur_policy.bindings[:] | ||
| cur_policy.bindings.extend(kept) | ||
| admin.set_iam_policy(request={"resource": db_path, "policy": cur_policy}) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like we need both roles here:
roles/spanner.fineGrainedAccessUserwithout a condition (to grantspanner.databases.useRoleBasedAccesson the database).roles/spanner.databaseRoleUserwith the/databaseRoles/{database_role}IAM condition (to grant access to the specific database role).Attaching the
/databaseRoles/...condition directly toroles/spanner.fineGrainedAccessUseris accepted byset_iam_policy, so the call succeeds, but it won't actually grant FGAC access to the database role. Could we update this to add both bindings (and clean up both in the live testfinallyblock)?For more info, see the Spanner FGAC docs and IAM roles reference (as well as the Go/Java
spanner_enable_fine_grained_accesssamples).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right, and thank you for catching this — it's a real bug, not a nit. With the condition on
roles/spanner.fineGrainedAccessUserand noroles/spanner.databaseRoleUserbinding, the call succeeded but never granted access to the database role. The earlier Python sample this one replaces has the same single-binding pattern, so your review fixed a long-standing problem.Fixed in 4bd34ce: the sample now adds both bindings as you suggested, the unit test asserts both on the policy that is sent, and the live test checks both are present and removes both in its
finallyblock (leaving any pre-existing unconditioned grant alone).