Skip to content

[Server] Reuse OPA metadata within each authorization call - #2110

Merged
yili-db merged 7 commits into
unitycatalog:mainfrom
Orcus01:fix/opa-metadata-reuse
Nov 14, 2026
Merged

yili-db merged 7 commits into
unitycatalog:mainfrom
Orcus01:fix/opa-metadata-reuse

Conversation

@Orcus01

@Orcus01 Orcus01 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

PR Checklist

  • A description of the changes is added to the description of this PR.
  • If there is a related issue, make sure it is linked to this PR.
  • 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 (not applicable: internal metadata reuse).

Description of changes

authorizeAny and authorizeAll currently reload the same identity, resource, and parent metadata for every evaluated privilege. This change builds the input once per call and reuses it while sending a separate OPA request for each privilege.

Privilege order, duplicate privileges, short-circuiting, empty-input results, and denial decisions and error handling from main are preserved. A missing metadata record now logs one warning per call with the full privileges list. The log key changes from privilege= to privileges=. Metadata remains local to the call; later calls reload it, and authorization decisions are not cached. No API or configuration changes.

Tests verify one metadata read transaction per call, separate ordered OPA requests, fresh metadata and decisions on later calls, and missing-record/database/OPA failures. The regression tests fail against the original implementation because of repeated reads.

Validation on the latest main (JDK 17):

  • build/sbt 'server/javafmtCheckAll' 'server/testOnly io.unitycatalog.server.auth.*' — 146 tests passed; formatting passed.
  • git diff --check — passed.

Fixes #2108.

@yili-db

yili-db commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

/review

throw new BaseException(
ErrorCode.UNAVAILABLE, "OPA response must contain a boolean result.allow");
for (Privileges action : actions) {
((ObjectNode) input.get("input")).put("privilege", action.name());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The new loop edits a JSON field that OpaInputBuilder already creates. Both classes now know how that part of the request is structured. A future change to the request format would need coordinated edits in both classes. This is a small maintainability concern.

Add a package-private setter to the existing builder and use it for both writes:

--- a/server/src/main/java/io/unitycatalog/server/auth/OpaAuthorizer.java
+++ b/server/src/main/java/io/unitycatalog/server/auth/OpaAuthorizer.java
@@ -107,5 +107,5 @@
       }
       for (Privileges action : actions) {
-        ((ObjectNode) input.get("input")).put("privilege", action.name());
+        inputBuilder.setPrivilege(input, action);
         if (evaluate(input) != requireAll) {
           return !requireAll;

--- a/server/src/main/java/io/unitycatalog/server/auth/OpaInputBuilder.java
+++ b/server/src/main/java/io/unitycatalog/server/auth/OpaInputBuilder.java
@@ -49,5 +49,5 @@
             principal.put("external_id", user.getExternalId());
           }
-          input.put("privilege", privilege.name());
+          setPrivilege(request, privilege);
           input.set("resource", resource(session, resourceType, resourceId));
           return request;
@@ -55,4 +55,8 @@
         "Could not build OPA authorization input",
         /* readOnly= */ true);
+  }
+
+  void setPrivilege(ObjectNode request, Privileges privilege) {
+    ((ObjectNode) request.get("input")).put("privilege", privilege.name());
   }

@yili-db
yili-db requested a review from timothyw553 November 6, 2026 20:36
@yili-db

yili-db commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] The logic looks correct to me: ordering, duplicates, short-circuit, empty-input results, NOT_FOUND denial, and UNAVAILABLE wrapping are all preserved, and the reused ObjectNode is serialized before the next privilege is set. A couple of small suggestions on the builder contract, and most of my comments are about trimming the new tests, which largely overlap existing ones.

Unrelated to this PR: the "All tests" failure is UnityAccessEvaluatorTest.batchChecksSharedParentsOncePerList, which looks like a skew with the READ METADATA change (#2086); the default "All tests" job also fails on main at 46daf40.

ObjectNode input;
try {
input = inputBuilder.build(principal, resourceType, resource, action);
input = inputBuilder.build(principal, resourceType, resource, actions[0]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Can we drop the privilege parameter from build? Right now actions[0] is written by build and then immediately overwritten by the first loop iteration. If build only gathers principal/resource metadata, setPrivilege becomes the single place a privilege gets bound, and the double write goes away.

"Authorization check denied: principal={}, privilege={}, resource={} {}: {}",
principal,
action,
actions[0],

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] nit: for authorizeAny(OWNER, SELECT) this now logs only privilege=OWNER, which reads as if only OWNER was checked. Maybe log Arrays.toString(actions) instead (and update missingMetadataLogsTheCheckAndMissingRecord)?

/* readOnly= */ true);
}

void setPrivilege(ObjectNode request, Privileges privilege) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Please add a one-line doc saying this changes, in place, a request returned by build; it only works on that envelope.


@ParameterizedTest
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
void readsMetadataOnceAndPreservesEachEvaluatedPrivilege(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Ordering and short-circuit are already covered by anyAndAllPreserveOrderingAndShortCircuit; the only new check here is "metadata read once", and the nested ternaries make it hard to follow. Can we instead add assertMetadataReadOnce() to one case of the existing test (e.g. a denied authorizeAny(OWNER, SELECT)) and drop this 4-way parameterized test?


@ParameterizedTest
@ValueSource(booleans = {false, true})
void reloadsMetadataOnTheNextCallAndDoesNotCacheDecisions(boolean requireAll) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] A guard against cross-call reuse makes sense, but verifying openSession() twice across two calls would be enough. Do we need the renamed table / updated email setup and the requireAll parameterization?

}

@Test
void emptyPrivilegesDoNotReadMetadataOrCallOpa() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] This repeats the empty-input assertions at the end of anyAndAllPreserveOrderingAndShortCircuit. Adding verifyNoInteractions(sessionFactory) there would cover it.


@ParameterizedTest
@ValueSource(booleans = {false, true})
void metadataFailuresStopMultiPrivilegeChecksBeforeHttp(boolean requireAll) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] This mostly repeats metadataFailureStopsBeforeHttpAndDoesNotExposeDatabaseDetails; since authorize now goes through the same path, what does the multi-privilege variant add? nit: this and opaFailureStopsMultiPrivilegeChecks pass arguments to catchThrowableOfType in different orders.


@ParameterizedTest
@CsvSource({"false,{}", "true,{}", "false,not json", "true,not json"})
void opaFailureStopsMultiPrivilegeChecks(boolean requireAll, String invalidReply) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Nice, this is the one that really matters: it's the only test showing a bad reply on a later privilege stops the loop.

@yili-db

yili-db commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Re-review of 068f4b5: all prior comments from the 11-07 review are addressed in code, and I found no blockers. Three follow-ups below. The first two are inline. The third is for the PR description.

The description still says denial handling is unchanged. The warn key changed from privilege= to privileges=[...], and a multi-privilege miss now logs one line per call instead of one per privilege. One sentence in the description covers it.


clearInvocations(sessionFactory, session);
assertThat(authorizer.authorizeAny(principal, TABLE, table, OWNER, SELECT)).isFalse();
assertPrivileges("OWNER", "SELECT");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] The PR description says duplicate privileges are preserved, but no test sends a duplicate now. The removed reloads variant used OWNER, SELECT, SELECT, and that was the only case. Can we add SELECT, SELECT to anyAndAllPreserveOrderingAndShortCircuit? For example, authorizeAny(..., SELECT, SELECT) should send two OPA requests, with assertPrivileges("SELECT", "SELECT").

allowOnly();
assertThat(authorizer.authorizeAny(principal, TABLE, table, OWNER, SELECT)).isFalse();
assertThat(authorizer.authorizeAny(principal, TABLE, table, OWNER, SELECT)).isFalse();
verify(sessionFactory, times(2)).openSession();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] This is covered by the assertMetadataReadOnce() after clearInvocations in anyAndAllPreserveOrderingAndShortCircuit. If you keep this test, one line covers the decision half: assertThat(requests).hasSize(4).

@yili-db

yili-db commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Thanks for the follow-up, @Orcus01. The duplicate-privilege case and the decision count are both covered now, and the merge with main keeps the upstream OPA changes intact. Great work on the refactor.

Two small things for the PR description and one test to strengthen. Each is inline or listed here:

  • The description says the warning carries the full privileges list. It would help to also say that the key changed from privilege= to privileges=, so anyone matching the old key in alerts knows to update.

Also, if you have a moment, consider adding build a one-line Javadoc noting the result has no privilege yet, so the two-step contract is visible to future callers.

"WARN Authorization check denied",
"principal=" + principal,
"privilege=SELECT",
"privileges=[SELECT]",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Nice touch on the log assertion. Since the description promises the full privileges list, could we also cover the multi-privilege case here? For example, call authorizeAny(principal, TABLE, table, OWNER, SELECT) against missing metadata and assert one WARN line containing privileges=[OWNER, SELECT]. That would lock in the behavior the PR describes.

assertThat(error.getErrorCode()).isEqualTo(ErrorCode.UNAVAILABLE);
assertThat(error)
.hasMessage(
invalidReply.equals("{}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Small readability idea: could the expected message be a @CsvSource column instead of a ternary on invalidReply? That would keep each case readable in one row.


ObjectNode build(
UUID principalId, SecurableType resourceType, UUID resourceId, Privileges privilege) {
ObjectNode build(UUID principalId, SecurableType resourceType, UUID resourceId) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Optional: a one-line Javadoc here saying the returned request has no privilege yet, and that setPrivilege has to be called before it is sent, would make the two-step contract clear to future callers.

@yili-db

yili-db commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Thanks, @Orcus01. This round closes the multi-privilege log gap, the @CsvSource cleanup, the build Javadoc, and the key rename in the description. Nice work.

Two small optional inline suggestions, plus one line for the description. From my side this is in good shape.

  • The JSON sent to OPA now lists privilege after resource. OPA ignores key order, but raw request logs will show it, so one line in the description would help.

assertPrivileges("OWNER", "SELECT");
assertMetadataReadOnce();
clearInvocations(sessionFactory, session);
assertThat(authorizer.authorizeAny(principal, TABLE, table, SELECT, SELECT)).isFalse();

@yili-db yili-db Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Nice, the duplicate case is now covered for authorizeAny. Could we add the authorizeAll side too? With allowOnly(SELECT) first, authorizeAll(principal, TABLE, table, SELECT, SELECT) should return true after two requests, with assertPrivileges("SELECT", "SELECT").

throw new BaseException(
ErrorCode.UNAVAILABLE, "OPA returned HTTP " + response.status().code());
for (Privileges action : actions) {
inputBuilder.setPrivilege(input, action);

@yili-db yili-db Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Small behavior note: before this change, a null entry in actions failed inside build and was reported as INTERNAL. Now it fails inside the OPA block and is reported as UNAVAILABLE, which blames OPA for a caller bug. An Objects.requireNonNull on each element before the loop would keep the old mapping. If null is not a supported input, leaving it as is is also fine.

@yili-db
yili-db merged commit f898fb0 into unitycatalog:main Nov 14, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Server] Avoid reloading OPA metadata for each privilege check

3 participants