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
127 changes: 126 additions & 1 deletion docs/server/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,127 @@ server.audiences=<Client ID provided earlier>
export UC_SERVER_CLIENT_SECRET='<Client secret provided earlier>'
```

### List authorization

For both Casbin and OPA, permission denials and client errors (HTTP 4xx) filter out
individual items. Unexpected errors during authorization or resource resolution fail
the whole request.

### OPA authorization

Casbin is the default authorization backend. To use Open Policy Agent (OPA) for privilege
decisions, add these settings to `etc/conf/server.properties` and restart UC:

```properties
server.authorization=enable
server.authorization.provider=opa
server.authorization.opa.decision-url=http://localhost:8181/v1/data/uc/authz
server.authorization.opa.response-timeout=PT5S
```

The decision URL is the full OPA data API URL for your policy package. It must use HTTP or
HTTPS, without credentials in the URL or a fragment. Use HTTPS or a trusted local connection.
Selecting OPA requires authorization to be enabled and a decision URL; otherwise startup fails.
Authentication and UC user provisioning work as before. UC does not forward the user's token
to OPA.

UC keeps its existing authorization expressions and asks OPA about each evaluated privilege,
including `OWNER`. For example, creating a table in `analytics.reports` can require:

| Privilege | Resource |
| --- | --- |
| `USE_CATALOG` | Catalog `analytics` |
| `USE_SCHEMA` | Schema `analytics.reports` |
| `CREATE_TABLE` | Schema `analytics.reports` |
| `CREATE_EXTERNAL_TABLE` | The external location, when an external table resolves to one |

Each privilege is a separate request. UC checks the existing `OWNER` alternatives too and
short-circuits when an expression allows or denies the operation. Path resolution, overlap
validation, and staging-table creator checks remain in UC.

For the `CREATE_TABLE` check, UC sends:

```json
{
"input": {
"principal": { "id": "<UC user UUID>", "email": "[email protected]" },
"privilege": "CREATE_TABLE",
"resource": {
"id": "<schema UUID>", "type": "SCHEMA", "name": "reports",
"parents": [
{ "id": "<catalog UUID>", "type": "CATALOG", "name": "analytics" }
]
}
}
}
```

`principal.external_id` is included when provisioned on the UC user. UC has no group or role
membership to include; your policy can resolve it using your own data sources. Privileges and
resource types use uppercase enum names, such as `CREATE_TABLE` and `REGISTERED_MODEL`.
Names are local names. Parents are ordered from schema to catalog for data objects; schemas
have a catalog parent. Catalogs, external locations, credentials, and the metastore have empty
parent arrays. The metastore has no name. Staging table IDs use resource type `TABLE`.
UC sends no native grants, owner fields, or cloud credentials.

OPA must return a boolean `result.allow`:

```json
{ "result": { "allow": true } }
```

An explicit `false` follows UC's normal deny or list-filter behavior. Transport errors, timeouts,
HTTP errors, and missing or invalid decisions fail the UC request with HTTP 503. UC never falls
back to native grants. UC reuses identical checks within one expression evaluation or across list
items evaluated with the same expression. Full-access and BROWSE expressions have separate caches.
Other checks in the same request can repeat OPA calls. Decisions are not reused across requests.
The response timeout applies to each OPA call and is an ISO-8601 duration of at least 1 ms
(`PT0.001S`). UC also cancels pending OPA HTTP calls when the UC request times out or is cancelled.
A large list can still require calls for every item.

If the user, resource, or a parent is missing while building OPA input, the privilege check is
denied. Other UC metadata failures keep their UC error code, usually HTTP 500.

**Native permission APIs remain available.** Grant/revoke/list APIs still manage UC's native
records, but those grants do not affect OPA decisions. Resource creation and deletion also
maintain native owner and hierarchy records. Switching back to Casbin uses those records,
including changes made while OPA was selected. OPA's `OWNER`, `MANAGE`, and `READ_METADATA` decisions,
combined with UC's usage checks, control access to other users' native grants.

SCIM also asks OPA whether the target user has `OWNER` on the metastore before deleting or
deactivating that user. An allow decision prevents the change. Native ownership alone does not
provide this protection in OPA mode; the policy must grant metastore `OWNER` to protected users.

#### Try a policy

The example in [`etc/conf/opa-example.rego`](https://github.com/unitycatalog/unitycatalog/blob/main/etc/conf/opa-example.rego)
allows the local bootstrap account (`admin`) and looks up other privileges in OPA's own
`data.grants`. Replace this example with your policy for deployment.

From the repository root, start OPA 1.x:

```sh
opa run --server --addr=127.0.0.1:8181 etc/conf/opa-example.rego
```

In another terminal, add grants directly to OPA. Replace the UUID placeholders with the UC
catalog and schema IDs:

```sh
curl -X PUT http://localhost:8181/v1/data/grants \
-H 'Content-Type: application/json' \
-d '[
{"principal":"[email protected]","privilege":"USE_CATALOG","type":"CATALOG","id":"<catalog UUID>"},
{"principal":"[email protected]","privilege":"USE_SCHEMA","type":"SCHEMA","id":"<schema UUID>"},
{"principal":"[email protected]","privilege":"CREATE_TABLE","type":"SCHEMA","id":"<schema UUID>"}
]'
```

With Alice provisioned in UC, these grants let her create tables in that schema. An external
table under a registered external location also needs `CREATE_EXTERNAL_TABLE` on that location.
The example grants no table read or ownership privileges to Alice; add those to your OPA policy
as needed. OPA policy and data administration is separate from UC's grant APIs.

### Issuer and Audience Validation

When authorization is enabled, the server validates incoming identity tokens against configured issuers and audiences:
Expand Down Expand Up @@ -164,7 +285,8 @@ where you run `bin/uc auth login`; the server does not read it. The file still w

`server.authorization.strict-privilege-checks` is a temporary migration setting. It defaults to
`true` and will be removed in a future release. Permission fixes that use this setting apply the
corrected rules by default.
corrected rules by default. With OPA, this setting also changes which privileges UC asks OPA
to authorize.

The setting covers:

Expand Down Expand Up @@ -195,6 +317,9 @@ Use the same value on every server instance. Restart each instance after changin

### Multiple server instances

This section applies to Casbin. With OPA, `server.authorization.policy-refresh` does not change
authorization decisions.

Authorization decisions use an in-memory Casbin policy loaded from the shared `casbin_rule` table.
A grant or revoke written on one server process is not visible to other processes until they reload
that table.
Expand Down
19 changes: 19 additions & 0 deletions etc/conf/opa-example.rego
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Example for local testing with OPA 1.x.
# The admin rule allows all privileges. Replace it before deployment.

package uc.authz

import rego.v1

default allow := false

# The local bootstrap account needs an OPA policy too.
allow if input.principal.email == "admin"

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: this rule grants everything to any principal whose email is admin. The docs say to replace it, but the file does not say so. Add a header saying this is for local trials, needs OPA 1.x, and the admin rule must be replaced before deployment.

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.

added a header saying this is for local testing with OPA 1.x. it also states that the admin rule allows everything and must be replaced before deployment.


allow if {
some grant in data.grants
grant.principal == input.principal.email
grant.privilege == input.privilege
grant.type == input.resource.type
grant.id == input.resource.id
}
13 changes: 11 additions & 2 deletions etc/conf/server.properties
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ server.client-id=
server.client-secret=
server.redirect-port=

# Privilege decisions use Casbin by default. OPA requires server.authorization=enable.
# Native grant/revoke/list APIs remain available, but their grants do not affect OPA decisions.
# server.authorization.provider=casbin
# server.authorization.opa.decision-url=http://localhost:8181/v1/data/uc/authz
# Response timeout for each OPA call, not for the complete UC request.
# ISO-8601 duration, at least PT0.001S (1 ms).
# server.authorization.opa.response-timeout=PT5S

# Permission-check migration. Stricter checks are on by default.
# Set false temporarily to keep the previous rules, including access those rules allowed.
# Use the same setting on every server instance and restart after changing it.
Expand Down Expand Up @@ -55,8 +63,9 @@ server.access-token-timeout=PT24H
# server.shutdown-timeout=PT5S

# Authorization policy refresh across server instances that share one database.
# Required for any multi-instance / HA deployment: each instance keeps Casbin
# policy in memory, and without refresh, grants/revokes made through another
# Applies to Casbin decisions only; OPA decisions are unaffected.
# Required for any multi-instance / HA deployment that uses Casbin: each instance
# keeps policy in memory, and without refresh, grants/revokes made through another
# instance are invisible until restart. See docs/server/auth.md.
#
# server.authorization.policy-refresh=false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import io.unitycatalog.server.audit.Auditor;
import io.unitycatalog.server.auth.AllowingAuthorizer;
import io.unitycatalog.server.auth.JCasbinAuthorizer;
import io.unitycatalog.server.auth.OpaAuthorizer;
import io.unitycatalog.server.auth.UnityCatalogAuthorizer;
import io.unitycatalog.server.auth.decorator.UnityAccessDecorator;
import io.unitycatalog.server.auth.decorator.UnityAccessUtil;
Expand Down Expand Up @@ -109,6 +110,7 @@ public class UnityCatalogServer implements AutoCloseable {

private UnityCatalogServer(UnityCatalogServer.Builder unityCatalogServerBuilder) {
setDefaults(unityCatalogServerBuilder);
unityCatalogServerBuilder.serverProperties.validateProperties();
this.shutdownTimeout = unityCatalogServerBuilder.serverProperties.getShutdownTimeout();
Path configurationFolder = Path.of("etc", "conf");
SecurityConfiguration securityConfiguration = new SecurityConfiguration(configurationFolder);
Expand Down Expand Up @@ -345,8 +347,20 @@ private UnityCatalogAuthorizer initializeAuthorizer(
JCasbinAuthorizer authorizer =
new JCasbinAuthorizer(hibernateConfigurator, serverProperties);
try {
UnityCatalogAuthorizer backend;
if (serverProperties.isOpaAuthorizationEnabled()) {
LOGGER.info("Using OPA for authorization decisions.");
backend =
new OpaAuthorizer(
authorizer,
hibernateConfigurator.getSessionFactory(),
serverProperties.getOpaDecisionUrl(),
serverProperties.getOpaResponseTimeout());
} else {
backend = authorizer;
}
UnityCatalogAuthorizer effective =
Optional.ofNullable(auditor).map(a -> a.wrap(authorizer)).orElse(authorizer);
Optional.ofNullable(auditor).map(a -> a.wrap(backend)).orElse(backend);
new UnityAccessUtil(repositories).initializeAdmin(effective);
return effective;
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.linecorp.armeria.client.ClientRequestContext;
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 com.linecorp.armeria.server.ServiceRequestContext;
import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.model.SecurableType;
Expand All @@ -17,6 +19,7 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -53,30 +56,49 @@ public OpaAuthorizer(
.followRedirects(RedirectConfig.disabled())
.responseTimeoutMode(ResponseTimeoutMode.FROM_START)
.responseTimeout(responseTimeout)
.contextCustomizer(
ctx -> {
ServiceRequestContext root = ctx.root();
if (root != null) {
// Successful UC requests never complete the cancellation future.
AtomicReference<ClientRequestContext> pending = new AtomicReference<>(ctx);
root.whenRequestCancelling()
.thenAccept(
cause -> {
ClientRequestContext call = pending.getAndSet(null);
if (call != null) {
call.cancel(cause);
}
});
ctx.log().whenComplete().thenAccept(unused -> pending.set(null));
}
})
.maxResponseLength(MAX_RESPONSE_LENGTH)
.build();
}

@Override
public boolean authorize(
UUID principal, SecurableType resourceType, UUID resource, Privileges action) {
JsonNode input;
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;
input = inputBuilder.build(principal, resourceType, resource, action);
} catch (RuntimeException e) {
ErrorCode code =
e instanceof BaseException failure ? failure.getErrorCode() : ErrorCode.INTERNAL;
if (code != ErrorCode.NOT_FOUND) {
throw new BaseException(code, "Could not build OPA authorization input", e);
}
LOGGER.warn(
"Authorization check denied: principal={}, privilege={}, resource={} {}: {}",
principal,
action,
resourceType,
resource,
e.getMessage());
return false;
}
try {
String request = JsonUtils.getInstance().writeValueAsString(input);
AggregatedHttpResponse response =
webClient
Expand All @@ -101,6 +123,8 @@ public boolean authorize(
ErrorCode.UNAVAILABLE, "OPA response must contain a boolean result.allow");
}
return allow.booleanValue();
} catch (BaseException e) {
throw e;
} catch (Exception e) {
throw new BaseException(
ErrorCode.UNAVAILABLE, "Could not get an authorization decision from OPA", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.function.UnaryOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.spel.SpelEvaluationException;

/**
* Filters GET and LIST responses based on user authorization permissions.
Expand Down Expand Up @@ -106,8 +107,8 @@ public ResultFilter(
* <li>Removes the item if the expression evaluates to false
* </ol>
*
* <p>If an error occurs during authorization evaluation for an item, that item is filtered out
* (removed from the list) as a security precaution.
* <p>Explicit denials and 4xx {@link BaseException}s filter out the item. Unexpected errors fail
* the request so a failed authorization check cannot look like a successful list.
*
* @param securableType The type of resources being filtered (TABLE, VOLUME, FUNCTION, etc.)
* @param items The list of items to filter in-place. This list is modified by removing
Expand Down Expand Up @@ -157,6 +158,14 @@ public <T> void filter(SecurableType securableType, List<T> items, UnaryOperator
iterator.set(result);
}
} catch (Exception e) {

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 future-proofing, since the list path is covered today: this catch rethrows any 5xx BaseException unchanged, so the model-only masking in resolveResourceIdsForItem depends on each source sanitizing its own message. Would it work to mask INTERNAL here once for all list paths, and keep the specific UNAVAILABLE messages from OPA? That would also let us drop the per-call rewrap.

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.

i’d leave the broader masking for a follow-up. the current metadata lookup failure is already masked and tested, so i’m keeping the existing handling here.

// SpEL wraps client errors from privilege checks.
Throwable failure = e instanceof SpelEvaluationException ? e.getCause() : e;
if (!(failure instanceof BaseException baseException)) {
throw new BaseException(ErrorCode.INTERNAL, "Failed to authorize list items", e);
}
if (!baseException.getErrorCode().getHttpStatus().isClientError()) {
throw baseException;
}
LOGGER.warn("Error evaluating authorization for item, filtering out: {}", e.getMessage());
iterator.remove();
}
Expand Down Expand Up @@ -211,9 +220,13 @@ private Map<SecurableType, UUID> resolveResourceIdsForItem(
&& !preResolvedIds.containsKey(CATALOG)
&& !preResolvedIds.containsKey(SCHEMA)) {
RegisteredModelInfo model = (RegisteredModelInfo) item;
combined.putAll(
keyMapper.mapResourceKeys(
Map.of(CATALOG, model.getCatalogName(), SCHEMA, model.getSchemaName())));
try {
combined.putAll(
keyMapper.mapResourceKeys(
Map.of(CATALOG, model.getCatalogName(), SCHEMA, model.getSchemaName())));
} catch (BaseException e) {
throw new BaseException(e.getErrorCode(), "Failed to authorize list items", e);
}
}
// For everything else, the catalog and schema IDs are already included in preResolvedIds
// if needed.
Expand Down
Loading
Loading