adutra commented on code in PR #2680:
URL: https://github.com/apache/polaris/pull/2680#discussion_r2380127562


##########
polaris-core/src/main/java/org/apache/polaris/core/auth/OpaPolarisAuthorizer.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.polaris.core.auth;
+
+// Removed Quarkus/MicroProfile annotations for portability
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import jakarta.annotation.Nonnull;
+import jakarta.annotation.Nullable;
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+import okhttp3.MediaType;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+import org.apache.iceberg.exceptions.ForbiddenException;
+import org.apache.polaris.core.entity.PolarisBaseEntity;
+import org.apache.polaris.core.persistence.PolarisResolvedPathWrapper;
+
+/**
+ * OPA-based implementation of {@link PolarisAuthorizer}.
+ *
+ * <p>This authorizer delegates authorization decisions to an Open Policy 
Agent (OPA) server using a
+ * configurable REST API endpoint and policy path. The input to OPA is 
constructed from the
+ * principal, entities, operation, and resource context.
+ */
+public class OpaPolarisAuthorizer implements PolarisAuthorizer {
+  private final String opaServerUrl;
+  private final String opaPolicyPath;
+  private final OkHttpClient httpClient;
+  private final ObjectMapper objectMapper;
+
+  /** Private constructor for factory method and advanced wiring. */
+  private OpaPolarisAuthorizer(
+      String opaServerUrl,
+      String opaPolicyPath,
+      OkHttpClient httpClient,
+      ObjectMapper objectMapper) {
+    this.opaServerUrl = opaServerUrl;
+    this.opaPolicyPath = opaPolicyPath;
+    this.httpClient = httpClient;
+    this.objectMapper = objectMapper;
+  }
+
+  /**
+   * Static factory for runtime configuration and CDI producer compatibility.
+   *
+   * @param opaServerUrl OPA server URL
+   * @param opaPolicyPath OPA policy path
+   * @param timeoutMs HTTP call timeout in milliseconds
+   * @param client OkHttpClient (optional, can be null)
+   * @param mapper ObjectMapper (optional, can be null)
+   * @return OpaPolarisAuthorizer instance
+   */
+  public static OpaPolarisAuthorizer create(
+      String opaServerUrl,
+      String opaPolicyPath,
+      int timeoutMs,
+      OkHttpClient client,
+      ObjectMapper mapper) {
+    OkHttpClient clientWithTimeout =
+        (client != null)
+            ? 
client.newBuilder().callTimeout(java.time.Duration.ofMillis(timeoutMs)).build()
+            : new OkHttpClient.Builder()
+                .callTimeout(java.time.Duration.ofMillis(timeoutMs))
+                .build();
+    ObjectMapper objectMapper = (mapper != null) ? mapper : new ObjectMapper();
+    return new OpaPolarisAuthorizer(opaServerUrl, opaPolicyPath, 
clientWithTimeout, objectMapper);
+  }
+
+  /**
+   * Authorizes a single target and secondary entity for the given principal 
and operation.
+   *
+   * <p>Delegates to the multi-target version for consistency.
+   *
+   * @param polarisPrincipal the principal requesting authorization
+   * @param activatedEntities the set of activated entities (roles, etc.)
+   * @param authzOp the operation to authorize
+   * @param target the main target entity
+   * @param secondary the secondary entity (if any)
+   * @throws ForbiddenException if authorization is denied by OPA
+   */
+  @Override
+  public void authorizeOrThrow(
+      @Nonnull PolarisPrincipal polarisPrincipal,
+      @Nonnull Set<PolarisBaseEntity> activatedEntities,
+      @Nonnull PolarisAuthorizableOperation authzOp,
+      @Nullable PolarisResolvedPathWrapper target,
+      @Nullable PolarisResolvedPathWrapper secondary) {
+    authorizeOrThrow(
+        polarisPrincipal,
+        activatedEntities,
+        authzOp,
+        target == null ? null : List.of(target),
+        secondary == null ? null : List.of(secondary));
+  }
+
+  /**
+   * Authorizes one or more target and secondary entities for the given 
principal and operation.
+   *
+   * <p>Sends the authorization context to OPA and throws if not allowed.
+   *
+   * @param polarisPrincipal the principal requesting authorization
+   * @param activatedEntities the set of activated entities (roles, etc.)
+   * @param authzOp the operation to authorize
+   * @param targets the list of main target entities
+   * @param secondaries the list of secondary entities (if any)
+   * @throws ForbiddenException if authorization is denied by OPA
+   */
+  @Override
+  public void authorizeOrThrow(
+      @Nonnull PolarisPrincipal polarisPrincipal,
+      @Nonnull Set<PolarisBaseEntity> activatedEntities,
+      @Nonnull PolarisAuthorizableOperation authzOp,
+      @Nullable List<PolarisResolvedPathWrapper> targets,
+      @Nullable List<PolarisResolvedPathWrapper> secondaries) {
+    boolean allowed = queryOpa(polarisPrincipal, activatedEntities, authzOp, 
targets, secondaries);
+    if (!allowed) {
+      throw new ForbiddenException("OPA denied authorization");
+    }
+  }
+
+  /**
+   * Sends an authorization query to the OPA server and parses the response.
+   *
+   * <p>Builds the OPA input JSON, sends it via HTTP POST, and checks the 
'allow' field in the
+   * response.
+   *
+   * @param principal the principal requesting authorization
+   * @param entities the set of activated entities
+   * @param op the operation to authorize
+   * @param targets the list of main target entities
+   * @param secondaries the list of secondary entities (if any)
+   * @return true if OPA allows the operation, false otherwise
+   * @throws RuntimeException if the OPA query fails
+   */
+  private boolean queryOpa(
+      PolarisPrincipal principal,
+      Set<PolarisBaseEntity> entities,
+      PolarisAuthorizableOperation op,
+      List<PolarisResolvedPathWrapper> targets,
+      List<PolarisResolvedPathWrapper> secondaries) {
+    try {
+      String inputJson = buildOpaInputJson(principal, entities, op, targets, 
secondaries);
+      RequestBody body = RequestBody.create(inputJson, 
MediaType.parse("application/json"));
+      Request request = new Request.Builder().url(opaServerUrl + 
opaPolicyPath).post(body).build();
+      try (Response response = httpClient.newCall(request).execute()) {
+        if (!response.isSuccessful()) return false;
+        // Parse response JSON for 'result.allow'
+        ObjectNode respNode = (ObjectNode) 
objectMapper.readTree(response.body().string());
+        return respNode.path("result").path("allow").asBoolean(false);
+      }
+    } catch (IOException e) {
+      throw new RuntimeException("OPA query failed", e);
+    }
+  }
+
+  /**
+   * Builds the OPA input JSON for the authorization query.
+   *
+   * <p>Assembles the actor, action, resource, and context sections into the 
expected OPA input
+   * format.
+   *
+   * @param principal the principal requesting authorization
+   * @param entities the set of activated entities
+   * @param op the operation to authorize
+   * @param targets the list of main target entities
+   * @param secondaries the list of secondary entities (if any)
+   * @return the OPA input JSON string
+   * @throws IOException if JSON serialization fails
+   */
+  private String buildOpaInputJson(
+      PolarisPrincipal principal,
+      Set<PolarisBaseEntity> entities,
+      PolarisAuthorizableOperation op,
+      List<PolarisResolvedPathWrapper> targets,
+      List<PolarisResolvedPathWrapper> secondaries)
+      throws IOException {
+    ObjectNode input = objectMapper.createObjectNode();

Review Comment:
   > There's role in `PolarisPrincipal`, as well as the `activatedEntities` and 
I couldn't figure out easily which one I should pass over into OPA.
   
   I think I can provide some explanations. 
   
   The roles in `PolarisPrincipal` are principal roles resolved by the 
`Authenticator`. Today, any principal role in the access token will appear 
there, but it will be checked against the database. Therefore principal roles 
must have been created beforehand, using the Polaris management API, if you 
want to make use of them. Even if you are using an external IDP, you still need 
to create the principal roles beforehand, and that is one of the pain points 
today.
   
   Furthermore, the access token controls which principal roles should be 
"activated". "Activate a role" means that the role is considered for 
authorization decisions for the current request; if the role is not active (not 
present in the token), it won't be considered. This allows access tokens to 
contain a subset of the roles the principal was granted. 
   
   As for `activatedEntities`, it is a bit of a cryptic name, I confess. This 
parameter contains a mix of principal roles and catalog roles that the 
authenticated principal has been granted. This parameter is populated by the 
`Resolver`. The principal roles are the same ones that you get from the 
`PolarisPrincipal` (but the `Resolver` re-fetches them from the database 
unfortunately). The catalog roles, if any, are populated by the `Resolver` as 
well.
   
   Finally, the `Resolver` also validates all involved "paths", that is, 
references to resources such as tables and views that are being affected by the 
request.
   
   Then, once the `Resolver` has finished resolving roles and validating 
"paths", the `PolarisAuthorizer` is invoked with these fundamental elements:
   
   1. The principal
   2. The principal roles and catalog roles (in `activatedEntities`)
   3. The resources or "paths" affected by the operation
   4. The operation to authorize
   
   > I couldn't figure out easily which one I should pass over into OPA.
   
   I would say that:
   
   1. For principal roles, you probably need to send those to OPA, as they 
indicate group membership – unless OPA can figure this out by simply searching 
the principal name.
   2. For catalog roles however, it probably doesn't make sense to manage them 
in Polaris since you are already managing access control externally. I would 
expect OPA users to never create any catalog role at all. So it doesn't make 
sense to include those either in the request to OPA.
   
   Sorry for the wall of text 😅 
   
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to