Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.unitycatalog.server.cleanup;

import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.observability.StorageCleanupMetrics;
import io.unitycatalog.server.observability.UnityCatalogMetrics;
import io.unitycatalog.server.persist.CleanupTaskRepository;
Expand Down Expand Up @@ -217,6 +218,12 @@ private static NormalizedURL validateTask(Claim claim) {
}

private static String safeError(Exception exception) {
return "Storage cleanup failed: " + exception.getClass().getSimpleName();
// A general error the server chose, such as for a failed AssumeRole, carries the failure as its
// cause; naming its class keeps the record specific without the failure's message.
String name =
exception instanceof BaseException be && exception.getCause() != null
? be.getErrorCode() + " caused by " + exception.getCause().getClass().getSimpleName()
: exception.getClass().getSimpleName();
return "Storage cleanup failed: " + name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ protected BaseException toBaseException(Throwable cause) {
if (cause instanceof BaseException be) {
return be;
}
if (StorageExceptions.isStorageFailure(cause)) {
return StorageExceptions.toGeneralError(cause);
}
if (cause instanceof JWTVerificationException) {
// Use a generic message to avoid leaking JWT verification details to the client
return wrapException(ErrorCode.UNAUTHENTICATED, "Invalid access token.", cause);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package io.unitycatalog.server.exception;

import software.amazon.awssdk.core.exception.SdkException;

/**
* Failures of the server's own AWS SDK calls, such as to S3. Their messages, from the SDK or the
* storage service, can name its endpoint, so callers get a general error. The failure is kept as
* the cause, for the caller to log. Azure and GCS failures are not covered.
*/
public final class StorageExceptions {
/** The message callers get when the server's storage access fails. */
private static final String GENERAL_MESSAGE = "Failed to access storage.";

// Bounds the walk over causes, which a cycle would otherwise make endless.
private static final int MAX_CAUSE_DEPTH = 64;

private StorageExceptions() {}

/**
* Whether {@code e} or one of its causes is an AWS SDK failure. The walk stops at a {@link
* BaseException}, which already says what callers get.
*/
public static boolean isStorageFailure(Throwable e) {
Throwable current = e;
for (int depth = 0; current != null && depth < MAX_CAUSE_DEPTH; depth++) {
if (current instanceof SdkException) {
return true;
}
if (current instanceof BaseException) {
return false;
}
current = current.getCause();
}
return false;
}

/**
* Returns the general error reported for a storage failure.
*
* @param e a failure for which {@link #isStorageFailure} holds
* @return an INTERNAL error that carries no storage detail in its message
*/
public static BaseException toGeneralError(Throwable e) {
return BaseExceptionHandler.wrapException(ErrorCode.INTERNAL, GENERAL_MESSAGE, e);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.exception.StorageExceptions;
import io.unitycatalog.server.exception.TransactionRollbackException;
import java.util.Optional;
import org.hibernate.Session;
Expand Down Expand Up @@ -158,6 +159,9 @@ private static RuntimeException rollBack(
if (e instanceof BaseException baseException) {
return baseException;
}
if (StorageExceptions.isStorageFailure(e)) {
return StorageExceptions.toGeneralError(e);
}
ErrorCode errorCode = DatabaseErrors.errorCode(sessionFactory, e).orElse(ErrorCode.INTERNAL);
return new BaseException(errorCode, errorMessage + ": " + e.getMessage(), e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.unitycatalog.server.service.credential.aws;

import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.model.AwsIamRoleResponse;
import io.unitycatalog.server.persist.dao.CredentialDAO;
import io.unitycatalog.server.service.credential.CredentialContext;
Expand All @@ -11,6 +13,7 @@
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.sts.StsClient;
Expand Down Expand Up @@ -115,7 +118,14 @@ public Credentials generate(CredentialContext ctx) {
.durationSeconds((int) Duration.ofHours(1).toSeconds());
externalId.ifPresent(roleRequestBuilder::externalId);

return stsClient.assumeRole(roleRequestBuilder.build()).credentials();
try {
return stsClient.assumeRole(roleRequestBuilder.build()).credentials();
} catch (SdkException e) {
// The SDK failure is the cause, which the exception handler logs. This names the failed
// step more precisely than StorageExceptions' general message.
throw new BaseException(
ErrorCode.INTERNAL, "Failed to vend temporary storage credentials.", e);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import static org.mockito.Mockito.when;

import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.observability.UcMetric;
import io.unitycatalog.server.observability.UcMetricConstants;
import io.unitycatalog.server.observability.UnityCatalogMetrics;
Expand Down Expand Up @@ -50,6 +52,7 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.sts.model.StsException;

@SuppressWarnings("unchecked")
class StorageCleanupWorkerTest {
Expand Down Expand Up @@ -191,6 +194,20 @@ void retriesWhenFilesRemain() {
verifyFailure("Storage cleanup failed: IllegalStateException");
}

@Test
void recordsTheCauseOfAGeneralError() {
// For example a failed AssumeRole while vending the cleanup credentials.
doThrow(
new BaseException(
ErrorCode.INTERNAL,
"Failed to vend temporary storage credentials.",
StsException.builder().message("secret").build()))
.when(fileIO)
.deletePrefix(PREFIX);
assertThat(worker.runOnce()).isTrue();
verifyFailure("Storage cleanup failed: INTERNAL caused by StsException");
}

@Test
void retriesStorageFailureWithoutItsMessage() {
doThrow(new IllegalArgumentException("secret")).when(fileIO).deletePrefix(PREFIX);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.server.ServiceRequestContext;
import io.unitycatalog.server.delta.model.DeltaErrorType;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import org.apache.iceberg.exceptions.AlreadyExistsException;
import org.apache.iceberg.exceptions.BadRequestException;
import org.apache.iceberg.exceptions.CommitFailedException;
Expand All @@ -40,8 +43,10 @@
import org.apache.iceberg.exceptions.UnprocessableEntityException;
import org.apache.iceberg.rest.responses.ErrorResponse;
import org.apache.iceberg.rest.responses.ErrorResponseParser;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import software.amazon.awssdk.core.exception.SdkClientException;

/**
* Pins the response each API sends for every {@link ErrorCode}, so a change to a status or an error
Expand Down Expand Up @@ -146,6 +151,34 @@ public void everyApiReportsTheErrorCode(ErrorCode errorCode) throws Exception {
assertThat(deltaError.path("type").asText()).isEqualTo(expected.deltaType().getValue());
}

@Test
public void everyApiReportsStorageFailuresAsAGeneralError() throws Exception {
SdkClientException storage = SdkClientException.create("Connect to storage.example.com failed");
for (Throwable failure :
List.of(
storage,
new UncheckedIOException(new IOException("read failed", storage)),
// Would be INVALID_ARGUMENT without the storage failure in its causes.
new IllegalArgumentException("bad location", storage))) {
for (BaseExceptionHandler handler :
Comment on lines +157 to +163

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

an IllegalArgumentException can wrap an SDK error.

List.of(
GlobalExceptionHandler.INSTANCE,
IcebergRestExceptionHandler.INSTANCE,
DeltaApiExceptionHandler.INSTANCE)) {
AggregatedHttpResponse response = errorResponse(handler, failure);
assertThat(response.status().code()).isEqualTo(500);
assertThat(response.contentUtf8())
.contains("Failed to access storage.")
.doesNotContain("storage.example.com");
}
}
// An error the server already chose is reported as it is, whatever its cause.
BaseException chosen = new BaseException(ErrorCode.NOT_FOUND, "Table not found", storage);
assertThat(errorResponse(GlobalExceptionHandler.INSTANCE, chosen).status().code())
.isEqualTo(404);
assertThat(StorageExceptions.isStorageFailure(new RuntimeException(chosen))).isFalse();
}

private static AggregatedHttpResponse errorResponse(
BaseExceptionHandler handler, Throwable error) {
HttpRequest request = HttpRequest.of(HttpMethod.GET, "/");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import io.unitycatalog.server.testdatabase.SupportedDatabase;
import io.unitycatalog.server.testdatabase.TempDatabase;
import io.unitycatalog.server.testdatabase.TestDatabase;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
Expand Down Expand Up @@ -51,6 +53,7 @@
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import software.amazon.awssdk.core.exception.SdkClientException;

public class TransactionManagerTest {

Expand Down Expand Up @@ -145,6 +148,31 @@ public void testTransactionWithRuntimeException() {
verify(transaction, never()).commit();
}

@Test
public void testStorageFailureReportsGeneralError() {
// Storage messages name the storage endpoint, so only the general error is reported.
RuntimeException storageFailure =
new UncheckedIOException(
new IOException(
SdkClientException.create("Connect to storage.example.com:9000 failed")));

assertThatThrownBy(
() ->
TransactionManager.executeWithTransaction(
sessionFactory,
session -> {
throw storageFailure;
},
"Error executing operation",
false))
.isInstanceOf(BaseException.class)
.hasMessage("Failed to access storage.")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this also check that the storage failure is kept as the cause? On this path the handler logs the general BaseException itself, so its cause is the only place the S3 detail survives. I tried dropping it (passing null as the cause in toGeneralError), and all 64 tests in ErrorCodeTest, TransactionManagerTest and CloudCredentialVendorTest still passed. Adding this line makes this test fail on that change and pass on the current code:

Suggested change
.hasMessage("Failed to access storage.")
.hasMessage("Failed to access storage.")
.hasCause(storageFailure)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

.hasCause(storageFailure)
.extracting(e -> ((BaseException) e).getErrorCode())
.isEqualTo(ErrorCode.INTERNAL);
verify(transaction).rollback();
}

@Test
public void testTransactionRollbackExceptionIsRethrownAsIsNotWrapped() {
// A TransactionRollbackException signals rollback, not an error, so it is rethrown by
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import io.unitycatalog.server.service.credential.gcp.TestingCredentialGenerator;
import io.unitycatalog.server.utils.NormalizedURL;
import io.unitycatalog.server.utils.ServerProperties;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
Expand All @@ -40,6 +41,8 @@
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.StsClientBuilder;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
Expand Down Expand Up @@ -128,12 +131,32 @@ public void testGenerateS3TemporaryCredentials() {
.region(S3_REGION)
.awsRoleArn(ROLE_ARN)
.build()));
awsCredentialVendor = new AwsCredentialVendor(serverProperties);
credentialsOperations = new CloudCredentialVendor(awsCredentialVendor, null, null);
assertThatThrownBy(
() ->
vendCredential("s3://storageBase/abc", Set.of(CredentialContext.Privilege.SELECT)))
.isInstanceOf(StsException.class);
// A mocked STS client: an error response from STS, and a failure to reach it. Either is the
// cause of a general error, which the exception handler logs.
for (SdkException failure :
List.<SdkException>of(
StsException.builder().message("not authorized").statusCode(403).build(),
SdkClientException.create("Unable to connect to sts.us-west-2.amazonaws.com"))) {
StsClient stsClient = Mockito.mock(StsClient.class);
when(stsClient.assumeRole(any(AssumeRoleRequest.class))).thenThrow(failure);
StsClientBuilder stsClientBuilder = Mockito.mock(StsClientBuilder.class);
when(stsClientBuilder.region(any())).thenReturn(stsClientBuilder);
when(stsClientBuilder.credentialsProvider(any())).thenReturn(stsClientBuilder);
when(stsClientBuilder.build()).thenReturn(stsClient);
credentialsOperations =
new CloudCredentialVendor(
new AwsCredentialVendor(serverProperties, () -> stsClientBuilder), null, null);
assertThatThrownBy(
() ->
vendCredential(
"s3://storageBase/abc", Set.of(CredentialContext.Privilege.SELECT)))
.as(failure.getClass().getSimpleName())
.isInstanceOf(BaseException.class)
.hasMessage("Failed to vend temporary storage credentials.")
.hasCause(failure)
.extracting(e -> ((BaseException) e).getErrorCode())
.isEqualTo(ErrorCode.INTERNAL);
}
}

@Test
Expand Down
Loading