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
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",

Copy link
Copy Markdown
Contributor

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:

  1. roles/spanner.fineGrainedAccessUser without a condition (to grant spanner.databases.useRoleBasedAccess on the database).
  2. roles/spanner.databaseRoleUser with the /databaseRoles/{database_role} IAM condition (to grant access to the specific database role).

Attaching the /databaseRoles/... condition directly to roles/spanner.fineGrainedAccessUser is accepted by set_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 test finally block)?

Suggested change
role="roles/spanner.fineGrainedAccessUser",
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

For more info, see the Spanner FGAC docs and IAM roles reference (as well as the Go/Java spanner_enable_fine_grained_access samples).

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.

You're right, and thank you for catching this — it's a real bug, not a nit. With the condition on roles/spanner.fineGrainedAccessUser and no roles/spanner.databaseRoleUser binding, 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 finally block (leaving any pre-existing unconditioned grant alone).

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,
)
206 changes: 206 additions & 0 deletions spanner/database_admin/tests/enable_fine_grained_access_test.py
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"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If SPANNER_FGAC_IAM_MEMBER is not set in the environment, accessing it via os.environ will raise a KeyError and crash the test suite. It is safer to use os.environ.get and skip the test gracefully if the variable is missing.

    iam_member = os.environ.get("SPANNER_FGAC_IAM_MEMBER")
    if not iam_member:
        pytest.skip("SPANNER_FGAC_IAM_MEMBER environment variable not set.")

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.

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 KeyError (3ea847b).

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})