Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions server/src/main/java/io/unitycatalog/server/auth/OpaAuthorizer.java
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());

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] 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.

Copy link
Copy Markdown
Collaborator Author

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.

}
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();
}
}
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;
}
}
Loading
Loading