Skip to content

feat(spanner): Add conditional IAM fine-grained access binding sample - #14960

Open
iennae wants to merge 4 commits into
feat/spanner-create-databasefrom
feat/spanner-enable-fine-grained-access
Open

iennae wants to merge 4 commits into
feat/spanner-create-databasefrom
feat/spanner-enable-fine-grained-access

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_enable_fine_grained_access binding roles/spanner.fineGrainedAccessUser with a databaseRoles IAM condition.

Note: Stacked on #14943 (feat/spanner-create-database) so this PR shows only this sample's diff. It will merge into main after #14943.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Granting an IAM principal access to a specific Spanner database role attaches a version-3 IAM condition on roles/spanner.fineGrainedAccessUser. Add spanner_enable_fine_grained_access.
@iennae
iennae requested review from a team as code owners November 18, 2026 22:18
@snippet-bot

snippet-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label Bot added api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples. labels Nov 18, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces a new utility script and module, enable_fine_grained_access.py, to grant conditional IAM fine-grained access to a Google Cloud Spanner database role, along with corresponding unit and live tests. The feedback recommends improving the robustness of the IAM policy update by checking for existing bindings to prevent duplicates, and safely handling the SPANNER_FGAC_IAM_MEMBER environment variable in tests to avoid potential KeyError crashes.

Comment on lines +49 to +54
binding = policy.bindings.add(
role="roles/spanner.fineGrainedAccessUser",
members=[iam_member],
)
binding.condition.title = f"fgac_{database_role}"
binding.condition.expression = condition_expr

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

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.

        binding = None
        for b in policy.bindings:
            if (
                b.role == "roles/spanner.fineGrainedAccessUser"
                and b.condition.expression == condition_expr
            ):
                binding = b
                break

        if binding is None:
            binding = policy.bindings.add(
                role="roles/spanner.fineGrainedAccessUser",
            )
            binding.condition.title = f"fgac_{database_role}"
            binding.condition.expression = condition_expr

        if iam_member not in binding.members:
            binding.members.append(iam_member)

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.

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.


@conftest.live_only
def test_enable_fine_grained_access_live(capsys: pytest.CaptureFixture[str]) -> None:
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).

Problem: review of this sample identified correctness and robustness
improvements in the sample and its tests.

Solution: apply the accepted review suggestions and extend the tests to
cover the updated behavior. Details are in the review thread replies.

Files updated:
  - spanner/database_admin/tests/enable_fine_grained_access_test.py
Problem: reviewers of this sample set asked for stricter and clearer tests
and for a single source of truth for dependencies. Mocks were created
without a spec, so a renamed client argument would pass silently; the
mocked wait timeout was raised from the API call instead of from the
operation's result; live tests did not say which environment variables
they need; and some tests carried leftover or repeated lines. Package
dependencies were pinned in both pyproject.toml and requirements.txt.

Solution: where applicable to the files below, patch client classes with
autospec=True, raise the mocked TimeoutError from operation.result(),
document the required environment variables above each live test and skip
when one is missing, remove unused or duplicated test lines, and join
string literals that the formatter had left split on one line. For
package scaffolding, read dependencies from requirements.txt and update
the README install command to match.

Files updated:
  - spanner/database_admin/tests/enable_fine_grained_access_test.py

@angelcaamal angelcaamal left a comment •

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.

Overall looks great! Just left one comment on the IAM role bindings for FGAC.

policy = client.get_iam_policy(request=get_request)
policy.version = 3
binding = 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).

Problem: the sample attached the database-role IAM condition to
roles/spanner.fineGrainedAccessUser and never granted
roles/spanner.databaseRoleUser. The SetIamPolicy call succeeds, but the
principal is not granted access to the database role, so the sample did not do
what it describes. The same single-binding pattern exists in the earlier Python
sample this one replaces. The tests only checked that a policy was written, so
they did not catch it. Found in review by angelcaamal.

Solution: add two bindings, as the Spanner fine-grained access control
documentation describes: roles/spanner.fineGrainedAccessUser without a
condition, which makes the principal a fine-grained access control user, and
roles/spanner.databaseRoleUser with the condition naming the database role.
The unit test now asserts both bindings on the policy that is sent. The live
test asserts both bindings are present afterwards and its cleanup removes both,
leaving any pre-existing unconditioned grant in place.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants