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
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,114 @@ | ||
| # 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 conditional fineGrainedAccessUser IAM access for a database 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 | ||
| binding = policy.bindings.add( | ||
| role="roles/spanner.fineGrainedAccessUser", | ||
| members=[iam_member], | ||
| ) | ||
| binding.condition.title = f"fgac_{database_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,163 @@ | ||
| # 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 | ||
| 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) | ||
| 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.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() | ||
| 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) | ||
| 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) | ||
| 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 | ||
|
|
||
|
|
||
| @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, | ||
| ) | ||
| 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 | ||
| finally: | ||
| cur_policy = admin.get_iam_policy( | ||
| request={"resource": db_path, "options": {"requested_policy_version": 3}} | ||
| ) | ||
| cur_policy.version = 3 | ||
| kept = [ | ||
| b for b in cur_policy.bindings if b.condition.title != "fgac_new_parent" | ||
| ] | ||
| 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.
Directly appending a new binding to the policy can result in duplicate bindings or duplicate members if the function is called multiple times. It is more robust to check if a binding for the specified role and condition already exists, and if so, append the member to it only if they are not already present.
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.
Thanks! Keeping this as is: adding merge logic for existing bindings would distract from what the sample shows, which is adding a conditional binding for a database role.