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
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,10 @@ private AuthorizeExpressions() {}
* needs {@code OWNER}/{@code CREATE_EXTERNAL_TABLE} on the external location (if one resolves)
* and the storage path must not overlap a data securable.
*
* <p>The {@code #table_type} SpEL variable comes from {@code @AuthorizeKey(key = "table-type")};
* kebab-case payload keys surface with hyphens mapped to underscores (see {@link
* io.unitycatalog.server.auth.decorator.AuthorizeKeyLocator#getVariableName}).
* <p>The {@code #table_type} SpEL variable is {@code 'MANAGED'} or {@code 'EXTERNAL'}, supplied
* by the calling endpoint: a payload field for Delta ({@code @AuthorizeKey(key = "table-type")}),
* or a value derived by the Iceberg {@code *TableTypeExtractor} for the REST create and
* staged-commit paths.
*/
public static final String CREATE_TABLE =
"""
Expand All @@ -139,23 +140,6 @@ private AuthorizeExpressions() {}
#authorizeAny(#principal, #external_location, OWNER, CREATE_EXTERNAL_TABLE))))
""";

/**
* Iceberg {@code createTable} policy: same as {@link #CREATE_TABLE}, but discriminates MANAGED vs
* EXTERNAL on the request's {@code location} (Iceberg has no table_type). Keying on location (not
* the resolved external location) keeps the no-overlap guard running when a path resolves to no
* external location.
*/
public static final String CREATE_ICEBERG_TABLE =
"""
#authorizeAny(#principal, #catalog, OWNER, USE_CATALOG) &&
(#authorize(#principal, #schema, OWNER) ||
#authorizeAll(#principal, #schema, USE_SCHEMA, CREATE_TABLE)) &&
(#location == null ||
(#no_overlap_with_data_securable &&
(#external_location == null ||
#authorizeAny(#principal, #external_location, OWNER, CREATE_EXTERNAL_TABLE))))
""";

/**
* Authorization policy for updating / committing to a table (UC REST {@code
* DeltaCommitsService.postCommit} and the Delta {@code updateTable}). The Delta {@code POST
Expand All @@ -173,6 +157,17 @@ private AuthorizeExpressions() {}
#authorizeAll(#principal, #table, SELECT, MODIFY))
""";

/**
* Iceberg {@code updateTable} ({@code POST /tables/{table}}) policy for this dual-purpose
* endpoint: a staged-create commit ({@code #staged_create}, an {@code assert-create} requirement)
* is authorized exactly as {@link #CREATE_TABLE}; any other commit as {@link #UPDATE_TABLE}. The
* handler binds the {@code TABLE} resource key with {@code skipWhen = "staged_create"}, so it is
* not resolved for a staged create (no table row exists yet) and the two branches key on {@code
* #table} or not without one shape's resolution failing the other.
*/
public static final String UPDATE_ICEBERG_TABLE =
"#staged_create ? (" + CREATE_TABLE + ") : (" + UPDATE_TABLE + ")";

/**
* Authorization policy for deleting a table, shared by the UC REST, UC Delta API, and Iceberg
* REST delete endpoints. Metastore admin alone is intentionally not sufficient -- the caller must
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package io.unitycatalog.server.auth.annotation;

import io.unitycatalog.server.auth.decorator.AuthorizeValueExtractor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
Expand Down Expand Up @@ -61,13 +63,25 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Repeatable(AuthorizeKeys.class)
public @interface AuthorizeKey {
/**
* The key path to extract from the request. When the annotated parameter also carries
* {@code @Param}, leave this empty (the default) to reuse the {@code @Param} value as both the
* URL parameter name and the SpEL variable name; if set, it must equal the {@code @Param} value.
* When there is no {@code @Param}, this names a request body field; nested fields via dot
* notation (e.g., "config.operation") are supported for the body source.
*
* <p>When {@link #extractor} is set, this instead only names the SpEL variable (the value comes
* from the extractor, not a field lookup), and is required.
*/
String key() default "";

/**
* A custom extractor that computes the value from the bound request body, used when a field
* lookup by {@link #key} cannot express it. When set (non-default), {@link #key} names the SpEL
* variable and no {@code @Param} may be present. Defaults to the sentinel {@link
* AuthorizeValueExtractor} itself, meaning "no extractor: use {@link #key}".
*/
Class<? extends AuthorizeValueExtractor> extractor() default AuthorizeValueExtractor.class;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package io.unitycatalog.server.auth.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Container for repeated {@link AuthorizeKey} annotations on a single parameter, so one payload
* parameter can expose more than one SpEL variable (e.g. a table type and a staged-create flag).
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface AuthorizeKeys {
AuthorizeKey[] value();
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.unitycatalog.server.auth.annotation;

import io.unitycatalog.server.auth.decorator.AuthorizeValueExtractor;
import io.unitycatalog.server.model.SecurableType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
Expand Down Expand Up @@ -61,4 +62,24 @@
SecurableType value();

String key() default "";

/**
* A custom extractor that computes the resource key from the bound request body, used when a
* field lookup by {@link #key} cannot express it (e.g. the value depends on the contents of a
* list). When set (non-default), {@link #key} is unused (the variable name comes from {@link
* #value}) and no {@code @Param} may be present. Defaults to the sentinel {@link
* AuthorizeValueExtractor} itself, meaning "no extractor: use {@link #key}".
*/
Class<? extends AuthorizeValueExtractor> extractor() default AuthorizeValueExtractor.class;

/**
* Names a non-resource SpEL variable (an {@code @AuthorizeKey}); when it evaluates truthy this
* resource key is skipped: not resolved to an id, and absent from the expression context. Used
* for a dual-purpose endpoint where a resource applies to only one request shape (e.g. the
* Iceberg {@code updateTable} {@code TABLE} key is skipped for a staged-create commit, where no
* table row exists yet). Because the deciding variable may come from the body, the skip is
* applied after request values are gathered and before ids are resolved. Empty (the default)
* means always resolve.
*/
String skipWhen() default "";
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.unitycatalog.server.auth.annotation.AuthorizeResourceKey;
import io.unitycatalog.server.model.SecurableType;
import java.lang.reflect.Parameter;
import java.util.Map;
import java.util.Optional;
import lombok.Builder;
import lombok.Getter;
Expand Down Expand Up @@ -40,6 +41,13 @@ public enum Source {
private Source source;
private String key;

// Custom value extractor, or null to look the value up by key. Only set on PAYLOAD locators.
private AuthorizeValueExtractor extractor;

// For a resource key, the name of a non-resource variable that, when truthy, skips resolving this
// key. Null/empty means always resolve. See AuthorizeResourceKey#skipWhen.
private String skipWhen;

/**
* Extracts the variable name from a key. For resources, returns their securable type as variable
* name. e.g. "external_location" For other keys, returns the key name in annotated parameters or
Expand All @@ -59,17 +67,83 @@ public String getVariableName() {
return name.replace('-', '_');
}

/**
* Finds this locator's value from the request body. The caller supplies the body in the two forms
* the locator may need: {@code body} is the typed object the handler bound, and {@code bodyMap}
* is that same object as a JSON map. An {@link #extractor} reads {@code body}; a {@link #key}
* lookup walks {@code bodyMap}. Only valid for PAYLOAD locators.
*
* @param body the request body as its bound model object (the argument the handler receives, e.g.
* an {@code UpdateTableRequest}); read by the {@link #extractor} when one is set.
* @param bodyMap the same body re-serialized once to a nested {@code Map<String, Object>} (its
* JSON tree, keyed by wire names via the mapper's naming strategy / {@code @JsonProperty});
* walked by the {@link #key} lookup. May be null when this locator uses an extractor.
* @return the located value, or null when the key is absent from {@code bodyMap}.
*/
public Object findPayloadValue(Object body, Map<String, Object> bodyMap) {
if (extractor != null) {
return extractor.extract(body);
}
return findNestedValue(key, bodyMap);
}

private static Object findNestedValue(String key, Map<String, Object> map) {
// TODO: investigate better object traversal functionality
String[] args = key.split("[.]", 2);
if (args.length == 1) {
return map.get(args[0]);
}
if (map.get(args[0]) instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> value = (Map<String, Object>) map.get(args[0]);
return findNestedValue(args[1], value);
}
return null;
}

public static AuthorizeKeyLocator from(AuthorizeResourceKey key, Parameter parameter) {
return from(Optional.of(key.value()), key.key(), parameter);
return from(
Optional.of(key.value()),
key.key(),
extractorOf(key.extractor()),
key.skipWhen(),
parameter);
}

public static AuthorizeKeyLocator from(AuthorizeKey key, Parameter parameter) {
return from(Optional.empty(), key.key(), parameter);
return from(Optional.empty(), key.key(), extractorOf(key.extractor()), "", parameter);
}

private static AuthorizeKeyLocator from(
Optional<SecurableType> type, String key, Parameter parameter) {
Optional<SecurableType> type,
String key,
AuthorizeValueExtractor extractor,
String skipWhen,
Parameter parameter) {
Param param = parameter.getAnnotation(Param.class);
if (extractor != null) {
// A custom extractor reads the value from the bound body, so the source is PAYLOAD (deferred
// to the gate converter) and no @Param may be present. A resource key takes its variable name
// from its securable type; a raw AuthorizeKey still needs a key to name its SpEL variable.
if (param != null) {
throw new IllegalStateException(
"Authorization extractor on parameter "
+ parameter.getName()
+ " cannot be combined with @Param");
}
if (type.isEmpty() && key.isEmpty()) {
throw new IllegalStateException(
"@AuthorizeKey with an extractor must set key to name its SpEL variable: "
+ parameter.getName());
}
return AuthorizeKeyLocator.builder()
.source(Source.PAYLOAD)
.type(type)
.key(key)
.extractor(extractor)
.skipWhen(skipWhen)
.build();
}
if (param != null) {
// @Param bound: source is the URL query/path. If a key is explicitly set it must equal
// @Param.value() so the SpEL variable name and URL parameter name agree; leaving it empty
Expand All @@ -88,13 +162,36 @@ private static AuthorizeKeyLocator from(
.source(Source.PARAM)
.type(type)
.key(param.value())
.skipWhen(skipWhen)
.build();
}
// No @Param: the key names a request body field.
if (key.isEmpty()) {
throw new RuntimeException(
"Couldn't find param key for authorization key: " + parameter.getName());
}
return AuthorizeKeyLocator.builder().source(Source.PAYLOAD).type(type).key(key).build();
return AuthorizeKeyLocator.builder()
.source(Source.PAYLOAD)
.type(type)
.key(key)
.skipWhen(skipWhen)
.build();
}

/**
* Instantiates the annotation's extractor class, or returns null for the sentinel default ({@link
* AuthorizeValueExtractor} itself) that means "no custom extractor".
*/
private static AuthorizeValueExtractor extractorOf(
Class<? extends AuthorizeValueExtractor> extractorClass) {
if (extractorClass == AuthorizeValueExtractor.class) {
return null;
}
try {
return extractorClass.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"Cannot instantiate authorization value extractor " + extractorClass.getName(), e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.unitycatalog.server.auth.decorator;

/**
* Computes an authorization value from an already-bound request body, for cases where a plain field
* lookup cannot express it (e.g. the value depends on the contents of a list). Named on {@link
* io.unitycatalog.server.auth.annotation.AuthorizeKey} or {@link
* io.unitycatalog.server.auth.annotation.AuthorizeResourceKey} in place of a {@code key}, and
* invoked by {@link AuthorizeKeyLocator}.
*
* <p>Implementations must be stateless and expose a public no-arg constructor; one instance is
* created per annotation.
*
* <p>The return type depends on which annotation the extractor is on:
*
* <ul>
* <li>On {@code @AuthorizeResourceKey}, the value is mapped to a resource id by {@code
* KeyMapper}, so it must be a {@code String} (a name, full name, or storage path), a {@code
* UUID}, or {@code null} ({@code null} means "not set" and is skipped).
* <li>On {@code @AuthorizeKey}, the value is exposed directly as a SpEL variable, so its type
* only has to match how the expression uses it (e.g. a {@code Boolean} for a ternary
* condition, a {@code String} for an {@code == '...'} comparison). Enums are surfaced as
* their {@code toString()}; any other type is passed through as-is.
* </ul>
*/
public interface AuthorizeValueExtractor {

/**
* @param body the bound request body (the exact object the handler receives); never null.
* @return the value to expose (a resource key to map, or a raw SpEL variable), or null. See the
* type contract on the interface.
*/
Object extract(Object body);
}
Loading
Loading