Repository navigation
[Server] Add a privilege-level OPA authorizer #2077
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
timothyw553
merged 4 commits into
unitycatalog:main
from
timothyw553:stack/opa-authorizer
Nov 3, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
eef7d11
[Server] Add a privilege-level OPA authorizer
timothyw553 04815f2
[Server] Update OPA test database setup
timothyw553 e1a7bde
[Server] Keep OPA failures generic and deny missing metadata
timothyw553 263cd4d
[Server] Log missing OPA authorization metadata
timothyw553 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
178 changes: 178 additions & 0 deletions
178
server/src/main/java/io/unitycatalog/server/auth/OpaAuthorizer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| package io.unitycatalog.server.auth; | ||
|
|
||
| import com.fasterxml.jackson.databind.DeserializationFeature; | ||
| import com.fasterxml.jackson.databind.JsonNode; | ||
| import com.linecorp.armeria.client.ResponseTimeoutMode; | ||
| import com.linecorp.armeria.client.WebClient; | ||
| import com.linecorp.armeria.client.redirect.RedirectConfig; | ||
| import com.linecorp.armeria.common.AggregatedHttpResponse; | ||
| import com.linecorp.armeria.common.MediaType; | ||
| import io.unitycatalog.server.exception.BaseException; | ||
| import io.unitycatalog.server.exception.ErrorCode; | ||
| import io.unitycatalog.server.model.SecurableType; | ||
| import io.unitycatalog.server.persist.model.Privileges; | ||
| import io.unitycatalog.server.utils.JsonUtils; | ||
| import java.time.Duration; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.UUID; | ||
| import org.hibernate.SessionFactory; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| /** | ||
| * Delegates each privilege decision to OPA. Native grants and hierarchy remain available for | ||
| * permission management and resource bookkeeping, but do not affect OPA decisions. | ||
| */ | ||
| public class OpaAuthorizer implements UnityCatalogAuthorizer, AutoCloseable { | ||
| private static final Logger LOGGER = LoggerFactory.getLogger(OpaAuthorizer.class); | ||
| private static final int MAX_RESPONSE_LENGTH = 64 * 1024; | ||
|
|
||
| private final JCasbinAuthorizer nativeAuthorizer; | ||
| private final OpaInputBuilder inputBuilder; | ||
| private final WebClient webClient; | ||
| private final String decisionUrl; | ||
|
|
||
| /** | ||
| * @param nativeAuthorizer stores native grants and hierarchy; closed with this authorizer | ||
| * @param sessionFactory supplies identity and resource metadata | ||
| * @param decisionUrl full OPA data API URL returning a boolean {@code result.allow} | ||
| * @param responseTimeout response timeout for each OPA call | ||
| */ | ||
| public OpaAuthorizer( | ||
| JCasbinAuthorizer nativeAuthorizer, | ||
| SessionFactory sessionFactory, | ||
| String decisionUrl, | ||
| Duration responseTimeout) { | ||
| this.nativeAuthorizer = nativeAuthorizer; | ||
| this.inputBuilder = new OpaInputBuilder(sessionFactory); | ||
| this.decisionUrl = decisionUrl; | ||
| this.webClient = | ||
| WebClient.builder() | ||
| .followRedirects(RedirectConfig.disabled()) | ||
| .responseTimeoutMode(ResponseTimeoutMode.FROM_START) | ||
| .responseTimeout(responseTimeout) | ||
| .maxResponseLength(MAX_RESPONSE_LENGTH) | ||
| .build(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean authorize( | ||
| UUID principal, SecurableType resourceType, UUID resource, Privileges action) { | ||
| try { | ||
| JsonNode input; | ||
| try { | ||
| input = inputBuilder.build(principal, resourceType, resource, action); | ||
| } catch (BaseException e) { | ||
| if (e.getErrorCode() != ErrorCode.NOT_FOUND) { | ||
| throw e; | ||
| } | ||
| LOGGER.warn( | ||
| "Authorization check denied: principal={}, privilege={}, resource={} {}: {}", | ||
| principal, | ||
| action, | ||
| resourceType, | ||
| resource, | ||
| e.getMessage()); | ||
| return false; | ||
| } | ||
| String request = JsonUtils.getInstance().writeValueAsString(input); | ||
| AggregatedHttpResponse response = | ||
| webClient | ||
| .prepare() | ||
| .post(decisionUrl) | ||
| .content(MediaType.JSON, request) | ||
| .execute() | ||
| .aggregate() | ||
| .join(); | ||
| if (!response.status().isSuccess()) { | ||
| throw new BaseException( | ||
| ErrorCode.UNAVAILABLE, "OPA returned HTTP " + response.status().code()); | ||
| } | ||
| JsonNode body = | ||
| JsonUtils.getInstance() | ||
| .reader() | ||
| .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) | ||
| .readTree(response.contentUtf8()); | ||
| JsonNode allow = body.path("result").path("allow"); | ||
| if (!allow.isBoolean()) { | ||
| throw new BaseException( | ||
| ErrorCode.UNAVAILABLE, "OPA response must contain a boolean result.allow"); | ||
| } | ||
| return allow.booleanValue(); | ||
| } catch (Exception e) { | ||
| throw new BaseException( | ||
| ErrorCode.UNAVAILABLE, "Could not get an authorization decision from OPA", e); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public boolean authorizeAny( | ||
| UUID principal, SecurableType resourceType, UUID resource, Privileges... actions) { | ||
| return Arrays.stream(actions) | ||
| .anyMatch(action -> authorize(principal, resourceType, resource, action)); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean authorizeAll( | ||
| UUID principal, SecurableType resourceType, UUID resource, Privileges... actions) { | ||
| return Arrays.stream(actions) | ||
| .allMatch(action -> authorize(principal, resourceType, resource, action)); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean grantAuthorization(UUID principal, UUID resource, Privileges action) { | ||
| return nativeAuthorizer.grantAuthorization(principal, resource, action); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean revokeAuthorization(UUID principal, UUID resource, Privileges action) { | ||
| return nativeAuthorizer.revokeAuthorization(principal, resource, action); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean clearAuthorizationsForPrincipal(UUID principal) { | ||
| return nativeAuthorizer.clearAuthorizationsForPrincipal(principal); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean clearAuthorizationsForResource(UUID resource) { | ||
| return nativeAuthorizer.clearAuthorizationsForResource(resource); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean addHierarchyChild(UUID parent, UUID child) { | ||
| return nativeAuthorizer.addHierarchyChild(parent, child); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean removeHierarchyChild(UUID parent, UUID child) { | ||
| return nativeAuthorizer.removeHierarchyChild(parent, child); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean removeHierarchyChildren(UUID resource) { | ||
| return nativeAuthorizer.removeHierarchyChildren(resource); | ||
| } | ||
|
|
||
| @Override | ||
| public UUID getHierarchyParent(UUID resource) { | ||
| return nativeAuthorizer.getHierarchyParent(resource); | ||
| } | ||
|
|
||
| @Override | ||
| public List<Privileges> listAuthorizations(UUID principal, UUID resource) { | ||
| return nativeAuthorizer.listAuthorizations(principal, resource); | ||
| } | ||
|
|
||
| @Override | ||
| public Map<UUID, List<Privileges>> listAuthorizations(UUID resource) { | ||
| return nativeAuthorizer.listAuthorizations(resource); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| nativeAuthorizer.close(); | ||
| } | ||
| } | ||
144 changes: 144 additions & 0 deletions
144
server/src/main/java/io/unitycatalog/server/auth/OpaInputBuilder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| package io.unitycatalog.server.auth; | ||
|
|
||
| import com.fasterxml.jackson.databind.node.ArrayNode; | ||
| import com.fasterxml.jackson.databind.node.ObjectNode; | ||
| import io.unitycatalog.server.exception.BaseException; | ||
| import io.unitycatalog.server.exception.ErrorCode; | ||
| import io.unitycatalog.server.model.SecurableType; | ||
| import io.unitycatalog.server.persist.dao.CatalogInfoDAO; | ||
| import io.unitycatalog.server.persist.dao.CredentialDAO; | ||
| import io.unitycatalog.server.persist.dao.ExternalLocationDAO; | ||
| import io.unitycatalog.server.persist.dao.FunctionInfoDAO; | ||
| import io.unitycatalog.server.persist.dao.IdentifiableDAO; | ||
| import io.unitycatalog.server.persist.dao.MetastoreDAO; | ||
| import io.unitycatalog.server.persist.dao.RegisteredModelInfoDAO; | ||
| import io.unitycatalog.server.persist.dao.SchemaInfoDAO; | ||
| import io.unitycatalog.server.persist.dao.StagingTableDAO; | ||
| import io.unitycatalog.server.persist.dao.TableInfoDAO; | ||
| import io.unitycatalog.server.persist.dao.UserDAO; | ||
| import io.unitycatalog.server.persist.dao.VolumeInfoDAO; | ||
| import io.unitycatalog.server.persist.model.Privileges; | ||
| import io.unitycatalog.server.persist.utils.TransactionManager; | ||
| import io.unitycatalog.server.utils.JsonUtils; | ||
| import java.util.UUID; | ||
| import org.hibernate.Session; | ||
| import org.hibernate.SessionFactory; | ||
|
|
||
| /** Builds OPA input from identity and resource metadata, without native grants or credentials. */ | ||
| class OpaInputBuilder { | ||
| private final SessionFactory sessionFactory; | ||
|
|
||
| OpaInputBuilder(SessionFactory sessionFactory) { | ||
| this.sessionFactory = sessionFactory; | ||
| } | ||
|
|
||
| ObjectNode build( | ||
| UUID principalId, SecurableType resourceType, UUID resourceId, Privileges privilege) { | ||
| return TransactionManager.executeWithTransaction( | ||
| sessionFactory, | ||
| session -> { | ||
| UserDAO user = required(session, UserDAO.class, principalId); | ||
| ObjectNode request = JsonUtils.getInstance().createObjectNode(); | ||
| ObjectNode input = request.putObject("input"); | ||
| ObjectNode principal = | ||
| input | ||
| .putObject("principal") | ||
| .put("id", user.getId().toString()) | ||
| .put("email", user.getEmail()); | ||
| if (user.getExternalId() != null) { | ||
| principal.put("external_id", user.getExternalId()); | ||
| } | ||
| input.put("privilege", privilege.name()); | ||
| input.set("resource", resource(session, resourceType, resourceId)); | ||
| return request; | ||
| }, | ||
| "Could not build OPA authorization input", | ||
| /* readOnly= */ true); | ||
| } | ||
|
|
||
| private ObjectNode resource(Session session, SecurableType type, UUID id) { | ||
| return switch (type) { | ||
| case METASTORE -> { | ||
| required(session, MetastoreDAO.class, id); | ||
| ObjectNode metastore = | ||
| JsonUtils.getInstance() | ||
| .createObjectNode() | ||
| .put("id", id.toString()) | ||
| .put("type", type.name()); | ||
| metastore.putArray("parents"); | ||
| yield metastore; | ||
| } | ||
| case CATALOG -> withParents(type, required(session, CatalogInfoDAO.class, id)); | ||
| case SCHEMA -> { | ||
| SchemaInfoDAO schema = required(session, SchemaInfoDAO.class, id); | ||
| yield withParents( | ||
| type, | ||
| schema, | ||
| describe( | ||
| SecurableType.CATALOG, | ||
| required(session, CatalogInfoDAO.class, schema.getCatalogId()))); | ||
| } | ||
| case TABLE -> { | ||
| TableInfoDAO table = session.get(TableInfoDAO.class, id); | ||
| if (table != null) { | ||
| yield dataResource(session, type, table, table.getSchemaId()); | ||
| } | ||
| StagingTableDAO staging = required(session, StagingTableDAO.class, id); | ||
| yield dataResource(session, type, staging, staging.getSchemaId()); | ||
| } | ||
| case VOLUME -> { | ||
| VolumeInfoDAO volume = required(session, VolumeInfoDAO.class, id); | ||
| yield dataResource(session, type, volume, volume.getSchemaId()); | ||
| } | ||
| case FUNCTION -> { | ||
| FunctionInfoDAO function = required(session, FunctionInfoDAO.class, id); | ||
| yield dataResource(session, type, function, function.getSchemaId()); | ||
| } | ||
| case REGISTERED_MODEL -> { | ||
| RegisteredModelInfoDAO model = required(session, RegisteredModelInfoDAO.class, id); | ||
| yield dataResource(session, type, model, model.getSchemaId()); | ||
| } | ||
| case EXTERNAL_LOCATION -> withParents(type, required(session, ExternalLocationDAO.class, id)); | ||
| case CREDENTIAL -> withParents(type, required(session, CredentialDAO.class, id)); | ||
| }; | ||
| } | ||
|
|
||
| private ObjectNode dataResource( | ||
| Session session, SecurableType type, IdentifiableDAO resource, UUID schemaId) { | ||
| SchemaInfoDAO schema = required(session, SchemaInfoDAO.class, schemaId); | ||
| CatalogInfoDAO catalog = required(session, CatalogInfoDAO.class, schema.getCatalogId()); | ||
| return withParents( | ||
| type, | ||
| resource, | ||
| describe(SecurableType.SCHEMA, schema), | ||
| describe(SecurableType.CATALOG, catalog)); | ||
| } | ||
|
|
||
| private ObjectNode withParents( | ||
| SecurableType type, IdentifiableDAO resource, ObjectNode... parents) { | ||
| ObjectNode result = describe(type, resource); | ||
| ArrayNode parentNodes = result.putArray("parents"); | ||
| for (ObjectNode parent : parents) { | ||
| parentNodes.add(parent); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| private ObjectNode describe(SecurableType type, IdentifiableDAO resource) { | ||
| return JsonUtils.getInstance() | ||
| .createObjectNode() | ||
| .put("id", resource.getId().toString()) | ||
| .put("type", type.name()) | ||
| .put("name", resource.getName()); | ||
| } | ||
|
|
||
| private <T> T required(Session session, Class<T> type, UUID id) { | ||
| T value = session.get(type, id); | ||
| if (value == null) { | ||
| throw new BaseException( | ||
| ErrorCode.NOT_FOUND, | ||
| "Could not resolve authorization metadata: " + type.getSimpleName() + " " + id); | ||
| } | ||
| return value; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[AI Assisted] These messages reach API clients, and #2078's tests pin them on the UC, Iceberg and Delta APIs. The OPA HTTP status and the expected response shape are server-side details. Can we log the detail and return a generic message, like the metadata-failure path already does? Same for line 84.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done, clients now get the generic message. the original details stay in the cause and get logged by the existing handler.