jbonofre commented on code in PR #2680: URL: https://github.com/apache/polaris/pull/2680#discussion_r2422934586
########## extensions/auth/opa/src/main/java/org/apache/polaris/extension/auth/opa/OpaHttpClientFactory.java: ########## @@ -0,0 +1,131 @@ +/* + * 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.extension.auth.opa; + +import com.google.common.base.Strings; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import javax.net.ssl.SSLContext; +import org.apache.hc.client5.http.config.RequestConfig; Review Comment: Just curious: do you prefer to use Apache HTTPc instead of the HTTP client provided by the JDK ? ########## extensions/auth/opa/src/main/java/org/apache/polaris/extension/auth/opa/OpaPolarisAuthorizer.java: ########## @@ -0,0 +1,407 @@ +/* + * 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.FileInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import javax.net.ssl.SSLContext; +import org.apache.http.HttpHeaders; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustAllStrategy; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.util.EntityUtils; +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 TokenProvider tokenProvider; + private final CloseableHttpClient httpClient; + private final ObjectMapper objectMapper; + + /** Private constructor for factory method and advanced wiring. */ + private OpaPolarisAuthorizer( + String opaServerUrl, + String opaPolicyPath, + TokenProvider tokenProvider, + CloseableHttpClient httpClient, + ObjectMapper objectMapper) { + this.opaServerUrl = opaServerUrl; + this.opaPolicyPath = opaPolicyPath; + this.tokenProvider = tokenProvider; + this.httpClient = httpClient; + this.objectMapper = objectMapper; + } + + /** + * Static factory that accepts a TokenProvider for advanced token management. + * + * @param opaServerUrl OPA server URL + * @param opaPolicyPath OPA policy path + * @param tokenProvider Token provider for authentication (optional) + * @param timeoutMs HTTP call timeout in milliseconds + * @param verifySsl Whether to verify SSL certificates for HTTPS connections + * @param trustStorePath Custom SSL trust store path (optional) + * @param trustStorePassword Custom SSL trust store password (optional) + * @param client Apache HttpClient (optional, can be null) + * @param mapper ObjectMapper (optional, can be null) + * @return OpaPolarisAuthorizer instance + */ + public static OpaPolarisAuthorizer create( + String opaServerUrl, + String opaPolicyPath, + TokenProvider tokenProvider, + int timeoutMs, + boolean verifySsl, + String trustStorePath, + String trustStorePassword, + Object client, // Accept any client type for compatibility + ObjectMapper mapper) { + + try { + // Create request configuration with timeouts + RequestConfig requestConfig = + RequestConfig.custom() + .setConnectTimeout(timeoutMs) + .setSocketTimeout(timeoutMs) + .setConnectionRequestTimeout(timeoutMs) + .build(); + + // Configure SSL for HTTPS connections + SSLConnectionSocketFactory sslSocketFactory = + createSslSocketFactory(opaServerUrl, verifySsl, trustStorePath, trustStorePassword); + + // Create HTTP client with SSL configuration + CloseableHttpClient httpClient; + if (client instanceof CloseableHttpClient) { + httpClient = (CloseableHttpClient) client; + } else { + if (sslSocketFactory != null) { + httpClient = + HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .setSSLSocketFactory(sslSocketFactory) + .build(); + } else { + httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); + } + } + + ObjectMapper objectMapperWithDefaults = mapper != null ? mapper : new ObjectMapper(); + return new OpaPolarisAuthorizer( + opaServerUrl, opaPolicyPath, tokenProvider, httpClient, objectMapperWithDefaults); + } catch (Exception e) { + throw new RuntimeException("Failed to create OpaPolarisAuthorizer with SSL configuration", e); + } + } + + /** + * 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); + + // Create HTTP POST request using Apache HttpComponents + HttpPost httpPost = new HttpPost(opaServerUrl + opaPolicyPath); + httpPost.setHeader("Content-Type", "application/json"); + + // Add bearer token authentication if provided + if (tokenProvider != null) { + String token = tokenProvider.getToken(); + if (token != null && !token.isEmpty()) { + httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); + } + } + + httpPost.setEntity(new StringEntity(inputJson, StandardCharsets.UTF_8)); + + // Execute request + try (CloseableHttpResponse response = httpClient.execute(httpPost)) { + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + return false; + } + + // Read and parse response + String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + ObjectNode respNode = (ObjectNode) objectMapper.readTree(responseBody); + 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(); + input.set("actor", buildActorNode(principal)); + input.put("action", op.name()); + input.set("resource", buildResourceNode(targets, secondaries)); + input.set("context", buildContextNode()); + ObjectNode root = objectMapper.createObjectNode(); + root.set("input", input); Review Comment: Yes, I agree that it would be "simpler/cleaner" to create beans (eventually usign Jackson annotations) to generate the JSON input, generating the associate schema and validating it. It's pretty straight forward as we already "bundle" Jackson. -- 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]
