flyrain commented on code in PR #2680: URL: https://github.com/apache/polaris/pull/2680#discussion_r2412297582
########## runtime/service/src/main/java/org/apache/polaris/service/auth/DefaultPolarisAuthorizerFactory.java: ########## @@ -0,0 +1,37 @@ +/* + * 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.service.auth; + +import io.smallrye.common.annotation.Identifier; +import jakarta.enterprise.context.RequestScoped; +import org.apache.polaris.core.auth.PolarisAuthorizer; +import org.apache.polaris.core.auth.PolarisAuthorizerFactory; +import org.apache.polaris.core.auth.PolarisAuthorizerImpl; +import org.apache.polaris.core.config.RealmConfig; + +/** Factory for creating the default Polaris authorizer implementation. */ +@RequestScoped Review Comment: Same here ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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); Review Comment: I assume the OPA query REST spec are standardized in terms of path, request payload, header, response and http codes. Can you confirm? Would it be possible to add Java doc about which OPA spec we are using here? How does a OPA Service support multiple Polaris instance? Configuring different path? ########## polaris-core/src/main/java/org/apache/polaris/core/auth/FileTokenProvider.java: ########## @@ -0,0 +1,229 @@ +/* + * 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; + +import jakarta.annotation.Nullable; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A token provider that reads tokens from a file and automatically reloads them based on a + * configurable refresh interval or JWT expiration timing. + * + * <p>This is particularly useful in Kubernetes environments where tokens are mounted as files and + * refreshed by external systems (e.g., service account tokens, projected volumes, etc.). + * + * <p>The token file is expected to contain the bearer token as plain text. Leading and trailing + * whitespace will be trimmed. + * + * <p>If JWT expiration refresh is enabled and the token is a valid JWT with an 'exp' claim, the + * provider will automatically refresh the token based on the expiration time minus a configurable + * buffer, rather than using the fixed refresh interval. + */ +public class FileTokenProvider implements TokenProvider { + + private static final Logger logger = LoggerFactory.getLogger(FileTokenProvider.class); + + private final Path tokenFilePath; + private final Duration refreshInterval; + private final boolean jwtExpirationRefresh; + private final Duration jwtExpirationBuffer; + private final ReadWriteLock lock = new ReentrantReadWriteLock(); + + private volatile String cachedToken; + private volatile Instant lastRefresh; + private volatile Instant nextRefresh; + private volatile boolean closed = false; + + /** + * Create a new file-based token provider with basic refresh interval. + * + * @param tokenFilePath path to the file containing the bearer token + * @param refreshInterval how often to check for token file changes + */ + public FileTokenProvider(String tokenFilePath, Duration refreshInterval) { + this(tokenFilePath, refreshInterval, true, Duration.ofSeconds(60)); + } + + /** + * Create a new file-based token provider with JWT expiration support. + * + * @param tokenFilePath path to the file containing the bearer token + * @param refreshInterval how often to check for token file changes (fallback for non-JWT tokens) + * @param jwtExpirationRefresh whether to use JWT expiration for refresh timing + * @param jwtExpirationBuffer buffer time before JWT expiration to refresh the token + */ + public FileTokenProvider( + String tokenFilePath, + Duration refreshInterval, + boolean jwtExpirationRefresh, + Duration jwtExpirationBuffer) { + this.tokenFilePath = Paths.get(tokenFilePath); + this.refreshInterval = refreshInterval; + this.jwtExpirationRefresh = jwtExpirationRefresh; + this.jwtExpirationBuffer = jwtExpirationBuffer; + this.lastRefresh = Instant.MIN; // Force initial load + this.nextRefresh = Instant.MIN; // Force initial calculation + + logger.info( + "Created file token provider for path: {} with refresh interval: {}, JWT expiration refresh: {}, JWT buffer: {}", + tokenFilePath, + refreshInterval, + jwtExpirationRefresh, + jwtExpirationBuffer); + } + + @Override + @Nullable + public String getToken() { + if (closed) { + logger.warn("Token provider is closed, returning null"); + return null; + } + + // Check if we need to refresh + if (shouldRefresh()) { + refreshToken(); + } + + lock.readLock().lock(); + try { + return cachedToken; + } finally { + lock.readLock().unlock(); + } + } + + @Override + public void close() { + closed = true; + lock.writeLock().lock(); + try { + cachedToken = null; + logger.info("File token provider closed"); + } finally { + lock.writeLock().unlock(); + } + } + + private boolean shouldRefresh() { + return Instant.now().isAfter(nextRefresh); + } + + private void refreshToken() { + lock.writeLock().lock(); + try { + // Double-check pattern - another thread might have refreshed while we waited for the lock + if (!shouldRefresh()) { + return; + } + + String newToken = loadTokenFromFile(); + cachedToken = newToken; + lastRefresh = Instant.now(); + + // Calculate next refresh time based on JWT expiration or fixed interval + nextRefresh = calculateNextRefresh(newToken); + + if (logger.isDebugEnabled()) { Review Comment: Do we need this if clause? I think `logger.debug()` will check that by default. ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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) Review Comment: I guess we will need a connection manager (`HttpClientConnectionManager`) soon, as each operation triggers a opa http call. The connection manager could optimize the http client connections. BTW, is it a crazy idea to use the `org.apache.iceberg.rest.HTTPClient` directly? It is well tested with a lot of things built in including connection manager, proxy, etc. The only concern is that it has a bit of extra Iceberg stuff. ########## polaris-core/src/main/java/org/apache/polaris/core/auth/JwtDecoder.java: ########## @@ -0,0 +1,94 @@ +/* + * 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; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Simple JWT decoder that extracts claims without signature verification. This is used solely for + * reading the expiration time from JWT tokens to determine refresh timing. + */ +public class JwtDecoder { Review Comment: Could we use an existing lib, like we did in the class `JWTBroker`? Does something like `JWT.decode()` in the lib `java-jwt` work here? ########## runtime/service/src/main/java/org/apache/polaris/service/auth/OpaPolarisAuthorizerFactory.java: ########## @@ -0,0 +1,97 @@ +/* + * 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.service.auth; + +import io.smallrye.common.annotation.Identifier; +import jakarta.enterprise.context.RequestScoped; +import jakarta.inject.Inject; +import java.time.Duration; +import org.apache.polaris.core.auth.FileTokenProvider; +import org.apache.polaris.core.auth.OpaPolarisAuthorizer; +import org.apache.polaris.core.auth.PolarisAuthorizer; +import org.apache.polaris.core.auth.PolarisAuthorizerFactory; +import org.apache.polaris.core.auth.StaticTokenProvider; +import org.apache.polaris.core.auth.TokenProvider; +import org.apache.polaris.core.config.RealmConfig; +import org.apache.polaris.service.config.AuthorizationConfiguration; + +/** Factory for creating OPA-based Polaris authorizer implementations. */ +@RequestScoped Review Comment: Would `applicationScope` fit better here? We don't need to create a new factory every time a http request comes in. ########## polaris-core/src/main/java/org/apache/polaris/core/auth/TokenProvider.java: ########## @@ -0,0 +1,51 @@ +/* + * 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; + +import jakarta.annotation.Nullable; + +/** + * Interface for providing bearer tokens for authentication. + * + * <p>Implementations can provide tokens from various sources such as: + * + * <ul> + * <li>Static string values + * <li>Files (with automatic reloading) + * <li>External token services + * </ul> + */ +public interface TokenProvider { Review Comment: Nit: Shall we call it `BearerTokenProvider` to be more descriptive, if it is only for bearer token? ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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) { + Review Comment: We may need to do a null check for url and path here. `createSslSocketFactory()` did check the server url, but it doesn't throw, in that case line 129 still creates a http client. I'm not sure how far line 129 can go when url or path is null. It'd be good to fail early in that case. ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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: Not a blocker: Not a fan of manually building the request payload. One option is to create Java classes(example, `DataCompactionPolicyContent`), another option is autogen based on the REST spec. Is there a REST spec we can at least refer to? ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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 Review Comment: Do we need this comment? ########## runtime/service/src/main/java/org/apache/polaris/service/auth/OpaPolarisAuthorizerFactory.java: ########## @@ -0,0 +1,97 @@ +/* + * 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.service.auth; + +import io.smallrye.common.annotation.Identifier; +import jakarta.enterprise.context.RequestScoped; +import jakarta.inject.Inject; +import java.time.Duration; +import org.apache.polaris.core.auth.FileTokenProvider; +import org.apache.polaris.core.auth.OpaPolarisAuthorizer; +import org.apache.polaris.core.auth.PolarisAuthorizer; +import org.apache.polaris.core.auth.PolarisAuthorizerFactory; +import org.apache.polaris.core.auth.StaticTokenProvider; +import org.apache.polaris.core.auth.TokenProvider; +import org.apache.polaris.core.config.RealmConfig; +import org.apache.polaris.service.config.AuthorizationConfiguration; + +/** Factory for creating OPA-based Polaris authorizer implementations. */ +@RequestScoped +@Identifier("opa") +public class OpaPolarisAuthorizerFactory implements PolarisAuthorizerFactory { + + private final AuthorizationConfiguration authorizationConfig; + + @Inject + public OpaPolarisAuthorizerFactory(AuthorizationConfiguration authorizationConfig) { + this.authorizationConfig = authorizationConfig; + } + + @Override + public PolarisAuthorizer create(RealmConfig realmConfig) { + AuthorizationConfiguration.OpaConfig opa = authorizationConfig.opa(); + + // Create appropriate token provider based on configuration + TokenProvider tokenProvider = createTokenProvider(opa); + + return OpaPolarisAuthorizer.create( + opa.url().orElse(null), + opa.policyPath().orElse(null), + tokenProvider, + opa.timeoutMs().orElse(2000), // Default to 2000ms if not specified + opa.verifySsl(), // Default is true from @WithDefault annotation + opa.trustStorePath().orElse(null), + opa.trustStorePassword().orElse(null), + null, + null); + } + + /** + * Creates a token provider based on the OPA configuration. + * + * <p>Prioritizes static token over file-based token: + * + * <ol> + * <li>If bearerToken.staticValue is set, uses StaticTokenProvider + * <li>If bearerToken.filePath is set, uses FileTokenProvider + * <li>Otherwise, returns StaticTokenProvider with null token + * </ol> + */ + private TokenProvider createTokenProvider(AuthorizationConfiguration.OpaConfig opa) { + AuthorizationConfiguration.BearerTokenConfig bearerToken = opa.bearerToken(); + + // Static token takes precedence + if (bearerToken.staticValue().isPresent()) { + return new StaticTokenProvider(bearerToken.staticValue().get()); + } + + // File-based token as fallback + if (bearerToken.filePath().isPresent()) { + Duration refreshInterval = Duration.ofSeconds(bearerToken.refreshInterval()); + boolean jwtExpirationRefresh = bearerToken.jwtExpirationRefresh(); + Duration jwtExpirationBuffer = Duration.ofSeconds(bearerToken.jwtExpirationBuffer()); + + return new FileTokenProvider( Review Comment: Looks like we will create `FileTokenProvider` for every http request. It may not be necessary. Image how much I/O we need as each `FileTokenProvider` refresh the token by itself. Wondering if we could make it per-realm object, given that we don't do per-request token now. ########## runtime/service/src/main/java/org/apache/polaris/service/config/AuthorizationConfiguration.java: ########## @@ -0,0 +1,75 @@ +/* + * 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.service.config; + +import io.smallrye.config.ConfigMapping; +import io.smallrye.config.WithDefault; +import java.util.Optional; + +@ConfigMapping(prefix = "polaris.authorization") +public interface AuthorizationConfiguration { + @WithDefault("default") + String type(); + + OpaConfig opa(); + + interface OpaConfig { + Optional<String> url(); + + Optional<String> policyPath(); + + Optional<Integer> timeoutMs(); + + BearerTokenConfig bearerToken(); + + @WithDefault("true") + boolean verifySsl(); + + Optional<String> trustStorePath(); + + Optional<String> trustStorePassword(); + } + + interface BearerTokenConfig { Review Comment: Nit: Adding a default method like this here, so that caller can validate it? ``` default void validate() { if (refreshInterval() <= 0) { throw new IllegalArgumentException("refreshInterval must be greater than 0"); } if (jwtExpirationBuffer() <= 0) { throw new IllegalArgumentException("jwtExpirationBuffer must be greater than 0"); } } ``` ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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 Review Comment: The a parameter `client` isn't used now, how do you envision it is used in the future? ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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 Review Comment: Same question for the `mapper`? ########## 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: Can we add a Java doc here or somewhere else to clarify that Polaris principal roles and catalog roles are bypassed? Since this literally does that. ########## polaris-core/src/main/java/org/apache/polaris/core/auth/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); + return objectMapper.writeValueAsString(root); + } + + /** + * Builds the actor section of the OPA input JSON. + * + * <p>Includes principal name, and roles as a generic field. + * + * @param principal the principal requesting authorization + * @return the actor node for OPA input + */ + private ObjectNode buildActorNode(PolarisPrincipal principal) { + ObjectNode actor = objectMapper.createObjectNode(); + actor.put("principal", principal.getName()); + ArrayNode roles = objectMapper.createArrayNode(); + for (String role : principal.getRoles()) roles.add(role); + actor.set("roles", roles); + return actor; + } + + /** + * Builds the resource section of the OPA input JSON. + * + * <p>Includes the main target entity under 'primary' and secondary entities under 'secondaries'. + * + * @param targets the list of main target entities + * @param secondaries the list of secondary entities + * @return the resource node for OPA input + */ + private ObjectNode buildResourceNode( + List<PolarisResolvedPathWrapper> targets, List<PolarisResolvedPathWrapper> secondaries) { + ObjectNode resource = objectMapper.createObjectNode(); + // Main targets as 'targets' array + ArrayNode targetsArray = objectMapper.createArrayNode(); + if (targets != null && !targets.isEmpty()) { + for (PolarisResolvedPathWrapper targetWrapper : targets) { + targetsArray.add(buildSingleResourceNode(targetWrapper)); + } + } + resource.set("targets", targetsArray); + // Secondaries as array + ArrayNode secondariesArray = objectMapper.createArrayNode(); + if (secondaries != null && !secondaries.isEmpty()) { + for (PolarisResolvedPathWrapper secondaryWrapper : secondaries) { + secondariesArray.add(buildSingleResourceNode(secondaryWrapper)); + } + } + resource.set("secondaries", secondariesArray); + return resource; + } + + /** Helper to build a resource node for a single PolarisResolvedPathWrapper. */ + private ObjectNode buildSingleResourceNode(PolarisResolvedPathWrapper wrapper) { + ObjectNode node = objectMapper.createObjectNode(); + if (wrapper == null) return node; + var resolvedEntity = wrapper.getResolvedLeafEntity(); + if (resolvedEntity != null) { + var entity = resolvedEntity.getEntity(); + node.put("type", entity.getType().name()); + node.put("name", entity.getName()); + var parentPath = wrapper.getResolvedParentPath(); + if (parentPath != null && !parentPath.isEmpty()) { + ArrayNode parentsArray = objectMapper.createArrayNode(); + for (var parent : parentPath) { + ObjectNode parentNode = objectMapper.createObjectNode(); + parentNode.put("type", parent.getEntity().getType().name()); + parentNode.put("name", parent.getEntity().getName()); + parentsArray.add(parentNode); + } + node.set("parents", parentsArray); + } + } + return node; + } + + /** + * Builds the context section of the OPA input JSON. + * + * <p>Includes only timestamp and request ID. + * + * @return the context node for OPA input + */ + private ObjectNode buildContextNode() { + ObjectNode context = objectMapper.createObjectNode(); + context.put("time", java.time.ZonedDateTime.now().toString()); + context.put("request_id", java.util.UUID.randomUUID().toString()); + return context; + } + + /** + * Creates an SSL socket factory for HTTPS connections based on the configuration. + * + * @param opaServerUrl the OPA server URL + * @param verifySsl whether to verify SSL certificates + * @param trustStorePath custom trust store path (optional) + * @param trustStorePassword custom trust store password (optional) + * @return SSLConnectionSocketFactory for HTTPS connections, or null for HTTP + * @throws Exception if SSL configuration fails + */ + private static SSLConnectionSocketFactory createSslSocketFactory( + String opaServerUrl, boolean verifySsl, String trustStorePath, String trustStorePassword) + throws Exception { + + // Only configure SSL for HTTPS URLs + if (opaServerUrl == null || !opaServerUrl.toLowerCase(Locale.ROOT).startsWith("https")) { + return null; + } + + SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); + SSLContext sslContext; + + if (!verifySsl) { + // Disable SSL verification (for development/testing) + sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE); + sslContext = sslContextBuilder.build(); + return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + } else if (trustStorePath != null && !trustStorePath.isEmpty()) { Review Comment: nit: -> `Strings.isNullOrEmpty()` -- 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]
