Skip to content

feat(policy): Add UnsafeUpdateKey implementation#3731

Open
c-r33d wants to merge 14 commits into
mainfrom
unsafe-update-key-impl
Open

feat(policy): Add UnsafeUpdateKey implementation#3731
c-r33d wants to merge 14 commits into
mainfrom
unsafe-update-key-impl

Conversation

@c-r33d

@c-r33d c-r33d commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements UnsafeUpdateKey for KAS registry keys.

Changes

  • Added DB support for unsafe key updates.

  • Supports:

    • public key only -> remote with provider config
    • remote -> public key only, clearing provider config
    • remote provider config replacement
  • Added validation for unsupported existing key modes.

  • Added typed errors for unsafe update validation failures.

  • Added integration coverage in kas_registry_key_test.go.

  • Added focused unit coverage for unsafe key update validation.

Depends on:

Summary by CodeRabbit

  • New Features

    • Added an unsafe key update operation that can update key modes and provider configuration data and returns the updated key.
    • Introduced request validation for IDs, allowed key-mode transitions, and provider configuration requirements.
    • Audit events now capture original and updated key details for unsafe updates.
  • Bug Fixes

    • Improved update error handling with clearer status codes for invalid transitions and missing provider configurations.
  • Tests

    • Added integration and unit tests covering success paths, validation failures, unsupported modes, and provider configuration error cases.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 43ee7f70-e3f1-4920-966a-d0a408400125

📥 Commits

Reviewing files that changed from the base of the PR and between ded9cd8 and 654c6f1.

⛔ Files ignored due to path filters (1)
  • service/go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • service/go.mod
  • service/integration/kas_registry_key_test.go
  • service/policy/db/key_access_server_registry.go
  • service/policy/db/key_access_server_registry_test.go
  • service/policy/unsafe/unsafe_test.go

📝 Walkthrough

Walkthrough

Implements the UnsafeUpdateKey RPC across request validation, database updates, transactions, audit logging, error mapping, dependency updates, and integration tests. Supported key-mode transitions and provider-configuration rules are covered by unit and integration tests.

Changes

Unsafe key update

Layer / File(s) Summary
Validation and status contracts
service/pkg/db/errors.go, service/pkg/db/errors_test.go, service/policy/db/key_access_server_registry_test.go, service/policy/unsafe/unsafe_test.go
Adds unsafe-update errors, Connect status mappings, request validation tests, and key-mode validation tests.
Database unsafe update
service/policy/db/queries/..., service/policy/db/key_access_server_registry.sql.go, service/policy/db/key_access_server_registry.go
Adds the SQL update operation and validates key IDs, modes, provider configurations, affected rows, and refreshed key results.
RPC orchestration and audit
service/policy/unsafe/unsafe.go, service/policy/kasregistry/key_access_server_registry.go, service/go.mod
Implements transactional unsafe updates with audit values, statusifies regular update failures, and updates direct protocol and SDK versions.
Integration coverage and fixtures
service/integration/kas_registry_key_test.go
Tests key-mode transitions, provider-configuration changes, failure cases, persisted results, and cleanup.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant UnsafeService
  participant PolicyDBClient
  participant Database
  participant AuditLogger
  Client->>UnsafeService: UnsafeUpdateKey request
  UnsafeService->>PolicyDBClient: Load existing key
  PolicyDBClient->>Database: Validate and update key
  Database-->>PolicyDBClient: Updated key
  PolicyDBClient-->>UnsafeService: Return updated key
  UnsafeService->>AuditLogger: Record original and updated values
  UnsafeService-->>Client: UnsafeUpdateKey response
Loading

Possibly related PRs

Suggested reviewers: jakedoublev

Poem

I’m a rabbit with keys in a row,
Updating their modes as they go.
With configs checked tight,
And audits just right,
Safe trails through the database glow.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding an UnsafeUpdateKey implementation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch unsafe-update-key-impl

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added comp:db DB component comp:policy Policy Configuration ( attributes, subject mappings, resource mappings, kas registry) comp:sdk A software development kit, including library, for client applications and inter-service communicati docs Documentation size/m labels Jul 7, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces an 'UnsafeUpdateKey' operation to the KAS registry, enabling administrative updates to key modes and provider configurations. This functionality is designed for support scenarios where keys need to be reconfigured without deleting and recreating them, ensuring existing TDF decryptability is maintained where applicable. The changes include full gRPC service definitions, database layer updates, and robust validation to prevent invalid state transitions.

Highlights

  • UnsafeUpdateKey Implementation: Added a new 'UnsafeUpdateKey' RPC to the UnsafeService, allowing for in-place modification of KAS registry keys.
  • Key Mode Transitions: Implemented support for switching between REMOTE and PUBLIC_KEY_ONLY key modes, and updating provider configurations for existing REMOTE keys.
  • Validation and Error Handling: Added strict validation for key mode transitions and introduced typed errors to handle unsupported operations.
  • Testing Coverage: Added comprehensive integration tests in 'kas_registry_key_test.go' and unit tests for validation logic in 'key_access_server_registry_unsafe_test.go'.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Ignored Files
  • Ignored by pattern: docs/openapi/**/* (1)
    • docs/openapi/policy/unsafe/unsafe.openapi.yaml
  • Ignored by pattern: protocol/**/* (3)
    • protocol/go/policy/unsafe/unsafe.pb.go
    • protocol/go/policy/unsafe/unsafe_grpc.pb.go
    • protocol/go/policy/unsafe/unsafeconnect/unsafe.connect.go
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


A key once set in stone and cold, Now shifts its mode as we are told. With unsafe calls and careful care, We update keys with grace and flair.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@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 an unsafe key update operation (UnsafeUpdateKey) to the policy service, allowing support-only switching between REMOTE and PUBLIC_KEY_ONLY key modes or updating the provider configuration for existing remote keys. The changes span protocol definitions, database-layer implementation, audit logging, and comprehensive integration and unit tests. The code reviewer provided several valuable suggestions to enhance the robustness and cleanliness of the implementation, including strengthening database-level validation of provider_config_id based on the target key mode, adding defensive nil checks to prevent potential panics, returning nil instead of empty structs in audit logs to reduce noise, and adding test cases to verify invalid provider configuration ID validation.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread service/policy/db/key_access_server_registry.go
Comment thread service/policy/db/key_access_server_registry.go
Comment thread service/policy/db/key_access_server_registry_test.go
Comment thread service/policy/db/key_access_server_registry_test.go
Comment thread service/policy/unsafe/unsafe.go
Comment thread service/policy/unsafe/unsafe.go
@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 206.401029ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 114.232398ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 426.494546ms
Throughput 234.47 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 47.803464599s
Average Latency 476.438324ms
Throughput 104.59 requests/second

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 203.855015ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 110.501836ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 423.725647ms
Throughput 236.00 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 45.081782726s
Average Latency 448.679812ms
Throughput 110.91 requests/second

@c-r33d
c-r33d marked this pull request as ready for review July 21, 2026 14:44
@c-r33d
c-r33d requested review from a team as code owners July 21, 2026 14:44
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 226.354622ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 112.805941ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 408.209186ms
Throughput 244.97 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 49.724833218s
Average Latency 496.203717ms
Throughput 100.55 requests/second

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
service/policy/kasregistry/key_access_server_registry.go (1)

299-324: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Double-StatusifyError wrapping silently downgrades all UpdateKey failures to CodeInternal.

Line 303-304 now statusifies the error inside the RunInTx callback, but line 322-324 (unchanged) statusifies it again outside. StatusifyError's first call wraps the error in connect.NewError(code, errors.New(ErrTextXxx)) — a brand-new error unrelated to the original sentinel (e.g. db.ErrCannotUpdateToUnspecified). connect.Error.Unwrap() returns that fresh inner error, so on the second pass none of the errors.Is(err, ErrXxx) checks in StatusifyError match, and it falls through to the generic connect.CodeInternal fallback — discarding the correctly classified code and message from the first call.

This affects every failure path of the pre-existing UpdateKey RPC (e.g. ErrCannotUpdateToUnspecified should map to CodeInvalidArgument, but will now return CodeInternal). service/policy/unsafe/unsafe.go's new UnsafeUpdateKey shows the correct pattern: statusify once inside the callback, then propagate the error unchanged outside.

🐛 Proposed fix: remove the redundant outer statusify
 	if err != nil {
-		return nil, db.StatusifyError(ctx, s.logger, err, db.ErrTextUpdateFailed, slog.String("key_access_server_keys", req.Msg.GetId()))
+		return nil, err
 	}
 
 	return connect.NewResponse(rsp), nil
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/policy/kasregistry/key_access_server_registry.go` around lines 299 -
324, Remove the redundant outer StatusifyError call after RunInTx in the
UpdateKey flow. Return the transaction error unchanged so the statusified error
produced inside the callback retains its original Connect code and message,
matching the propagation pattern used by UnsafeUpdateKey.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@service/policy/db/key_access_server_registry.go`:
- Around line 623-630: In the KeyMode_KEY_MODE_UNSPECIFIED branch of the key
access server registry update logic, validate newProviderConfiguration.Valid
before checking existingMode so an empty provider configuration returns
ErrUnsafeUpdateKeyProviderConfigRequired rather than the existing-mode error.
Preserve the current behavior for valid provider configurations and add coverage
for existingMode PUBLIC_KEY_ONLY, requestMode UNSPECIFIED, and an empty provider
configuration.

---

Outside diff comments:
In `@service/policy/kasregistry/key_access_server_registry.go`:
- Around line 299-324: Remove the redundant outer StatusifyError call after
RunInTx in the UpdateKey flow. Return the transaction error unchanged so the
statusified error produced inside the callback retains its original Connect code
and message, matching the propagation pattern used by UnsafeUpdateKey.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2aa85237-02e8-422e-a405-af339e236edf

📥 Commits

Reviewing files that changed from the base of the PR and between c89b193 and ded9cd8.

📒 Files selected for processing (10)
  • service/integration/kas_registry_key_test.go
  • service/pkg/db/errors.go
  • service/pkg/db/errors_test.go
  • service/policy/db/key_access_server_registry.go
  • service/policy/db/key_access_server_registry.sql.go
  • service/policy/db/key_access_server_registry_test.go
  • service/policy/db/queries/key_access_server_registry.sql
  • service/policy/kasregistry/key_access_server_registry.go
  • service/policy/unsafe/unsafe.go
  • service/policy/unsafe/unsafe_test.go

Comment thread service/policy/db/key_access_server_registry.go
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 158.769742ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 84.079375ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 337.116313ms
Throughput 296.63 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 40.342764003s
Average Latency 401.817594ms
Throughput 123.94 requests/second

@github-actions

Copy link
Copy Markdown
Contributor

@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 210.887768ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 106.333627ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 449.6384ms
Throughput 222.40 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 51.45754356s
Average Latency 512.878575ms
Throughput 97.17 requests/second

@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 204.470577ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 114.624143ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 428.7823ms
Throughput 233.22 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 50.20987235s
Average Latency 500.615588ms
Throughput 99.58 requests/second

@c-r33d
c-r33d requested a review from a team as a code owner July 21, 2026 21:19
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 171.776534ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 113.644617ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 419.896182ms
Throughput 238.15 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 49.779817451s
Average Latency 495.779658ms
Throughput 100.44 requests/second

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Govulncheck found vulnerabilities ⚠️

The following modules have known vulnerabilities:

  • examples
  • otdfctl
  • sdk
  • service
  • lib/fixtures
  • tests-bdd

See the workflow run for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:db DB component comp:policy Policy Configuration ( attributes, subject mappings, resource mappings, kas registry) comp:sdk A software development kit, including library, for client applications and inter-service communicati docs Documentation size/m

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant