Repository navigation
[Server] Add ownership transfer - #2149
Conversation
01a3248 to
f3a9209
Compare
## 🥞 Stacked PR Use this [link](https://github.com/unitycatalog/unitycatalog/pull/2088/files) to review incremental changes. - [**stack/split/pr2088-manage-only-20261106**](#2088) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2088/files)] ← _this PR_ - [stack/split/ownership-transfer-after-manage-20261106](#2149) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2149/files/bd264af6dcbaa219b02f30de72fdd01e6e805ed8..f3a92097e7c4c5f39321d2f18434e69905182feb)] --------- **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [x] If there is a related issue, make sure it is linked to this PR. - [x] If you've fixed a bug or added code that should be tested, add tests! - [x] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** This lets an owner delegate object administration with `MANAGE`. For example, an owner can let Alice manage access to `main.public.sales`: ```http PATCH /api/2.1/unity-catalog/permissions/table/main.public.sales Content-Type: application/json {"changes": [{"principal": "[email protected]", "add": ["MANAGE"]}]} ``` With `USE CATALOG` on `main` and `USE SCHEMA` on `main.public`, Alice can grant Bob `SELECT` without owning the table: ```http PATCH /api/2.1/unity-catalog/permissions/table/main.public.sales Content-Type: application/json {"changes": [{"principal": "[email protected]", "add": ["SELECT"]}]} ``` Managers can read full metadata and grants, change grants, update supported metadata, and delete supported objects. Catalog and schema grants also cover their children. Callers need usage grants above the scope where they hold `MANAGE`. The metastore does not support `MANAGE`. Data credentials, model publishing, and creation still use their existing permission checks. Managers can grant themselves other privileges. Delegated managers need creation rights to rename catalogs, schemas, tables, volumes, and models, including when strict checks are disabled. They can rename external locations and credentials with `MANAGE`. The implementation extends the existing authorization rules. API request formats and persistence code are unchanged. Ownership transfer is the second PR in this stack: #2149. It depends on this PR. Validation passed: 63 focused tests on H2 and 63 on MySQL 8. These cover authorization, grant handling, MANAGE, Iceberg credentials, and legacy rename rules. Java formatting and server/test Checkstyle also passed. ```sh build/sbt javafmtAll server/checkstyle server/Test/checkstyle build/sbt "server/testOnly io.unitycatalog.server.auth.decorator.UnityAccessEvaluatorTest io.unitycatalog.server.service.PermissionServiceTest io.unitycatalog.server.sdk.access.SdkManageAccessControlTest io.unitycatalog.server.sdk.access.SdkIcebergCredentialMigrationTest io.unitycatalog.server.sdk.access.SdkModelRenameLegacyAccessControlTest io.unitycatalog.server.sdk.access.SdkVolumeRenameLegacyAccessControlTest" ``` Related: #1823. --------- Signed-off-by: Timothy Wang <[email protected]>
f3a9209 to
7c048d3
Compare
|
/review |
1 similar comment
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Review of ac9f222. Main asks: (1) call out the released owner field change on credential and external location updates; (2) add deny tests for credential and external location owner changes; (3) decide whether the global denial after a failed reload is intended, and document it; (4) move the casbin_rule SQL behind JCasbinAuthorizer.
Items with no commentable line in the diff:
- The regenerated
ui/src/types/api/catalog.gen.tspicks up changes unrelated to ownership (for example the/staging-tablespath). Can we split those hunks into their own PR, or name them in the description, so the diff shows only the owner changes? RepositoryUtils.isViewLike(server/src/main/java/io/unitycatalog/server/persist/utils/RepositoryUtils.java:143-146) coversVIEWandMETRIC_VIEW, but notMATERIALIZED_VIEWorSTREAMING_TABLE. Both are rejected at create time today, so nothing is exposed. Once they are supported, a MANAGE holder could hand one to any user throughPATCH /tables. Can we add them now, or track it in an issue?
| type: string | ||
| owner: | ||
| description: Username of current owner of credential. | ||
| description: Username of the new owner. The user must already exist. |
There was a problem hiding this comment.
[AI Assisted] The owner field on UpdateCredentialRequest (here, and on UpdateExternalLocation at line 3116) shipped in v0.3.0, and the server ignored it on PATCH until now. Existing clients that echo a stored owner back in an update will now transfer ownership, or move it back if their copy is stale. Can we call this out explicitly in the PR description, docs/server/auth.md, and the release notes, and say whether a migration path is needed?
There was a problem hiding this comment.
Added an upgrade note to the PR description and auth guide. Clients must omit owner unless they intend to transfer ownership. No database migration is needed.
There was a problem hiding this comment.
[AI Assisted] Nit: the upgrade note covers credential and external location only. Could it also name the other PATCH endpoints that accept owner now (catalog, schema, volume, and registered model)?
There was a problem hiding this comment.
Added catalog, schema, volume, and registered model PATCH requests to the ownership-transfer documentation. (AI assisted)
| new ExternalLocationsApi(manager) | ||
| .updateExternalLocation(LOCATION, new UpdateExternalLocation().comment("managed location")); | ||
| .updateExternalLocation( | ||
| LOCATION, new UpdateExternalLocation().owner(PRINCIPAL_2).comment("managed location")); |
There was a problem hiding this comment.
[AI Assisted] We have allow cases for credential and external location owner changes (lines 412 and 417) but no deny case. Since these expressions now gate an owner change, can we add one where a principal with no OWNER or MANAGE on the object gets PERMISSION_DENIED and the owner is unchanged?
There was a problem hiding this comment.
Added both cases in 4338278. They check PERMISSION_DENIED and verify that the stored owner stays unchanged.
| } | ||
|
|
||
| @Override | ||
| public void reloadAuthorizations() { |
There was a problem hiding this comment.
[AI Assisted] When the post-commit reload fails, reloadAuthorizations installs an enforcer that denies every principal, including metastore admins, until a later request reloads successfully. The client also gets an error even though the transfer committed (see AuthorizedService.java:72-80). Failing closed is the right direction. Is the global denial intended? If so, can we document it in the Javadoc and docs/server/auth.md? Would applying the committed OWNER delta to the in-memory enforcer on failure be a narrower option?
There was a problem hiding this comment.
Yes, denying all users on that instance is intentional. Keeping stale permissions could retain the previous owner's access. The Javadoc and auth guide now explain recovery and the possibility that the transfer committed before the error. I’d keep partial cache updates outside this PR.
| // The JDBC adapter commits on a separate connection. Use this transaction for both writes. | ||
| session | ||
| .createNativeMutationQuery( | ||
| "DELETE FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND v2 = :owner") |
There was a problem hiding this comment.
[AI Assisted] The owner update writes casbin_rule with raw SQL from the repository, so the repository now depends on the JDBC adapter's table and column names. Keeping the owner column and the OWNER row in one transaction is the right call, and the rollback test covers it. Could the SQL move into JCasbinAuthorizer behind a method that takes the Session, so the repository calls the authorizer and the schema stays in one place? Create and grant write the OWNER row after commit, so this is stronger than the existing pattern, not a copy of it.
There was a problem hiding this comment.
I’d keep the SQL in OwnershipRepository for this PR. This helper keeps the ownership writes together in the caller’s transaction. Moving it into the authorizer would require more wiring without changing that guarantee.
There was a problem hiding this comment.
[AI Assisted] Agreed the transaction guarantee holds either way, so this is about where the table knowledge lives. Today only auth/ knows the casbin_rule layout (the refresher reads it there), and this change would make persist/ a second owner of it. The OPA forwarding gap already shows how easily that goes wrong. Could we add a default method on UnityCatalogAuthorizer, List<UUID> replaceOwner(Connection connection, UUID resource, UUID newOwner), with an empty default that returns no old owners? Implement the current SQL in JCasbinAuthorizer, forward it from OpaAuthorizer and AuditingAuthorizer (the wrapper must forward it, or the SQL is skipped), and call it from OwnershipRepository inside session.doWork. That keeps the same transaction and returns the old owners for the audit read. It is roughly 30 to 50 lines, mostly moved, and follows the reloadAuthorizations pattern already in this PR.
There was a problem hiding this comment.
Moved the SQL into JCasbinAuthorizer.replaceOwner(Session, ...), using the caller’s transaction. I kept it static because both authorization modes use the native grant store, which avoids extra startup and wrapper wiring. The repository still depends on Casbin, so this is a narrower change than your interface proposal.
There was a problem hiding this comment.
[AI Assisted] Thanks for moving the SQL out of the repository. Nit: OwnershipRepository now calls the static JCasbinAuthorizer.replaceOwner, so persistence depends on the concrete class. Could this become an interface method with a no-op default, so persistence stays on the abstraction? This is a nit: the table layout now lives only in auth/.
There was a problem hiding this comment.
I kept the static helper to avoid changing repository construction and authorizer wrappers in this PR. The helper uses the caller’s transaction and keeps the native policy SQL in auth/. (AI assisted)
| """ | ||
| #authorizeAny(#principal, #catalog, OWNER, MANAGE) && | ||
| (#authorizeAny(#principal, #catalog, OWNER, MANAGE) || | ||
| (#owner != null && #new_name == null && #comment == null && |
There was a problem hiding this comment.
[AI Assisted] The owner-only metastore-admin branch is repeated in four expressions with small differences (catalog and schema also exclude properties; see also SchemaService.java:123, VolumeService.java:160, and ModelService.java:143). Can we move it into one constant in AuthorizeExpressions, so catalog, schema, volume, and model share it and the exclusions cannot drift? The table and function PATCH endpoints only carry owner, so they only need the metastore check. The self-only rule for views, functions, and models can stay in validateOwnerTransfer.
There was a problem hiding this comment.
The expressions check different request fields. I’d keep those checks explicit here and leave extraction to a separate refactor.
There was a problem hiding this comment.
[AI Assisted] The four copies differ only in the properties clause, and this PR adds all four, so I would rather land the shared constant here than in a later refactor. The constant can include #properties == null || #properties.isEmpty(). Volume and model do not bind #properties; please confirm it evaluates as null there, which keeps the same constant valid.
There was a problem hiding this comment.
Extracted UPDATE_OWNER and used it in all four handlers. Unbound properties evaluates to null for volumes and models. Their admin transfer tests pass with the shared expression.
| } | ||
|
|
||
| /** Reloads ownership policy even when session cleanup fails after a commit. */ | ||
| protected <T> T updateWithOwnerReload(String newOwner, Supplier<T> update) { |
There was a problem hiding this comment.
[AI Assisted] Two follow-ups, not blocking: (a) updateWithOwnerReload reloads the whole policy under the write lock even when the owner is unchanged. Comparing before the reload would skip it. (b) The reload only affects this instance. With the default server.authorization.policy-refresh off (server/src/main/java/io/unitycatalog/server/utils/ServerProperties.java:268), other instances keep the old OWNER grant until restart. That matches existing grant changes, but the description and docs should not say the old owner loses access immediately.
There was a problem hiding this comment.
Updated the guide and PR description to explain that the reload is local and other instances need policy refresh. I’d leave the unchanged-owner optimization outside this PR.
| .build()); | ||
| } | ||
|
|
||
| /** Records the removed OWNER grants and the new OWNER grant only after commit. */ |
There was a problem hiding this comment.
[AI Assisted] Every owner change writes an OWNER REVOKE and GRANT audit record, including when the new owner is the current owner. Should a no-op transfer skip the audit records?
There was a problem hiding this comment.
The implementation still removes and inserts OWNER grants when the requested owner is unchanged. I’d keep the audit records aligned with those writes. Treating this as a no-op should cover both the stored grants and the owner field.
There was a problem hiding this comment.
[AI Assisted] Nit: a same-owner transfer still rewrites the OWNER row and emits the REVOKE and GRANT audit pair. Should a no-op transfer skip both?
There was a problem hiding this comment.
Matching owner metadata does not guarantee that the stored OWNER grants match. I kept the rewrite and its audit records so a repeated transfer can repair those grants. (AI assisted)
| * @param owner the requested username | ||
| * @return the stored username | ||
| */ | ||
| public String updateOwner(Session session, IdentifiableDAO resource, String owner) { |
There was a problem hiding this comment.
[AI Assisted] A missing principal currently returns NOT_FOUND, the same code as a missing securable, so clients can tell them apart only by the message. Would a dedicated error code make sense? Happy to keep it if the message is enough.
There was a problem hiding this comment.
I’d keep NOT_FOUND. The message identifies the missing user, so I don’t think this needs another public error code.
A SCIM group can now be named in a grant and its members act with its
grants, OWNER included.
- Grants: the principal name resolves as a user's email first, then a
group's name (a group named like a user's email never takes that
user's grants). A name that is neither still fails "User not found".
Listings name a group by its name.
- Decisions: GroupMembershipAuthorizer wraps JCasbinAuthorizer without
changing UnityCatalogAuthorizer. When a user's own grants deny a
check, it repeats the check for each group the user is a member of,
read from uc_group_members at that moment (no cache), so removing a
member or deleting a group applies from the next request on every
instance. Grants, hierarchy and listings stay per principal.
- OPA input: principal.groups lists the user's groups as {id, name,
external_id}, ordered by name; empty when the user has none.
- A group that owns the metastore can't be deleted (400), like such a
user. The user guard now looks at the user's own OWNER grant only, so
a member of a metastore-owning group can still be deleted or
deactivated.
Not in this change: transferring ownership to a group; ownership
transfer itself is not on main yet (unitycatalog#2149).
Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
…elete race - A grant that lands between deleteGroup's clear and its row delete leaves a casbin grant on a principal that no longer exists. GET permissions on that securable then failed with NOT_FOUND for every caller. Both listing paths now skip such an entry and log a WARN. - Add testGrantRacingGroupDeleteKeepsListingReadable (red with NOT_FOUND "User not found: <group id>" before the fix). - SdkScim2GroupTest writes OWNER grants through a second JCasbinAuthorizer over the server's store, with policy refresh on for the class, instead of reading the server's authorizer by reflection. - TODO(unitycatalog#2149) where ownership transfer and reloadAuthorizations() must change once unitycatalog#2149 lands. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
A SCIM group can now be named in a grant and its members act with its
grants, OWNER included.
- Grants: the principal name resolves as a user's email first, then a
group's name (a group named like a user's email never takes that
user's grants). A name that is neither still fails "User not found".
Listings name a group by its name.
- Decisions: GroupMembershipAuthorizer wraps JCasbinAuthorizer without
changing UnityCatalogAuthorizer. When a user's own grants deny a
check, it repeats the check for each group the user is a member of,
read from uc_group_members at that moment (no cache), so removing a
member or deleting a group applies from the next request on every
instance. Grants, hierarchy and listings stay per principal.
- OPA input: principal.groups lists the user's groups as {id, name,
external_id}, ordered by name; empty when the user has none.
- A group that owns the metastore can't be deleted (400), like such a
user. The user guard now looks at the user's own OWNER grant only, so
a member of a metastore-owning group can still be deleted or
deactivated.
Not in this change: transferring ownership to a group; ownership
transfer itself is not on main yet (unitycatalog#2149).
Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
…elete race - A grant that lands between deleteGroup's clear and its row delete leaves a casbin grant on a principal that no longer exists. GET permissions on that securable then failed with NOT_FOUND for every caller. Both listing paths now skip such an entry and log a WARN. - Add testGrantRacingGroupDeleteKeepsListingReadable (red with NOT_FOUND "User not found: <group id>" before the fix). - SdkScim2GroupTest writes OWNER grants through a second JCasbinAuthorizer over the server's store, with policy refresh on for the class, instead of reading the server's authorizer by reflection. - TODO(unitycatalog#2149) where ownership transfer and reloadAuthorizations() must change once unitycatalog#2149 lands. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
A SCIM group can now be named in a grant and its members act with its
grants, OWNER included.
- Grants: the principal name resolves as a user's email first, then a
group's name (a group named like a user's email never takes that
user's grants). A name that is neither still fails "User not found".
Listings name a group by its name.
- Decisions: GroupMembershipAuthorizer wraps JCasbinAuthorizer without
changing UnityCatalogAuthorizer. When a user's own grants deny a
check, it repeats the check for each group the user is a member of,
read from uc_group_members at that moment (no cache), so removing a
member or deleting a group applies from the next request on every
instance. Grants, hierarchy and listings stay per principal.
- OPA input: principal.groups lists the user's groups as {id, name,
external_id}, ordered by name; empty when the user has none.
- A group that owns the metastore can't be deleted (400), like such a
user. The user guard now looks at the user's own OWNER grant only, so
a member of a metastore-owning group can still be deleted or
deactivated.
Not in this change: transferring ownership to a group; ownership
transfer itself is not on main yet (unitycatalog#2149).
Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
…elete race - A grant that lands between deleteGroup's clear and its row delete leaves a casbin grant on a principal that no longer exists. GET permissions on that securable then failed with NOT_FOUND for every caller. Both listing paths now skip such an entry and log a WARN. - Add testGrantRacingGroupDeleteKeepsListingReadable (red with NOT_FOUND "User not found: <group id>" before the fix). - SdkScim2GroupTest writes OWNER grants through a second JCasbinAuthorizer over the server's store, with policy refresh on for the class, instead of reading the server's authorizer by reflection. - TODO(unitycatalog#2149) where ownership transfer and reloadAuthorizations() must change once unitycatalog#2149 lands. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
|
On the two points in your review: Generated UI types Added an explanation to the PR description. These APIs already exist in Unsupported table types Creation currently rejects both types. I’d keep |
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Re-review at c03fc06. The author commit resolves round-1 findings 1, 2, 3, and 6 to 10 (the pushbacks on 9 and 10 are accepted). Still open for approval: the OPA reload forwarding (inline on the interface, normal), the view-type race (normal), the refresher not seeing count-neutral transfers (normal, or narrow the PR description), and the metastore-admin denial tests (normal). The rest are nits. The casbin_rule placement stays open in the finding 4 thread; the reply there explains the abstraction point.
|
|
||
| Map<UUID, List<Privileges>> listAuthorizations(UUID resource); | ||
|
|
||
| /** Reloads policy after a committed ownership transfer. Uncached authorizers need no action. */ |
There was a problem hiding this comment.
[AI Assisted] With server.authorization.provider=opa, OpaAuthorizer forwards listAuthorizations to the native enforcer (OpaAuthorizer.java:190, :195) but does not forward reloadAuthorizations, so the post-commit reload never reaches it. Permission listings in PermissionService.java:229-230 and :371 keep the previous owner until restart. Decisions in authorize do not read the native cache, so access is not affected. Can we forward reloadAuthorizations to nativeAuthorizer, and add a case that transfers ownership through an OPA-wrapped server and checks the listing? The interface Javadoc here also needs updating, since "Uncached authorizers need no action" no longer describes the OPA decorator.
There was a problem hiding this comment.
Added forwarding to the native authorizer and updated the interface docs. The OPA integration test now checks the native grants immediately after an ownership transfer.
| @AuthorizeResourceKey(METASTORE) | ||
| public HttpResponse updateTable( | ||
| @Param("full_name") @AuthorizeResourceKey(TABLE) String fullName, UpdateTable updateTable) { | ||
| if (RepositoryUtils.isViewLike(tableRepository.getTable(fullName).getTableType().getValue())) { |
There was a problem hiding this comment.
[AI Assisted] The view check here and the update at TableRepository.java:1219 run in separate transactions, and the update does not check the table type. A DROP and CREATE VIEW of the same name between them lets the new view skip the metastore-admin rule. Can the view check run inside the repository transaction on the locked row, after updateOwner refreshes it, so the check and the write see the same table?
There was a problem hiding this comment.
Moved the check into the update transaction, after locking and refreshing the table. Added a regression test that verifies a denied view transfer leaves the owner, grants, and audit records unchanged.
There was a problem hiding this comment.
[AI Assisted] The check now runs under the table row lock. The callback in TableRepository.java:1233 also calls findPrincipalId and getMetastoreId, which open their own transactions, and authorizer.authorize, which can be an HTTP call to OPA. Under concurrent view transfers, the nested connections can exhaust the pool. Can the service decide whether the caller may transfer to others before the transaction, and let the repository check only the view type under the lock?
There was a problem hiding this comment.
The service now checks the caller’s transfer authority before opening the write transaction. The repository applies that result to the locked, refreshed table type. This removes the nested transactions and OPA call from the view check under the lock. (AI assisted)
| // The JDBC adapter commits on a separate connection. Use this transaction for both writes. | ||
| session | ||
| .createNativeMutationQuery( | ||
| "DELETE FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND v2 = :owner") |
There was a problem hiding this comment.
[AI Assisted] An owner transfer deletes one casbin_rule row and inserts one, so count(*) does not change, and the poller depends on max(id) (server/src/main/java/io/unitycatalog/server/auth/CasbinPolicyRefresher.java:46-48). If another policy commit with a higher id lands first, the poller can record that maximum and then miss this transfer when it commits, so other instances keep the old OWNER row until another change. The PR description says revocations propagate on the poll interval. Can we make the transfer change a value the poller checks (for example a version row updated in the same transaction), or describe propagation as dependent on the poll and not guaranteed under concurrent commits?
There was a problem hiding this comment.
Corrected the auth guide and PR description. Concurrent commits can hide a transfer from the poller, so the polling interval is not a guaranteed revocation deadline.
| List<UUID> oldOwners = | ||
| session | ||
| .createNativeQuery( | ||
| "SELECT v0 FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND" |
There was a problem hiding this comment.
[AI Assisted] Under MySQL's default REPEATABLE READ, the user lookup at OwnershipRepository.java:43 opens the snapshot, so the audit SELECT at this line can read old OWNER rows after the locking refresh at :47 waits for a concurrent transfer. Can the old-owner query use a locking read (FOR UPDATE), or run before any other read? A concurrent-transfer test that asserts the audited principals would cover it.
There was a problem hiding this comment.
The previous-owner query now uses FOR UPDATE. The concurrent-transfer test checks the revoke and grant records for both transfers. It passes on H2, MySQL, and PostgreSQL.
| throw e; | ||
| } finally { | ||
| try { | ||
| authorizer.reloadAuthorizations(); |
There was a problem hiding this comment.
[AI Assisted] updateWithOwnerReload reloads in finally even when the update fails before commit, for example for a blank owner or an unknown user. A caller who can PATCH can force a full policy reload under the write lock, and if that reload fails the instance denies everyone. Can the reload be skipped for failures before commit, or can the blank-owner and user checks run before the wrapper?
There was a problem hiding this comment.
Blank and unknown owners now fail before entering the reload path. Added tests that verify neither case reloads permissions. Reload still runs after update failures because a transaction can commit before session cleanup fails.
There was a problem hiding this comment.
[AI Assisted] Thanks for the pre-commit validation. One follow-up: a clean rollback, for example a name conflict, still reloads in the finally block (AuthorizedService.java:81). If that reload fails, every user is denied although nothing changed. The post-commit cleanup case does need the reload. Could a flag set after the transaction commits decide whether to reload?
There was a problem hiding this comment.
Validation failures and name conflicts now skip reload. The flag is set immediately before the database commit, so an uncertain commit or later session-close failure still triggers reload. Added regression coverage for both paths. (AI assisted)
| () -> | ||
| new RegisteredModelsApi(adminApiClient) | ||
| .updateRegisteredModel( | ||
| MODEL, new UpdateRegisteredModel().owner(PRINCIPAL_2).comment("denied"))); |
There was a problem hiding this comment.
[AI Assisted] The metastore-admin owner-only branch is new, and the tests only deny owner with comment. The exclusions for new_name and properties are what keep that branch owner-only. Can we add denials for an admin sending owner with new_name, and for catalog and schema with properties?
There was a problem hiding this comment.
Added tests that reject admin requests which change both owner and name for catalogs, schemas, volumes, and models. Catalog and schema tests also reject requests that change both owner and properties.
| this.userRepository = userRepository; | ||
| this.authorizationEnabled = authorizationEnabled; | ||
| this.auditor = auditor; | ||
| } |
There was a problem hiding this comment.
[AI Assisted] The updateOwner Javadoc says it replaces the OWNER policy, but it does so only when authorization is enabled. The DELETE_TABLE Javadoc in AuthorizeExpressions.java:195-200 also does not mention that the table PATCH now uses this policy. Can we update both?
There was a problem hiding this comment.
Updated both Javadocs to explain when native grants change and how the table ownership endpoint uses the shared policy.
c03fc06 to
b631f93
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Re-review at b631f93. Still open for approval: the create-path window (inline), the mutations on the empty enforcer after a failed reload (inline), and the reload after a clean rollback (reply on the existing thread). The remaining items are nits: the same-owner rewrite, the refresh re-check, the test gaps, and the static dependency (inline or reply on the existing thread). The released credential and external location owner item from the first round is already covered by the PR description and docs/server/auth.md, so it is not repeated here.
| if (user == null) { | ||
| throw new BaseException(ErrorCode.NOT_FOUND, "User not found: " + owner); | ||
| } | ||
| session.refresh(resource, LockMode.PESSIMISTIC_WRITE); |
There was a problem hiding this comment.
[AI Assisted] CatalogService.java:79 commits the row before initializeBasicAuthorization writes the creator's OWNER grant. A transfer that lands in that gap inserts the recipient's OWNER first, then the creator's grant adds a second row, so the creator keeps owner access after the metadata names someone else. The same pattern exists in the other create paths. Can the creator's grant be written in the create transaction, through replaceOwner, so there is no window?
There was a problem hiding this comment.
Moved the creator’s OWNER grant into the create transaction. Added an HTTP test that pauses creation after commit, transfers ownership, then resumes creation and verifies that the creator cannot change grants. (AI assisted)
| denying.setAdapter(adapter); | ||
| denying.enableAutoSave(true); | ||
| currentEnforcer.set(denying); | ||
| reloadRequired = true; |
There was a problem hiding this comment.
[AI Assisted] While reloadRequired is set, grants and revokes still run on the empty enforcer, because mutate does not check the flag. For revokes, SyncedEnforcer.removePolicy writes the adapter delete before it checks the in-memory model, but the method returns false. For grants, addPolicy checks the empty model first and then inserts, which can duplicate an existing row. PermissionService then lists from the empty enforcer (PermissionService.java:229, :371). Can mutations and listings either reload first or throw while the flag is set, with a test that checks the stored rows after recovery?
There was a problem hiding this comment.
These operations now return UNAVAILABLE while recovery is required. The test restores database access before attempting them, then verifies that the stored grants remain unchanged after recovery. (AI assisted)
| */ | ||
| @Override | ||
| public boolean refreshAuthorizations(long operationStartNanos) { | ||
| if (reloadRequired) { |
There was a problem hiding this comment.
[AI Assisted] Nit: refreshAuthorizations reads reloadRequired before taking the write lock and does not check it again under the lock. Could it re-check under the lock, so concurrent denied requests do not each reload after the first one succeeds?
There was a problem hiding this comment.
Added the second check under the write lock. Waiting requests skip the extra reload once another request has recovered the policy. (AI assisted)
| .getCatalogRepository() | ||
| .updateCatalog( | ||
| CATALOG, new UpdateCatalog().owner(SECOND_OWNER).newName("occupied"))) | ||
| .isInstanceOf(BaseException.class) |
There was a problem hiding this comment.
[AI Assisted] Nit, test gaps: there is no authorization-disabled owner PATCH test; the invalid-owner assertions check only BaseException, not the error code (NOT_FOUND for a missing user, INVALID_ARGUMENT for a blank owner); and there is no not-found test for updateTable or updateFunction. Could these be added?
There was a problem hiding this comment.
Added HTTP coverage for ownership transfer with authorization disabled, invalid owners, and missing tables and functions. The error cases check the exact error codes. These tests pass on H2, MySQL, and PostgreSQL. (AI assisted)
b631f93 to
18bb059
Compare
Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
Save creator OWNER grants in the create transaction so a delayed request cannot restore ownership after a transfer. Reload transfer policy after a commit attempt, and reject policy changes and listings while reload recovery is required. Check view-transfer authority before opening the write transaction. Add real HTTP transfer and creation-race coverage. Verify rollback, recipient errors, missing resources, and authorization-disabled updates. Signed-off-by: Timothy Wang <[email protected]>
Read the committed OWNER row under the reload lock and add it to the local cache without writing policy again. A delayed create cannot restore a former owner. Keep full recovery when the cache is incomplete. Signed-off-by: Timothy Wang <[email protected]>
Use a real repositories fixture for credential creation and close its owned credential vendor after each test. Signed-off-by: Timothy Wang <[email protected]>
d647031 to
4e81394
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Review of 4e81394.
The blocker is D-2 (inline). Under provider=opa, one failed native reload leaves grants and permission listings returning UNAVAILABLE until a create, transfer, poller reload, or restart clears it.
D-3 (inline, normal) is the retry behavior while the store is down.
Nits are inline where they have a diff line. Outside the diff: docs/server/configuration.md:235-236 still describes OWNER as the grant made when an object is created. The audit now also emits REVOKE and GRANT on every transfer.
| } | ||
|
|
||
| @Override | ||
| public void reloadAuthorizations() { |
There was a problem hiding this comment.
[AI Assisted] Blocker: with server.authorization.provider=opa, a failed native reload leaves the native store refusing grants and permission listings. A harness run at this head showed the following:
- After one failed native reload, grant and list calls through the native store return
UNAVAILABLE. - The OPA deny path does not recover the native store, because
OpaAuthorizerdoes not forwardrefreshAuthorizations. - Only a create (
loadOwner), another owner transfer, the poller (when policy refresh is enabled), or a restart clears it. - OPA allow and deny decisions keep working throughout.
Could the native store retry a pending reload before grant, revoke, and list calls? Could a test cover recovery followed by a grant?
There was a problem hiding this comment.
Fixed. Native grant changes and permission reads now retry a pending reload. The OPA test covers recovery through either operation with polling disabled.
| */ | ||
| @Override | ||
| public boolean refreshAuthorizations(long operationStartNanos) { | ||
| if (reloadRequired) { |
There was a problem hiding this comment.
[AI Assisted] Normal: while reloadRequired is set, each denied request takes the write lock and retries the full reload. The re-check under the lock coalesces a success: once one reload succeeds, waiting requests skip theirs. A failed reload is not shared. In a harness run with the store down, four concurrent refreshes made four reload attempts, one per waiter. With the store up, four concurrent refreshes made one reload. Could failed retries be single-flight, with a minimum interval between attempts, so waiting requests share one attempt?
There was a problem hiding this comment.
Agreed. Concurrent requests can each retry a failed reload. I’d handle the retry interval in a separate change to keep this PR focused.
| repositories | ||
| .getOwnershipRepository() | ||
| .updateOwner(session, dao, updateTable.getOwner(), beforeCommit); | ||
| if (RepositoryUtils.isViewLike(dao.getType()) && !canTransferViewToRecipient) { |
There was a problem hiding this comment.
[AI Assisted] Nit: this check runs after updateOwner has locked the row and rewritten casbin_rule. Rollback undoes that work, so this only avoids wasted work. The message is also in AuthorizedService. Could the two share one definition?
There was a problem hiding this comment.
The check needs the table type refreshed under the lock. Rejection rolls back the ownership writes. I’d leave the duplicate message cleanup for a separate change.
| } | ||
|
|
||
| public CatalogInfo updateCatalog( | ||
| String name, UpdateCatalog updateCatalog, Runnable beforeCommit) { |
There was a problem hiding this comment.
[AI Assisted] Nit: each update repository has a second overload that takes no beforeCommit and delegates with an empty callback. Could one shared hook helper replace these overloads, so the transactional owner write has a single entry point?
There was a problem hiding this comment.
Both overloads use the same transaction path. The shorter one preserves existing callers. I’d keep the current form in this PR.
| Map<UUID, List<Privileges>> listAuthorizations(UUID resource); | ||
|
|
||
| /** Loads the saved OWNER grant for a created resource without writing it again. */ | ||
| default void loadOwner(UUID resource) { |
There was a problem hiding this comment.
[AI Assisted] Nit: the default loadOwner calls reloadAuthorizations, and creation no longer calls grantAuthorization for OWNER. A third-party authorizer with its own grant store would stop receiving the creator's grant. Could the contract change be documented, or could the old grant call stay as the default for non-native authorizers?
There was a problem hiding this comment.
Documented on loadOwner: authorizers with a separate grant store must handle creation explicitly. The default only reloads policy.
Retry a pending policy reload before native grant changes and permission listings. Keep these requests unavailable while recovery fails. Return the adapter connection before retrying so repeated failures do not exhaust the pool. Test recovery through HTTP with OPA and clarify the creation and audit contracts. Signed-off-by: Timothy Wang <[email protected]>
|
/review |
Signed-off-by: Timothy Wang <[email protected]>
|
/review |
1 similar comment
|
/review |
Signed-off-by: Timothy Wang <[email protected]>
|
/review |
Signed-off-by: Timothy Wang <[email protected]>
|
/review |
|
On the audit documentation note in your review: Updated. The audit docs now cover the |
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Approving at 4334cc6.
- D-2 (OPA provider) is fixed and verified with a harness. Under OPA, after one failed reload, grant and list calls now retry the reload before they run. The harness showed
UNAVAILABLEwhile the store is down and recovery once it returns, with no restart or create needed. - The reload failure is now wrapped as
UNAVAILABLE, so a rawErrorno longer escapes the reload path. - The hierarchy edge recovers on the next permission read after a failed
loadOwner.
Follow-up, not blocking:
- D-3: failed reloads are retried once per waiter rather than shared. This is agreed as a follow-up. Please link the tracking issue from the PR description or a comment once it exists.
Non-blocking, inline: a create returns 503 after its row has committed when loadOwner fails.
| protected void initializeBasicAuthorization(String resourceId) { | ||
| UUID principalId = userRepository.findPrincipalId(); | ||
| authorizer.grantAuthorization(principalId, UUID.fromString(resourceId), Privileges.OWNER); | ||
| authorizer.loadOwner(UUID.fromString(resourceId)); |
There was a problem hiding this comment.
[AI Assisted] Non-blocking: when loadOwner fails after the create transaction has committed, the create request returns 503 even though the object exists. A client retry then fails because the name is taken. Could the response or the ownership docs say that the object was created, so clients read it before retrying?
timothyw553
left a comment
There was a problem hiding this comment.
mainly concerned about the mysql locking on casbin_rule and the cross-server cache race, plus a few test coverage gaps around commit failure and rollback. otherwise looks like a solid step.
| List<UUID> oldOwners = | ||
| session | ||
| .createNativeQuery( | ||
| "SELECT v0 FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND" |
There was a problem hiding this comment.
to my understanding casbin_rule has no index on (ptype, v1, v2), so this SELECT ... FOR UPDATE and DELETE scan the table and block unrelated inserts and deletes under mysql REPEATABLE READ (and switching to READ COMMITTED wouldn't stop unrelated deletes from blocking). could we replace this scan with an indexed locking and deletion strategy, and add a mysql concurrency test for unrelated grants and revokes?
|
|
||
| @ParameterizedTest | ||
| @ValueSource(booleans = {false, true}) | ||
| void sessionCloseFailureStillReloadsCommittedOwnership(boolean reloadFails) { |
There was a problem hiding this comment.
this tests a failure in session.close(), not when commit() succeeds in the db and then throws, so reloading only after a normal commit would still pass. could we also mock transaction.commit() to call realTransaction.commit() and throw, checking both reload success and reload failure?
| return newOwner == null | ||
| || !serverProperties.isAuthorizationEnabled() | ||
| || newOwner.equals(IdentityUtils.findPrincipalEmailAddress()) | ||
| || authorizer.authorize( |
There was a problem hiding this comment.
calling authorizer.authorize directly here bypasses the refresh-and-retry logic in UnityAccessEvaluator, so a stale cache could reject a metastore admin transferring a view, function, or model. should we go through the shared refresh-and-retry path here and add a stale-admin test?
#2319) **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [x] If there is a related issue, make sure it is linked to this PR. - [x] If you've fixed a bug or added code that should be tested, add tests! - [ ] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** Transferring ownership of a function that has properties fails with a 500. For example, after creating `main.default.fn` with `properties` set to `{"team":"ml"}`, `PATCH /api/2.1/unity-catalog/functions/main.default.fn` with `{"owner": "[email protected]"}` returns `INTERNAL` "Failed to update function: java.lang.NoSuchMethodException: io.unitycatalog.server.model.FunctionInfo.setProperties(java.util.Map)". The transaction rolls back, so the owner and the OWNER grant stay with the previous owner, and the function can't be transferred while it has properties. Functions without properties are not affected. The function update added in #2149 builds its response with `RepositoryUtils.attachProperties`. That helper looks up a `setProperties(Map)` method by reflection, but `FunctionInfo.properties` is a JSON string. #2149 was written while `attachProperties` still had a special case for functions, and #2233 removed that special case after function properties moved to their own JSON rendering and nothing else called it for functions. The two PRs merged in the opposite order, so on `main` every transfer of a function stored with properties hits the `Map` lookup and fails. The fix renders the update response's properties the same way `getFunction` and `listFunctions` do, so a transfer returns the same properties JSON as a later get. The stored properties are not touched by the update. The other callers of `attachProperties` pass catalogs, schemas and tables, whose properties are maps, so they are unaffected. **Tests** `OwnershipRepositoryTest.functionTransferKeepsProperties` transfers a function stored with properties. It checks that the new owner is saved and holds the only OWNER grant, that `getFunction` still returns the original properties, and that the update response returns the same properties. It fails on `main` with the `NoSuchMethodException` above, and it also fails if the update response drops the properties. `build/sbt "server/testOnly io.unitycatalog.server.persist.OwnershipRepositoryTest"` passes on H2 on Windows with JDK 17, and so do `server/javafmtCheckAll` and the checkstyle tasks. The change has no SQL of its own, so MySQL and PostgreSQL run in CI. Signed-off-by: Maha Rana Yadavalli <[email protected]> Co-authored-by: Maha Rana Yadavalli <[email protected]>
No conflicts. Brings in ownership transfer (unitycatalog#2149), pool metrics (unitycatalog#2284) and the check that tests leave the checkout clean (unitycatalog#2334). Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
## 🥞 Stacked PR Use this [link](https://github.com/unitycatalog/unitycatalog/pull/2313/files) to review incremental changes. - [stack/ownership-transfer-followup-20261120](#2313) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2313/files)] --------- **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [x] If there is a related issue, make sure it is linked to this PR. - [x] If you've fixed a bug or added code that should be tested, add tests! - [x] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** Follow-up to #2149. On MySQL, transferring ownership could block grants and revokes for unrelated objects. A newly promoted metastore admin could also be denied a transfer because the server checked cached permissions. Ownership updates use `READ COMMITTED` and an index on permission lookups. The owner field and `OWNER` grants still change in one database transaction. The admin check uses the existing refresh and retry path. Refreshing grants from another server requires `server.authorization.policy-refresh=true`. The server tries to create the index at startup. If this fails, it logs a warning with the setup SQL and continues. Transfers can still block unrelated grants and revokes until the index exists. See the [setup and upgrade instructions](https://github.com/unitycatalog/unitycatalog/blob/6278bd6182531a5b423bb1f5f8392d46ad8331af/docs/server/upgrades.md). PostgreSQL index creation can pause permission writes on running instances during an upgrade. Validation: - 108 focused ownership, HTTP, authorization refresh, and transaction checks passed on each of H2, MySQL 8, and PostgreSQL 18. - Concurrency tests cover catalogs, schemas, volumes, tables, functions, and models. All six cases fail on MySQL without the isolation fix. - Startup tests cover denied index creation, a failed metadata recheck, concurrent creation, and connection cleanup after core setup fails. - Java formatting and server main/test Checkstyle passed. --------- Signed-off-by: Timothy Wang <[email protected]>
🥞 Stacked PR
Use this link to review incremental changes.
PR Checklist
docsis updatedDescription of changes
This adds ownership transfer for catalogs, schemas, tables and views, functions, volumes, registered models, external locations, and storage credentials. The new owner must be an existing user.
For example, an authorized owner or manager can transfer
main.public.salesto Bob:Tables and functions get ownership PATCH endpoints. Other supported update requests gain missing owner fields or start saving the existing owner field. Views, functions, and models can be transferred to oneself; assigning another user requires a metastore administrator.
Upgrade note: v0.3.0 accepted
owneron credential and external location PATCH requests but ignored it. These requests now transfer ownership whenowneris set. Clients must omitownerwhen changing only other fields, including clients that copy stored object fields into update requests. No database migration is required.Creation and transfer save the object owner field and its
OWNERgrant in one database transaction. After creation, the server loads only the savedOWNERgrant for that object into its local permission cache. A delayed create request cannot restore a former owner's grant. Concurrent metadata edits preserve the current owner. After a transfer commits, the server reloads its local permission cache. Validation failures leave the permission cache unchanged. Other instances needserver.authorization.policy-refresh=trueto detect changes. Concurrent commits can leave the policy row count and maximum ID unchanged, so the poll can miss a transfer until another detectable change or a restart. The poll interval is not a guaranteed revocation deadline.If the local reload fails, the request returns an error even though the transfer may have committed. With native authorization, permission checks on that instance deny every user, including metastore admins, until a reload succeeds. Grant changes and grant listings also fail while the cache is incomplete. A denied request retries the reload even when policy refresh is disabled. Read the owner after recovery before retrying a transfer.
Tests use real HTTP requests to transfer ownership for all eight resource types. They check that the new owner can change grants, the former owner cannot, and unrelated grants remain. They also cover delayed creation, rejected transfers, rollback, restart, concurrent changes, and failed reload recovery.
This builds on the MANAGE support merged in #2088.
API reference docs and UI types are regenerated from the API specification. The UI file also picks up existing API definitions, including staging tables and Delta commits, that were missing from the generated file.
Validation: the full H2 server run reported 1,434 passing tests and one lifecycle failure because a local server already used port 8080. All nine lifecycle tests passed when rerun in a separate network namespace. All 157 focused checks passed on both MySQL 8 and PostgreSQL 18. Java formatting and server main/test Checkstyle passed. Release-upgrade tests were not run locally.
Related: #1823.