Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#11230] feat(server): Add HTTP-level audit logging via HttpAuditFilter (#11618)

Jerry Shaoa852382f682e
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CapturedEventListener.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CapturedEventListener.java
new file mode 100644
index 0000000000..b5a9ba7018
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/CapturedEventListener.java
@@ -0,0 +1,74 @@
+/*
+ * 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.gravitino.client.integration.test;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import org.apache.gravitino.listener.api.EventListenerPlugin;
+import org.apache.gravitino.listener.api.event.Event;
+import org.apache.gravitino.listener.api.event.PreEvent;
+
+/**
+ * A synchronous {@link EventListenerPlugin} that stores every received {@link Event} in a static
+ * list. Because MiniGravitino runs in the same JVM as the test, the static list is shared between
+ * the server and the test code, making it possible to assert on events dispatched by server
+ * internals (e.g. {@code HttpAuditFilter}).
+ *
+ * <p>The class must be public with a no-arg constructor so that {@code EventListenerManager} can
+ * instantiate it via reflection.
+ */
+public class CapturedEventListener implements EventListenerPlugin {
+
+ private static final List<Event> capturedEvents = new CopyOnWriteArrayList<>();
+
+ /** Clears all previously captured events. Call this in {@code @AfterEach} to isolate tests. */
+ public static void clear() {
+ capturedEvents.clear();
+ }
+
+ /** Returns an unmodifiable view of all events captured so far. */
+ public static List<Event> getEvents() {
+ return Collections.unmodifiableList(capturedEvents);
+ }
+
+ @Override
+ public void init(Map<String, String> properties) {}
+
+ @Override
+ public void start() {}
+
+ @Override
+ public void stop() {}
+
+ @Override
+ public void onPostEvent(Event event) {
+ capturedEvents.add(event);
+ }
+
+ @Override
+ public void onPreEvent(PreEvent preEvent) {}
+
+ @Override
+ public Mode mode() {
+ return Mode.SYNC;
+ }
+}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HttpAuditFilterIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HttpAuditFilterIT.java
new file mode 100644
index 0000000000..2bc5cb0a9a
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/HttpAuditFilterIT.java
@@ -0,0 +1,264 @@
+/*
+ * 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.gravitino.client.integration.test;
+
+import com.google.common.collect.Maps;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.auth.AuthConstants;
+import org.apache.gravitino.integration.test.util.BaseIT;
+import org.apache.gravitino.integration.test.util.ITUtils;
+import org.apache.gravitino.listener.EventListenerManager;
+import org.apache.gravitino.listener.api.event.Event;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.OperationType;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
+
+/**
+ * Integration tests for {@code HttpAuditFilter} covering HTTP-layer failure scenarios that are
+ * independent of authorization: unauthenticated requests (401) and malformed JSON bodies (400).
+ *
+ * <p>Uses MiniGravitino (in-process server) and a {@link CapturedEventListener} registered via
+ * config so that events dispatched inside the server are accessible from the test.
+ */
+@DisabledIfSystemProperty(named = ITUtils.TEST_MODE, matches = ITUtils.DEPLOY_TEST_MODE)
+public class HttpAuditFilterIT extends BaseIT {
+
+ private static final String LISTENER_NAME = "httpAuditCapture";
+
+ private HttpClient httpClient;
+
+ @BeforeAll
+ @Override
+ public void startIntegrationTest() throws Exception {
+ Map<String, String> configs = Maps.newHashMap();
+ configs.put(Configs.AUTHENTICATORS.getKey(), "simple");
+ configs.put(
+ EventListenerManager.GRAVITINO_EVENT_LISTENER_PREFIX
+ + EventListenerManager.GRAVITINO_EVENT_LISTENER_NAMES,
+ LISTENER_NAME);
+ configs.put(
+ EventListenerManager.GRAVITINO_EVENT_LISTENER_PREFIX
+ + LISTENER_NAME
+ + "."
+ + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,
+ CapturedEventListener.class.getName());
+ registerCustomConfigs(configs);
+ super.startIntegrationTest();
+ httpClient = HttpClient.newHttpClient();
+ }
+
+ @AfterEach
+ public void clearEvents() {
+ CapturedEventListener.clear();
+ }
+
+ // ─── Task 14: unknown route → 404 → HttpRequestFailureEvent ────────────────
+
+ /**
+ * A GET request to an unknown API route returns 404. {@code HttpAuditFilter} must emit an {@link
+ * HttpRequestFailureEvent} with {@code statusCode=404} because no operation-layer event was
+ * dispatched for a route that the server does not recognise.
+ *
+ * <p>Note: the {@code simple} authenticator admits anonymous requests, so 401 cannot be produced
+ * in this test configuration. A 404 unknown-route scenario is equally valid for verifying that
+ * the filter captures HTTP-layer failures.
+ */
+ @Test
+ public void testUnknownRouteProducesHttpRequestFailureEvent() throws Exception {
+ HttpRequest request =
+ HttpRequest.newBuilder()
+ .uri(
+ new URI(
+ "http://localhost:" + getGravitinoServerPort() + "/api/v99/nonexistent/route"))
+ .GET()
+ .build();
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ Assertions.assertEquals(404, response.statusCode());
+ awaitAtLeastOneEvent();
+
+ List<Event> events = CapturedEventListener.getEvents();
+ HttpRequestFailureEvent httpEvent =
+ events.stream()
+ .filter(e -> e instanceof HttpRequestFailureEvent)
+ .map(e -> (HttpRequestFailureEvent) e)
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No HttpRequestFailureEvent captured for 404"));
+
+ Assertions.assertEquals(404, httpEvent.statusCode());
+ Assertions.assertEquals("GET", httpEvent.httpMethod());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, httpEvent.eventSource());
+ // HttpAuditFilter's finally runs outside Subject.doAs — getCurrentUserName() returns anonymous
+ Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, httpEvent.user());
+ Assertions.assertEquals("/api/v99/nonexistent/route", httpEvent.requestUri());
+ Assertions.assertEquals(OperationType.UNKNOWN, httpEvent.operationType());
+ Assertions.assertNull(httpEvent.identifier());
+ Map<String, String> customInfo = httpEvent.customInfo();
+ Assertions.assertEquals("GET", customInfo.get("http.method"));
+ Assertions.assertEquals("/api/v99/nonexistent/route", customInfo.get("http.uri"));
+ Assertions.assertEquals("404", customInfo.get("http.status"));
+ }
+
+ // ─── Task 16: malformed JSON → 400 → HttpRequestFailureEvent ────────────────
+
+ /**
+ * A POST to the metalakes endpoint with a valid {@code Authorization} header but an invalid JSON
+ * body fails at the Jersey deserialization layer with a 400. {@code HttpAuditFilter} must emit an
+ * {@link HttpRequestFailureEvent} because no operation-layer failure event was dispatched.
+ */
+ @Test
+ public void testMalformedJsonBodyProducesHttpRequestFailureEvent() throws Exception {
+ // Construct a valid simple-auth header so the request passes AuthenticationFilter
+ String userName = System.getProperty("user.name");
+ String authHeader =
+ AuthConstants.AUTHORIZATION_BASIC_HEADER
+ + Base64.getEncoder()
+ .encodeToString((userName + ":dummy").getBytes(StandardCharsets.UTF_8));
+
+ HttpRequest request =
+ HttpRequest.newBuilder()
+ .uri(new URI("http://localhost:" + getGravitinoServerPort() + "/api/metalakes"))
+ .header("Authorization", authHeader)
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString("{this is not valid json"))
+ .build();
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ // Jersey returns 400 for unreadable request bodies; some versions may return 422
+ int status = response.statusCode();
+ Assertions.assertTrue(
+ status == 400 || status == 422,
+ "Expected 400 or 422 for malformed JSON body, got: " + status);
+ awaitAtLeastOneEvent();
+
+ List<Event> events = CapturedEventListener.getEvents();
+ HttpRequestFailureEvent httpEvent =
+ events.stream()
+ .filter(e -> e instanceof HttpRequestFailureEvent)
+ .map(e -> (HttpRequestFailureEvent) e)
+ .filter(e -> e.statusCode() >= 400)
+ .findFirst()
+ .orElseThrow(
+ () ->
+ new AssertionError(
+ "No HttpRequestFailureEvent with status >= 400 captured"
+ + " for malformed JSON"));
+ Assertions.assertEquals("POST", httpEvent.httpMethod());
+ Assertions.assertEquals("/api/metalakes", httpEvent.requestUri());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, httpEvent.eventSource());
+ Assertions.assertEquals(OperationType.UNKNOWN, httpEvent.operationType());
+ Assertions.assertNull(httpEvent.identifier());
+ // Auth succeeds (valid Basic header) before Jersey rejects the body, so the principal
+ // attribute is set on the request and resolveUser() returns the authenticated username.
+ Assertions.assertEquals(userName, httpEvent.user());
+ Map<String, String> malformedCustomInfo = httpEvent.customInfo();
+ Assertions.assertEquals("POST", malformedCustomInfo.get("http.method"));
+ Assertions.assertEquals("/api/metalakes", malformedCustomInfo.get("http.uri"));
+ Assertions.assertEquals(
+ String.valueOf(httpEvent.statusCode()), malformedCustomInfo.get("http.status"));
+ }
+
+ // ─── Health check bypass ─────────────────────────────────────────────────────
+
+ /**
+ * Requests to health check endpoints must never produce an {@link HttpRequestFailureEvent} even
+ * though they may not require authentication.
+ */
+ @Test
+ public void testHealthCheckRequestDoesNotProduceEvent() throws Exception {
+ HttpRequest request =
+ HttpRequest.newBuilder()
+ .uri(new URI("http://localhost:" + getGravitinoServerPort() + "/api/health"))
+ .GET()
+ .build();
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ // Health endpoint should succeed; if it were blocked we'd get a redirect, not a 4xx
+ Assertions.assertTrue(
+ response.statusCode() < 400,
+ "Health check endpoint should not return an error, got: " + response.statusCode());
+
+ // Since Mode.SYNC is used, any event would already be captured; no wait needed
+ List<Event> events = CapturedEventListener.getEvents();
+ boolean hasHttpFailureEvent =
+ events.stream().anyMatch(e -> e instanceof HttpRequestFailureEvent);
+ Assertions.assertFalse(
+ hasHttpFailureEvent, "Health check must not produce an HttpRequestFailureEvent");
+ }
+
+ // ─── No duplicate events per request ────────────────────────────────────────
+
+ /**
+ * Verifies that exactly one {@link HttpRequestFailureEvent} is emitted per failed HTTP request.
+ *
+ * <p>In particular, guards against the double-logging scenario where {@code HttpAuditFilter}
+ * could fire a second event if the servlet container re-invokes the filter chain with {@link
+ * javax.servlet.DispatcherType#ERROR} after an uncaught exception. The filter short-circuits
+ * {@code ERROR} dispatches, so only the original {@code REQUEST} dispatch produces an event.
+ */
+ @Test
+ public void testExactlyOneEventEmittedPerFailedRequest() throws Exception {
+ HttpRequest request =
+ HttpRequest.newBuilder()
+ .uri(
+ new URI(
+ "http://localhost:" + getGravitinoServerPort() + "/api/v99/no-such-endpoint"))
+ .GET()
+ .build();
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ Assertions.assertEquals(404, response.statusCode());
+ awaitAtLeastOneEvent();
+
+ long httpFailureEventCount =
+ CapturedEventListener.getEvents().stream()
+ .filter(e -> e instanceof HttpRequestFailureEvent)
+ .count();
+ Assertions.assertEquals(
+ 1,
+ httpFailureEventCount,
+ "Expected exactly one HttpRequestFailureEvent per failed request, got: "
+ + httpFailureEventCount);
+ }
+
+ // ─── Helper ──────────────────────────────────────────────────────────────────
+
+ private void awaitAtLeastOneEvent() {
+ Awaitility.await()
+ .atMost(5, TimeUnit.SECONDS)
+ .pollInterval(50, TimeUnit.MILLISECONDS)
+ .until(() -> !CapturedEventListener.getEvents().isEmpty());
+ }
+}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/HttpAuditAuthzDenialIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/HttpAuditAuthzDenialIT.java
new file mode 100644
index 0000000000..b3cfef9dd0
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/HttpAuditAuthzDenialIT.java
@@ -0,0 +1,289 @@
+/*
+ * 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.gravitino.client.integration.test.authorization;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.MetalakeChange;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.client.GravitinoAdminClient;
+import org.apache.gravitino.client.integration.test.CapturedEventListener;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.integration.test.util.ITUtils;
+import org.apache.gravitino.listener.EventListenerManager;
+import org.apache.gravitino.listener.api.event.Event;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.FailureEvent;
+import org.apache.gravitino.listener.api.event.OperationType;
+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
+
+/**
+ * Integration tests for authorization denial scenarios in {@code
+ * MetadataAuthorizationMethodInterceptor} and their interaction with {@code HttpAuditFilter}. All
+ * tests use MiniGravitino with authorization enabled.
+ *
+ * <p>Two denial mechanisms are covered:
+ *
+ * <ul>
+ * <li><b>Executor denial</b>: the user is a metalake member but lacks the required privilege. The
+ * authorization executor returns {@code false}, triggering an {@link
+ * AuthorizationDenialFailureEvent}. The {@code operationFailureFired} flag prevents {@code
+ * HttpAuditFilter} from emitting a duplicate failure event.
+ * <li><b>User-validation denial</b>: {@code checkCurrentUser} throws {@link ForbiddenException}
+ * because the user is not a metalake member. An {@link AuthorizationDenialFailureEvent} is
+ * dispatched, and the {@code operationFailureFired} flag again suppresses a duplicate.
+ * </ul>
+ */
+@DisabledIfSystemProperty(named = ITUtils.TEST_MODE, matches = ITUtils.DEPLOY_TEST_MODE)
+public class HttpAuditAuthzDenialIT extends BaseRestApiAuthorizationIT {
+
+ private static final String LISTENER_NAME = "httpAuditAuthzCapture";
+
+ /** A user who is authenticated but never added to {@link #METALAKE}. */
+ private static final String NON_MEMBER_USER = "nonMemberUser";
+
+ private static GravitinoAdminClient nonMemberClient;
+
+ @BeforeAll
+ @Override
+ public void startIntegrationTest() throws Exception {
+ // Register the capturing listener before the parent starts the server
+ customConfigs.put(
+ EventListenerManager.GRAVITINO_EVENT_LISTENER_PREFIX
+ + EventListenerManager.GRAVITINO_EVENT_LISTENER_NAMES,
+ LISTENER_NAME);
+ customConfigs.put(
+ EventListenerManager.GRAVITINO_EVENT_LISTENER_PREFIX
+ + LISTENER_NAME
+ + "."
+ + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,
+ CapturedEventListener.class.getName());
+ // Parent enables authorization, starts server, creates the metalake, and adds NORMAL_USER
+ super.startIntegrationTest();
+
+ // Create a client for a user who is NOT a metalake member
+ nonMemberClient =
+ GravitinoAdminClient.builder(serverUri).withSimpleAuth(NON_MEMBER_USER).build();
+ }
+
+ @AfterEach
+ public void clearEvents() {
+ CapturedEventListener.clear();
+ }
+
+ /**
+ * When an authenticated metalake member lacking {@code CREATE_CATALOG} privilege calls {@code
+ * createCatalog}, the authorization executor returns {@code false}. An {@link
+ * AuthorizationDenialFailureEvent} is dispatched and the {@code operationFailureFired} flag is
+ * set, so {@code HttpAuditFilter} skips emitting a duplicate failure event for the same request.
+ *
+ * <p>{@code listCatalogs} is intentionally not used here because it carries {@code expression =
+ * ""} which bypasses the authorization executor entirely.
+ */
+ @Test
+ public void testExecutorDenialOnCreateCatalogProducesEventAndNoDuplicate() {
+ // NORMAL_USER is in the metalake but has no CREATE_CATALOG privilege
+ Assertions.assertThrows(
+ ForbiddenException.class,
+ () ->
+ normalUserClient
+ .loadMetalake(METALAKE)
+ .createCatalog(
+ "denied-catalog", Catalog.Type.RELATIONAL, "hive", "", new HashMap<>()));
+ awaitAtLeastOneEvent();
+
+ List<Event> events = CapturedEventListener.getEvents();
+
+ long authzDenialCount =
+ events.stream().filter(e -> e instanceof AuthorizationDenialFailureEvent).count();
+ long otherFailureCount =
+ events.stream()
+ .filter(e -> e instanceof FailureEvent)
+ .filter(e -> !(e instanceof AuthorizationDenialFailureEvent))
+ .count();
+
+ Assertions.assertTrue(
+ authzDenialCount >= 1,
+ "Expected at least one AuthorizationDenialFailureEvent for a denied createCatalog");
+ Assertions.assertEquals(
+ 0,
+ otherFailureCount,
+ "No duplicate failure event should be emitted when"
+ + " AuthorizationDenialFailureEvent was already dispatched");
+
+ AuthorizationDenialFailureEvent authzEvent =
+ events.stream()
+ .filter(e -> e instanceof AuthorizationDenialFailureEvent)
+ .map(e -> (AuthorizationDenialFailureEvent) e)
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No AuthorizationDenialFailureEvent found"));
+ Assertions.assertEquals(NORMAL_USER, authzEvent.user());
+ Assertions.assertEquals(OperationType.AUTHORIZATION_DENIAL, authzEvent.operationType());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, authzEvent.eventSource());
+ // accessMetadataType = METALAKE for createCatalog → identifier is the metalake NameIdentifier
+ Assertions.assertEquals(NameIdentifier.of(METALAKE), authzEvent.identifier());
+ Map<String, String> customInfo = authzEvent.customInfo();
+ Assertions.assertEquals("createCatalog", customInfo.get("auth.method"));
+ Assertions.assertEquals(
+ "METALAKE::CREATE_CATALOG || METALAKE::OWNER", customInfo.get("auth.expression"));
+ }
+
+ /**
+ * When an authenticated metalake member calls {@code alterMetalake}, which requires {@code
+ * METALAKE::OWNER}, the authorization executor returns {@code false} because {@link #NORMAL_USER}
+ * was added as a plain member (not an owner). This is an executor denial for a different
+ * operation and expression than {@link
+ * #testExecutorDenialOnCreateCatalogProducesEventAndNoDuplicate()}.
+ */
+ @Test
+ public void testExecutorDenialOnAlterMetalakeProducesCorrectEvent() {
+ Assertions.assertThrows(
+ ForbiddenException.class,
+ () -> normalUserClient.alterMetalake(METALAKE, MetalakeChange.updateComment("no-op")));
+ awaitAtLeastOneEvent();
+
+ List<Event> events = CapturedEventListener.getEvents();
+
+ AuthorizationDenialFailureEvent authzEvent =
+ events.stream()
+ .filter(e -> e instanceof AuthorizationDenialFailureEvent)
+ .map(e -> (AuthorizationDenialFailureEvent) e)
+ .findFirst()
+ .orElseThrow(
+ () ->
+ new AssertionError(
+ "No AuthorizationDenialFailureEvent captured for alterMetalake"));
+ Assertions.assertEquals(NORMAL_USER, authzEvent.user());
+ Assertions.assertEquals(OperationType.AUTHORIZATION_DENIAL, authzEvent.operationType());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, authzEvent.eventSource());
+ Assertions.assertEquals(NameIdentifier.of(METALAKE), authzEvent.identifier());
+ Map<String, String> customInfo = authzEvent.customInfo();
+ Assertions.assertEquals("alterMetalake", customInfo.get("auth.method"));
+ Assertions.assertEquals("METALAKE::OWNER", customInfo.get("auth.expression"));
+ }
+
+ /**
+ * When an authenticated user who is NOT a metalake member calls {@code loadMetalake}, {@code
+ * checkCurrentUser} throws {@link ForbiddenException} before any operation proceeds. The
+ * interceptor dispatches an {@link AuthorizationDenialFailureEvent} and sets the {@code
+ * operationFailureFired} flag.
+ *
+ * <p>Note: {@link GravitinoAdminClient#loadMetalake} makes an immediate REST call, so {@code
+ * loadMetalake} is the intercepted operation — the event carries {@code auth.method=loadMetalake}
+ * and {@code auth.expression=METALAKE_USER}.
+ */
+ @Test
+ public void testNonMemberOnLoadMetalakeProducesAuthorizationEvent() {
+ // loadMetalake makes an immediate REST call; checkCurrentUser throws ForbiddenException for
+ // non-members before the method body executes.
+ Assertions.assertThrows(ForbiddenException.class, () -> nonMemberClient.loadMetalake(METALAKE));
+ awaitAtLeastOneEvent();
+
+ List<Event> events = CapturedEventListener.getEvents();
+
+ Assertions.assertTrue(
+ events.stream().anyMatch(e -> e instanceof AuthorizationDenialFailureEvent),
+ "checkCurrentUser failure must dispatch AuthorizationDenialFailureEvent");
+
+ AuthorizationDenialFailureEvent authzEvent =
+ events.stream()
+ .filter(e -> e instanceof AuthorizationDenialFailureEvent)
+ .map(e -> (AuthorizationDenialFailureEvent) e)
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No AuthorizationDenialFailureEvent found"));
+ Assertions.assertEquals(NON_MEMBER_USER, authzEvent.user());
+ Assertions.assertEquals(OperationType.AUTHORIZATION_DENIAL, authzEvent.operationType());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, authzEvent.eventSource());
+ Assertions.assertEquals(NameIdentifier.of(METALAKE), authzEvent.identifier());
+ Map<String, String> customInfo = authzEvent.customInfo();
+ // loadMetalake uses
+ // @AuthorizationExpression(expression = LOAD_METALAKE_AUTHORIZATION_EXPRESSION)
+ Assertions.assertEquals("loadMetalake", customInfo.get("auth.method"));
+ Assertions.assertEquals("METALAKE_USER", customInfo.get("auth.expression"));
+ }
+
+ /**
+ * When a non-member calls {@code alterMetalake} (expression {@code METALAKE::OWNER}), {@code
+ * checkCurrentUser} throws {@link ForbiddenException} before the expression executor runs. This
+ * verifies that the user-validation denial also sets the {@code operationFailureFired} flag — no
+ * duplicate {@link org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent} should
+ * be emitted, even when the operation carries a non-empty authorization expression.
+ */
+ @Test
+ public void testNonMemberOnAlterMetalakeProducesNoDuplicateFailureEvent() {
+ Assertions.assertThrows(
+ ForbiddenException.class,
+ () -> nonMemberClient.alterMetalake(METALAKE, MetalakeChange.updateComment("no-op")));
+ awaitAtLeastOneEvent();
+
+ List<Event> events = CapturedEventListener.getEvents();
+
+ long authzDenialCount =
+ events.stream().filter(e -> e instanceof AuthorizationDenialFailureEvent).count();
+ long otherFailureCount =
+ events.stream()
+ .filter(e -> e instanceof FailureEvent)
+ .filter(e -> !(e instanceof AuthorizationDenialFailureEvent))
+ .count();
+
+ Assertions.assertTrue(
+ authzDenialCount >= 1,
+ "Expected at least one AuthorizationDenialFailureEvent for non-member on alterMetalake");
+ Assertions.assertEquals(
+ 0,
+ otherFailureCount,
+ "No duplicate failure event should be emitted when"
+ + " AuthorizationDenialFailureEvent was already dispatched");
+
+ AuthorizationDenialFailureEvent authzEvent =
+ events.stream()
+ .filter(e -> e instanceof AuthorizationDenialFailureEvent)
+ .map(e -> (AuthorizationDenialFailureEvent) e)
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No AuthorizationDenialFailureEvent found"));
+ Assertions.assertEquals(NON_MEMBER_USER, authzEvent.user());
+ Assertions.assertEquals(OperationType.AUTHORIZATION_DENIAL, authzEvent.operationType());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, authzEvent.eventSource());
+ Assertions.assertEquals(NameIdentifier.of(METALAKE), authzEvent.identifier());
+ Map<String, String> customInfo = authzEvent.customInfo();
+ // checkCurrentUser fails before the expression is evaluated, but the annotation expression
+ // is still recorded in auth.expression for auditability.
+ Assertions.assertEquals("alterMetalake", customInfo.get("auth.method"));
+ Assertions.assertEquals("METALAKE::OWNER", customInfo.get("auth.expression"));
+ }
+
+ // ─── Helper ──────────────────────────────────────────────────────────────────
+
+ private void awaitAtLeastOneEvent() {
+ Awaitility.await()
+ .atMost(5, TimeUnit.SECONDS)
+ .pollInterval(50, TimeUnit.MILLISECONDS)
+ .until(() -> !CapturedEventListener.getEvents().isEmpty());
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java b/core/src/main/java/org/apache/gravitino/audit/AuditLog.java
index 52f3b74026..5ec07983c7 100644
--- a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java
+++ b/core/src/main/java/org/apache/gravitino/audit/AuditLog.java
@@ -105,6 +105,7 @@ import org.apache.gravitino.listener.api.event.PurgePartitionEvent;
import org.apache.gravitino.listener.api.event.PurgePartitionFailureEvent;
import org.apache.gravitino.listener.api.event.PurgeTableEvent;
import org.apache.gravitino.listener.api.event.PurgeTableFailureEvent;
+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
import org.apache.gravitino.listener.api.event.view.AlterViewEvent;
import org.apache.gravitino.listener.api.event.view.AlterViewFailureEvent;
import org.apache.gravitino.listener.api.event.view.CreateViewEvent;
@@ -483,6 +484,8 @@ public interface AuditLog {
LIST_FUNCTION_INFOS,
+ AUTHORIZATION_DENIAL,
+
UNKNOWN_OPERATION;
public static Operation fromEvent(Event event) {
@@ -587,6 +590,8 @@ public interface AuditLog {
return LOAD_FILESET;
} else if (event instanceof ListFilesetEvent || event instanceof ListFilesetFailureEvent) {
return LIST_FILESET;
+ } else if (event instanceof AuthorizationDenialFailureEvent) {
+ return AUTHORIZATION_DENIAL;
} else {
return UNKNOWN_OPERATION;
}
diff --git a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java
index 66ad5f80ff..3c4c905997 100644
--- a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java
+++ b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java
@@ -181,6 +181,7 @@ public class CompatibilityUtils {
.put(OperationType.DROP_FUNCTION, Operation.DROP_FUNCTION)
.put(OperationType.LIST_FUNCTION, Operation.LIST_FUNCTION)
.put(OperationType.LIST_FUNCTION_INFOS, Operation.LIST_FUNCTION_INFOS)
+ .put(OperationType.AUTHORIZATION_DENIAL, Operation.AUTHORIZATION_DENIAL)
.put(OperationType.UNKNOWN, Operation.UNKNOWN_OPERATION)
.build();
diff --git a/core/src/main/java/org/apache/gravitino/listener/EventBus.java b/core/src/main/java/org/apache/gravitino/listener/EventBus.java
index eb5b49cdfc..17af8d718a 100644
--- a/core/src/main/java/org/apache/gravitino/listener/EventBus.java
+++ b/core/src/main/java/org/apache/gravitino/listener/EventBus.java
@@ -31,6 +31,8 @@ import org.apache.gravitino.listener.api.event.Event;
import org.apache.gravitino.listener.api.event.FailureEvent;
import org.apache.gravitino.listener.api.event.PreEvent;
import org.apache.gravitino.listener.api.event.SupportsChangingPreEvent;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
+import org.apache.gravitino.utils.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -129,17 +131,27 @@ public class EventBus {
}
/**
- * Dispatches a failure failureEvent to listeners, swallowing all exceptions to preserve the
- * original error.
+ * Dispatches a failure event to listeners, swallowing all exceptions to preserve the original
+ * error.
*
* <p>When the primary operation fails, we want to notify listeners, but listener exceptions must
- * NOT propagate and mask the original failure. This method catches and logs all exceptions
- * (including {@link RuntimeException}, {@link Error}, etc.) to ensure the original exception can
- * be properly thrown to the caller.
+ * NOT propagate and mask the original failure. This method catches and logs all {@link
+ * Exception}s to ensure the original exception can be properly thrown to the caller.
+ *
+ * <p>For every failure event that is <em>not</em> an {@link HttpRequestFailureEvent}, this method
+ * also sets {@link RequestContext#markOperationFailureFired()} on the current thread. This lets
+ * {@code HttpAuditFilter} detect that an operation-layer failure event has already been
+ * dispatched and skip emitting a redundant HTTP-level event for the same request.
*
* @param failureEvent the failure event to dispatch
*/
private void dispatchFailureEvent(Event failureEvent) {
+ // Mark the request thread so HttpAuditFilter skips emitting its own event.
+ // HttpRequestFailureEvent is exempt — it IS the HTTP-layer event and must not set the flag,
+ // otherwise it would suppress itself on the next pass through the finally block.
+ if (!(failureEvent instanceof HttpRequestFailureEvent)) {
+ RequestContext.markOperationFailureFired();
+ }
try {
eventListeners.forEach(eventListener -> eventListener.onPostEvent(failureEvent));
} catch (Exception e) {
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/EventSource.java b/core/src/main/java/org/apache/gravitino/listener/api/event/EventSource.java
index 619c03f27a..d69762e79c 100644
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/EventSource.java
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/EventSource.java
@@ -21,5 +21,6 @@ package org.apache.gravitino.listener.api.event;
public enum EventSource {
GRAVITINO_SERVER,
- GRAVITINO_ICEBERG_REST_SERVER
+ GRAVITINO_ICEBERG_REST_SERVER,
+ GRAVITINO_LANCE_REST_SERVER
}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java
index a4a0127f3f..e6cf6f81bb 100644
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java
@@ -197,5 +197,7 @@ public enum OperationType {
LIST_FUNCTION,
LIST_FUNCTION_INFOS,
+ AUTHORIZATION_DENIAL,
+
UNKNOWN,
}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/server/AuthorizationDenialFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/server/AuthorizationDenialFailureEvent.java
new file mode 100644
index 0000000000..ef9613ec20
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/server/AuthorizationDenialFailureEvent.java
@@ -0,0 +1,154 @@
+/*
+ * 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.gravitino.listener.api.event.server;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.FailureEvent;
+import org.apache.gravitino.listener.api.event.OperationType;
+
+/**
+ * Represents an authorization denial that occurred inside {@code
+ * MetadataAuthorizationMethodInterceptor}: the request was authenticated but the authorization
+ * executor returned {@code false} for the requested operation, or user validation raised a
+ * forbidden exception.
+ *
+ * <p>This event carries rich context about the denial — the authenticated user, the resource
+ * identifier, the Java method name, and the authorization expression — so auditors can reconstruct
+ * exactly what was attempted and why it was refused.
+ *
+ * <p>Compared to a generic {@link HttpRequestFailureEvent} with {@code http.status=403}, this event
+ * is distinguished by {@link OperationType#AUTHORIZATION_DENIAL} and by the non-null {@link
+ * #identifier()} and {@link #customInfo()} fields. Dispatching this event before returning the 403
+ * response also sets the {@code RequestContext.operationFailureFired} flag, preventing {@code
+ * HttpAuditFilter} from emitting a duplicate HTTP-level event for the same request.
+ */
+@DeveloperApi
+public final class AuthorizationDenialFailureEvent extends FailureEvent {
+
+ private final String methodName;
+ private final String expression;
+ private final EventSource explicitEventSource;
+
+ /**
+ * Constructs an {@code AuthorizationDenialFailureEvent} attributed to the main Gravitino server.
+ *
+ * @param user the authenticated user whose request was denied.
+ * @param accessMetadataName the {@link NameIdentifier} of the resource the user attempted to
+ * access. May be {@code null} when the denial occurs at the metalake-user validation level
+ * before a specific resource is resolved.
+ * @param methodName the name of the intercepted Java method (e.g. {@code "loadTable"}).
+ * @param expression the authorization expression that was evaluated (e.g. {@code "TABLE:LOAD"}).
+ * May be empty when the denial occurs before the expression is extracted.
+ */
+ public AuthorizationDenialFailureEvent(
+ String user,
+ @Nullable NameIdentifier accessMetadataName,
+ String methodName,
+ String expression) {
+ this(user, accessMetadataName, methodName, expression, EventSource.GRAVITINO_SERVER);
+ }
+
+ /**
+ * Constructs an {@code AuthorizationDenialFailureEvent} with an explicit {@link EventSource}. Use
+ * this overload when the denial originates from a server other than the main Gravitino server
+ * (e.g. Iceberg REST, Lance REST).
+ *
+ * @param user the authenticated user whose request was denied.
+ * @param accessMetadataName the {@link NameIdentifier} of the resource the user attempted to
+ * access. May be {@code null}.
+ * @param methodName the name of the intercepted Java method.
+ * @param expression the authorization expression that was evaluated.
+ * @param eventSource identifies which server produced this denial event.
+ */
+ public AuthorizationDenialFailureEvent(
+ String user,
+ @Nullable NameIdentifier accessMetadataName,
+ String methodName,
+ String expression,
+ EventSource eventSource) {
+ super(user, accessMetadataName, new AuthorizationDenialException(user, methodName));
+ this.methodName = methodName;
+ this.expression = expression != null ? expression : "";
+ this.explicitEventSource = eventSource;
+ }
+
+ /** Returns {@link OperationType#AUTHORIZATION_DENIAL}. */
+ @Override
+ public OperationType operationType() {
+ return OperationType.AUTHORIZATION_DENIAL;
+ }
+
+ /** Returns the {@link EventSource} supplied at construction time. */
+ @Override
+ public EventSource eventSource() {
+ return explicitEventSource;
+ }
+
+ /**
+ * Returns authorization-specific context that distinguishes this event from HTTP-level events.
+ *
+ * <ul>
+ * <li>{@code auth.method} — the intercepted Java method name
+ * <li>{@code auth.expression} — the authorization expression evaluated, or empty string if not
+ * yet resolved at the point of denial
+ * </ul>
+ *
+ * <p>The denied resource name is available via {@link #identifier()} and is intentionally omitted
+ * here to avoid duplication.
+ */
+ @Override
+ public Map<String, String> customInfo() {
+ return ImmutableMap.of(
+ "auth.method", methodName,
+ "auth.expression", expression);
+ }
+
+ /** Returns the intercepted Java method name. */
+ public String methodName() {
+ return methodName;
+ }
+
+ /** Returns the authorization expression that was evaluated. */
+ public String expression() {
+ return expression;
+ }
+
+ /**
+ * A lightweight synthetic exception used as the {@link
+ * org.apache.gravitino.listener.api.event.FailureEvent#exception()} carrier. Stack trace
+ * collection is suppressed because authorization denials can be high-volume and the trace adds no
+ * diagnostic value for this event type.
+ */
+ public static final class AuthorizationDenialException extends RuntimeException {
+
+ private AuthorizationDenialException(String user, String methodName) {
+ super(
+ String.format("Authorization denied for user '%s' on operation '%s'", user, methodName),
+ null,
+ true,
+ false /* suppress stack trace */);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/server/HttpRequestFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/server/HttpRequestFailureEvent.java
new file mode 100644
index 0000000000..2556dba7bd
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/server/HttpRequestFailureEvent.java
@@ -0,0 +1,151 @@
+/*
+ * 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.gravitino.listener.api.event.server;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.FailureEvent;
+import org.apache.gravitino.listener.api.event.OperationType;
+
+/**
+ * Represents an HTTP-level request failure that occurred before or outside the operation dispatcher
+ * layer — for example, a 401 authentication rejection, a 400 malformed JSON body, or a 404 unknown
+ * route. It is emitted by {@code HttpAuditFilter} when the HTTP response status is 4xx or 5xx and
+ * no operation-layer {@link FailureEvent} was already dispatched for the same request.
+ *
+ * <p>Unlike operation-layer failure events, this event carries no {@link
+ * org.apache.gravitino.NameIdentifier} (the resource was never resolved) and its {@link
+ * #operationType()} is always {@link OperationType#UNKNOWN}. HTTP-specific context (method, URI,
+ * status code) is available via {@link #customInfo()}.
+ *
+ * <p>This event extends {@link FailureEvent} so it is routed through {@code
+ * EventBus.dispatchFailureEvent()}, which swallows listener exceptions and prevents audit failures
+ * from masking the original HTTP error.
+ */
+@DeveloperApi
+public final class HttpRequestFailureEvent extends FailureEvent {
+
+ private final String explicitRemoteAddress;
+ private final String httpMethod;
+ private final String requestUri;
+ private final int statusCode;
+ private final EventSource explicitEventSource;
+
+ /**
+ * Constructs an {@code HttpRequestFailureEvent}.
+ *
+ * @param user the authenticated user, or {@code "unknown"} if authentication had not completed.
+ * @param remoteAddress the client IP resolved by the filter (X-Forwarded-For or raw socket
+ * address). Stored explicitly because Iceberg and Lance servers do not install {@code
+ * RequestContextFilter}, so {@code RequestContext.getRemoteAddress()} may be unset.
+ * @param httpMethod the HTTP method (e.g. {@code "GET"}, {@code "POST"}).
+ * @param requestUri the request URI path (e.g. {@code "/api/metalakes/m1/catalogs"}).
+ * @param statusCode the HTTP response status code (e.g. {@code 401}, {@code 404}).
+ * @param eventSource identifies which server produced the event.
+ */
+ public HttpRequestFailureEvent(
+ String user,
+ String remoteAddress,
+ String httpMethod,
+ String requestUri,
+ int statusCode,
+ EventSource eventSource) {
+ super(user, null, new HttpRequestException(httpMethod, requestUri, statusCode));
+ this.explicitRemoteAddress = remoteAddress != null ? remoteAddress : "unknown";
+ this.httpMethod = httpMethod;
+ this.requestUri = requestUri;
+ this.statusCode = statusCode;
+ this.explicitEventSource = eventSource;
+ }
+
+ /** Returns {@link OperationType#UNKNOWN} — no operation was identified at the HTTP layer. */
+ @Override
+ public OperationType operationType() {
+ return OperationType.UNKNOWN;
+ }
+
+ /**
+ * Returns the explicitly-resolved client remote address. This overrides the base {@link
+ * org.apache.gravitino.listener.api.event.Event} behaviour (which reads from {@link
+ * org.apache.gravitino.utils.RequestContext}) so that events emitted by servers that do not
+ * install {@code RequestContextFilter} still carry a correct address.
+ */
+ @Override
+ public String remoteAddress() {
+ return explicitRemoteAddress;
+ }
+
+ /** Returns the {@link EventSource} supplied at construction time. */
+ @Override
+ public EventSource eventSource() {
+ return explicitEventSource;
+ }
+
+ /**
+ * Returns HTTP-specific context that distinguishes this event from operation-layer events.
+ *
+ * <ul>
+ * <li>{@code http.method} — the HTTP verb
+ * <li>{@code http.uri} — the request URI path
+ * <li>{@code http.status} — the response status code as a string
+ * </ul>
+ */
+ @Override
+ public Map<String, String> customInfo() {
+ return ImmutableMap.of(
+ "http.method", httpMethod,
+ "http.uri", requestUri,
+ "http.status", String.valueOf(statusCode));
+ }
+
+ /** Returns the HTTP method. */
+ public String httpMethod() {
+ return httpMethod;
+ }
+
+ /** Returns the request URI. */
+ public String requestUri() {
+ return requestUri;
+ }
+
+ /** Returns the HTTP response status code. */
+ public int statusCode() {
+ return statusCode;
+ }
+
+ /**
+ * A lightweight synthetic exception used as the {@link FailureEvent#exception()} carrier for
+ * {@link HttpRequestFailureEvent}. It encodes the HTTP method, URI, and status so that log
+ * formatters that render the exception message get readable output without needing to inspect
+ * {@link HttpRequestFailureEvent#customInfo()} separately.
+ */
+ public static final class HttpRequestException extends RuntimeException {
+
+ private HttpRequestException(String httpMethod, String requestUri, int statusCode) {
+ super(
+ String.format("HTTP request failed: %s %s -> %d", httpMethod, requestUri, statusCode),
+ null,
+ true,
+ false /* suppress stack trace — this is a synthetic carrier, not a real exception */);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/utils/RequestContext.java b/core/src/main/java/org/apache/gravitino/utils/RequestContext.java
index 9b37bdb942..bfdbb9c60e 100644
--- a/core/src/main/java/org/apache/gravitino/utils/RequestContext.java
+++ b/core/src/main/java/org/apache/gravitino/utils/RequestContext.java
@@ -20,8 +20,20 @@
package org.apache.gravitino.utils;
/**
- * Holds per-request context data (e.g. client IP) in a {@link ThreadLocal} so that event classes
- * constructed on the servlet thread can capture it without carrying a servlet dependency.
+ * Holds per-request context data in a {@link ThreadLocal} so that event classes constructed on the
+ * servlet thread can capture it without carrying a servlet dependency.
+ *
+ * <p>Currently tracks two pieces of state:
+ *
+ * <ul>
+ * <li><b>remoteAddress</b> — the client IP resolved from {@code X-Forwarded-For} or {@link
+ * javax.servlet.http.HttpServletRequest#getRemoteAddr()}.
+ * <li><b>operationFailureFired</b> — set to {@code true} by {@link
+ * org.apache.gravitino.listener.EventBus} when an operation-layer {@link
+ * org.apache.gravitino.listener.api.event.FailureEvent} is dispatched, so that {@code
+ * HttpAuditFilter} can skip emitting a redundant HTTP-level failure event for the same
+ * request.
+ * </ul>
*
* <p><b>Threading contract:</b> values must be set and cleared on the same (servlet) thread. Event
* constructors read the value at construction time and store it as a field, so async listener
@@ -30,6 +42,7 @@ package org.apache.gravitino.utils;
public class RequestContext {
private static final ThreadLocal<String> REMOTE_ADDRESS = new ThreadLocal<>();
+ private static final ThreadLocal<Boolean> OPERATION_FAILURE_FIRED = new ThreadLocal<>();
private RequestContext() {}
@@ -53,10 +66,39 @@ public class RequestContext {
}
/**
- * Removes the remote address binding from the current thread. Must be called in a {@code finally}
+ * Marks that an operation-layer {@code FailureEvent} has been dispatched for the current request.
+ * Called by {@code EventBus.dispatchFailureEvent()} for every failure event that is not itself an
+ * {@code HttpRequestFailureEvent}.
+ */
+ public static void markOperationFailureFired() {
+ OPERATION_FAILURE_FIRED.set(Boolean.TRUE);
+ }
+
+ /**
+ * Returns {@code true} if an operation-layer failure event has already been dispatched on this
+ * thread for the current request.
+ *
+ * @return {@code true} if the flag is set, {@code false} otherwise.
+ */
+ public static boolean isOperationFailureFired() {
+ return Boolean.TRUE.equals(OPERATION_FAILURE_FIRED.get());
+ }
+
+ /**
+ * Clears the operation-failure flag for the current request thread. Must be called in a {@code
+ * finally} block by {@code HttpAuditFilter} at the end of each request to prevent stale values
+ * from leaking to the next request on the same Jetty thread.
+ */
+ public static void resetOperationFailureFired() {
+ OPERATION_FAILURE_FIRED.remove();
+ }
+
+ /**
+ * Removes all per-request bindings from the current thread. Must be called in a {@code finally}
* block after the request completes to prevent thread-pool leaks.
*/
public static void clear() {
REMOTE_ADDRESS.remove();
+ OPERATION_FAILURE_FIRED.remove();
}
}
diff --git a/core/src/test/java/org/apache/gravitino/audit/TestOperation.java b/core/src/test/java/org/apache/gravitino/audit/TestOperation.java
index 94c7405d72..5531da02fe 100644
--- a/core/src/test/java/org/apache/gravitino/audit/TestOperation.java
+++ b/core/src/test/java/org/apache/gravitino/audit/TestOperation.java
@@ -75,6 +75,7 @@ import org.apache.gravitino.listener.api.event.EnableCatalogFailureEvent;
import org.apache.gravitino.listener.api.event.EnableMetalakeEvent;
import org.apache.gravitino.listener.api.event.EnableMetalakeFailureEvent;
import org.apache.gravitino.listener.api.event.Event;
+import org.apache.gravitino.listener.api.event.EventSource;
import org.apache.gravitino.listener.api.event.GetFileLocationEvent;
import org.apache.gravitino.listener.api.event.GetFileLocationFailureEvent;
import org.apache.gravitino.listener.api.event.GetPartitionEvent;
@@ -107,6 +108,8 @@ import org.apache.gravitino.listener.api.event.PartitionExistsEvent;
import org.apache.gravitino.listener.api.event.PurgePartitionEvent;
import org.apache.gravitino.listener.api.event.PurgePartitionFailureEvent;
import org.apache.gravitino.listener.api.event.PurgeTableEvent;
+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
import org.apache.gravitino.listener.api.event.view.AlterViewEvent;
import org.apache.gravitino.listener.api.event.view.AlterViewFailureEvent;
import org.apache.gravitino.listener.api.event.view.CreateViewEvent;
@@ -588,6 +591,66 @@ public class TestOperation {
AuditLog.Operation.fromEvent(disableCatalogFailureEvent));
}
+ @Test
+ public void testAuthorizationDenialOperation() {
+ Event authzDenialEvent =
+ new AuthorizationDenialFailureEvent(
+ USER, catalogIdentifier, "listCatalogs", "CATALOG:LIST");
+ Assertions.assertEquals(
+ AuditLog.Operation.AUTHORIZATION_DENIAL, AuditLog.Operation.fromEvent(authzDenialEvent));
+
+ // null identifier variant (denial before resource resolution)
+ Event authzDenialNullIdentifier =
+ new AuthorizationDenialFailureEvent(USER, null, "loadTable", "TABLE:LOAD");
+ Assertions.assertEquals(
+ AuditLog.Operation.AUTHORIZATION_DENIAL,
+ AuditLog.Operation.fromEvent(authzDenialNullIdentifier));
+ }
+
+ @Test
+ public void testHttpRequestFailureEventMapsToUnknownOperation() {
+ // HttpRequestFailureEvent has no specific business operation — it always maps to UNKNOWN
+ Event httpFailureEvent =
+ new HttpRequestFailureEvent(
+ USER, "1.2.3.4", "GET", "/api/metalakes", 401, EventSource.GRAVITINO_SERVER);
+ Assertions.assertEquals(
+ AuditLog.Operation.UNKNOWN_OPERATION, AuditLog.Operation.fromEvent(httpFailureEvent));
+
+ // Verify the same holds for other status codes (400, 403, 404, 500)
+ for (int status : new int[] {400, 403, 404, 500}) {
+ Event e =
+ new HttpRequestFailureEvent(
+ USER, "1.2.3.4", "POST", "/api/metalakes", status, EventSource.GRAVITINO_SERVER);
+ Assertions.assertEquals(
+ AuditLog.Operation.UNKNOWN_OPERATION,
+ AuditLog.Operation.fromEvent(e),
+ "HttpRequestFailureEvent with status " + status + " must map to UNKNOWN_OPERATION");
+ }
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ public void testSimpleFormatterHandlesServerEvents() {
+ // Smoke-test the v1 SimpleFormatter with the two new server-event types to confirm it
+ // does not NPE on their identifier/customInfo and maps to the correct Operation values.
+ SimpleFormatter formatter = new SimpleFormatter();
+
+ HttpRequestFailureEvent httpEvent =
+ new HttpRequestFailureEvent(
+ USER, "1.2.3.4", "GET", "/api/metalakes", 401, EventSource.GRAVITINO_SERVER);
+ SimpleAuditLog httpLog = formatter.format(httpEvent);
+ Assertions.assertEquals(AuditLog.Operation.UNKNOWN_OPERATION, httpLog.operation());
+ Assertions.assertEquals(AuditLog.Status.FAILURE, httpLog.status());
+ Assertions.assertNull(httpLog.identifier());
+
+ AuthorizationDenialFailureEvent authzEvent =
+ new AuthorizationDenialFailureEvent(USER, catalogIdentifier, "loadTable", "TABLE:LOAD");
+ SimpleAuditLog authzLog = formatter.format(authzEvent);
+ Assertions.assertEquals(AuditLog.Operation.AUTHORIZATION_DENIAL, authzLog.operation());
+ Assertions.assertEquals(AuditLog.Status.FAILURE, authzLog.status());
+ Assertions.assertEquals(catalogIdentifier.toString(), authzLog.identifier());
+ }
+
@Test
public void testExistsOperation() {
Event partitionExistsEvent =
diff --git a/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java b/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java
index f66a13b178..cfc22861cf 100644
--- a/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java
+++ b/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java
@@ -185,6 +185,7 @@ public class TestCompatibilityUtils {
{OperationType.DROP_FUNCTION, Operation.DROP_FUNCTION},
{OperationType.LIST_FUNCTION, Operation.LIST_FUNCTION},
{OperationType.LIST_FUNCTION_INFOS, Operation.LIST_FUNCTION_INFOS},
+ {OperationType.AUTHORIZATION_DENIAL, Operation.AUTHORIZATION_DENIAL},
{OperationType.UNKNOWN, Operation.UNKNOWN_OPERATION},
{null, Operation.UNKNOWN_OPERATION}
};
diff --git a/core/src/test/java/org/apache/gravitino/audit/v2/TestSimpleAuditLogV2.java b/core/src/test/java/org/apache/gravitino/audit/v2/TestSimpleAuditLogV2.java
index e57f60c93e..233d28b009 100644
--- a/core/src/test/java/org/apache/gravitino/audit/v2/TestSimpleAuditLogV2.java
+++ b/core/src/test/java/org/apache/gravitino/audit/v2/TestSimpleAuditLogV2.java
@@ -31,6 +31,8 @@ import org.apache.gravitino.listener.api.event.ListSchemaEvent;
import org.apache.gravitino.listener.api.event.ListTableEvent;
import org.apache.gravitino.listener.api.event.OperationStatus;
import org.apache.gravitino.listener.api.event.OperationType;
+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -217,6 +219,61 @@ public class TestSimpleAuditLogV2 {
Assertions.assertEquals("", fields[7]);
}
+ // ---- server event tests ----
+
+ @Test
+ public void testHttpRequestFailureEventFormat() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", "203.0.113.5", "GET", "/api/metalakes", 401, EventSource.GRAVITINO_SERVER);
+ SimpleAuditLogV2 log = new SimpleAuditLogV2(event);
+
+ Assertions.assertEquals("alice", log.user());
+ Assertions.assertEquals(OperationType.UNKNOWN, log.operationType());
+ Assertions.assertEquals(OperationStatus.FAILURE, log.operationStatus());
+ Assertions.assertNull(log.identifier());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, log.eventSource());
+ Assertions.assertEquals("203.0.113.5", log.remoteAddress());
+
+ String[] fields = log.toString().split("\t", -1);
+ Assertions.assertEquals(8, fields.length);
+ Assertions.assertEquals("alice", fields[1]);
+ Assertions.assertEquals("UNKNOWN", fields[2]);
+ Assertions.assertEquals("null", fields[3]);
+ Assertions.assertEquals("FAILURE", fields[4]);
+ Assertions.assertEquals("GRAVITINO_SERVER", fields[5]);
+ Assertions.assertEquals("203.0.113.5", fields[6]);
+ // customInfo contains http.method, http.uri, http.status
+ Assertions.assertTrue(fields[7].contains("http.method=GET"), fields[7]);
+ Assertions.assertTrue(fields[7].contains("http.uri=/api/metalakes"), fields[7]);
+ Assertions.assertTrue(fields[7].contains("http.status=401"), fields[7]);
+ }
+
+ @Test
+ public void testAuthorizationDenialFailureEventFormat() {
+ NameIdentifier resource = NameIdentifier.of("metalake", "catalog");
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("bob", resource, "listCatalogs", "CATALOG:LIST");
+ SimpleAuditLogV2 log = new SimpleAuditLogV2(event);
+
+ Assertions.assertEquals("bob", log.user());
+ Assertions.assertEquals(OperationType.AUTHORIZATION_DENIAL, log.operationType());
+ Assertions.assertEquals(OperationStatus.FAILURE, log.operationStatus());
+ Assertions.assertEquals("metalake.catalog", log.identifier());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, log.eventSource());
+
+ String[] fields = log.toString().split("\t", -1);
+ Assertions.assertEquals(8, fields.length);
+ Assertions.assertEquals("bob", fields[1]);
+ Assertions.assertEquals("AUTHORIZATION_DENIAL", fields[2]);
+ Assertions.assertEquals("metalake.catalog", fields[3]);
+ Assertions.assertEquals("FAILURE", fields[4]);
+ Assertions.assertEquals("GRAVITINO_SERVER", fields[5]);
+ // customInfo contains auth.method and auth.expression
+ Assertions.assertTrue(fields[7].contains("auth.method=listCatalogs"), fields[7]);
+ Assertions.assertTrue(fields[7].contains("auth.expression=CATALOG:LIST"), fields[7]);
+ }
+
// ---- stubs ----
static class StubEvent extends Event {
diff --git a/core/src/test/java/org/apache/gravitino/listener/TestEventBus.java b/core/src/test/java/org/apache/gravitino/listener/TestEventBus.java
index cd8c5ac111..a1b5c5ae0f 100644
--- a/core/src/test/java/org/apache/gravitino/listener/TestEventBus.java
+++ b/core/src/test/java/org/apache/gravitino/listener/TestEventBus.java
@@ -25,9 +25,13 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.listener.api.EventListenerPlugin;
import org.apache.gravitino.listener.api.event.Event;
+import org.apache.gravitino.listener.api.event.EventSource;
import org.apache.gravitino.listener.api.event.FailureEvent;
import org.apache.gravitino.listener.api.event.OperationStatus;
import org.apache.gravitino.listener.api.event.PreEvent;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
+import org.apache.gravitino.utils.RequestContext;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -94,6 +98,48 @@ public class TestEventBus {
Assertions.assertThrows(RuntimeException.class, () -> eventBus.dispatchEvent(postEvent));
}
+ @AfterEach
+ void clearRequestContext() {
+ RequestContext.resetOperationFailureFired();
+ RequestContext.clear();
+ }
+
+ // ─── operationFailureFired flag marking ──────────────────────────────────────
+
+ @Test
+ void testOperationLayerFailureEventSetsOperationFailureFiredFlag() {
+ EventBus eventBus = new EventBus(Collections.emptyList());
+ // Any FailureEvent that is not an HttpRequestFailureEvent should set the flag
+ Event failureEvent =
+ new FailureEvent("user", NameIdentifier.of("test"), new Exception("op error")) {
+ @Override
+ public OperationStatus operationStatus() {
+ return OperationStatus.FAILURE;
+ }
+ };
+
+ Assertions.assertFalse(RequestContext.isOperationFailureFired(), "Flag must start as false");
+ eventBus.dispatchEvent(failureEvent);
+ Assertions.assertTrue(
+ RequestContext.isOperationFailureFired(),
+ "Flag must be set after dispatching an operation-layer failure event");
+ }
+
+ @Test
+ void testHttpRequestFailureEventDoesNotSetOperationFailureFiredFlag() {
+ EventBus eventBus = new EventBus(Collections.emptyList());
+ HttpRequestFailureEvent httpEvent =
+ new HttpRequestFailureEvent(
+ "alice", "1.2.3.4", "GET", "/api/metalakes", 401, EventSource.GRAVITINO_SERVER);
+
+ eventBus.dispatchEvent(httpEvent);
+
+ Assertions.assertFalse(
+ RequestContext.isOperationFailureFired(),
+ "Flag must NOT be set when dispatching HttpRequestFailureEvent — "
+ + "it is the HTTP-layer event and must not suppress itself");
+ }
+
static class ThrowingEventListener implements EventListenerPlugin {
private final RuntimeException exceptionToThrow;
diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/server/TestAuthorizationDenialFailureEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/server/TestAuthorizationDenialFailureEvent.java
new file mode 100644
index 0000000000..b91696fc4d
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/server/TestAuthorizationDenialFailureEvent.java
@@ -0,0 +1,103 @@
+/*
+ * 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.gravitino.listener.api.event.server;
+
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.OperationType;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestAuthorizationDenialFailureEvent {
+
+ private static final NameIdentifier TABLE_IDENT =
+ NameIdentifier.of("metalake1", "catalog1", "schema1", "table1");
+
+ @Test
+ public void testFieldsStoredCorrectly() {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", TABLE_IDENT, "loadTable", "TABLE:LOAD");
+
+ Assertions.assertEquals("alice", event.user());
+ Assertions.assertEquals(TABLE_IDENT, event.identifier());
+ Assertions.assertEquals("loadTable", event.methodName());
+ Assertions.assertEquals("TABLE:LOAD", event.expression());
+ }
+
+ @Test
+ public void testOperationTypeIsAuthorizationDenial() {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", TABLE_IDENT, "loadTable", "TABLE:LOAD");
+
+ Assertions.assertEquals(OperationType.AUTHORIZATION_DENIAL, event.operationType());
+ }
+
+ @Test
+ public void testEventSourceIsGravitinoServer() {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", TABLE_IDENT, "loadTable", "TABLE:LOAD");
+
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, event.eventSource());
+ }
+
+ @Test
+ public void testCustomInfoContainsAuthFields() {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", TABLE_IDENT, "loadTable", "TABLE:LOAD");
+
+ Map<String, String> info = event.customInfo();
+ Assertions.assertEquals("loadTable", info.get("auth.method"));
+ Assertions.assertEquals("TABLE:LOAD", info.get("auth.expression"));
+ // resource name must NOT be duplicated in customInfo — it is in identifier()
+ Assertions.assertFalse(info.containsKey("auth.resource"));
+ }
+
+ @Test
+ public void testNullExpressionNormalisedToEmptyString() {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", TABLE_IDENT, "loadTable", null);
+
+ Assertions.assertEquals("", event.expression());
+ Assertions.assertEquals("", event.customInfo().get("auth.expression"));
+ }
+
+ @Test
+ public void testNullIdentifierAllowed() {
+ // Denial can occur before the resource identifier is resolved (e.g. metalake user validation)
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", null, "checkCurrentUser", "");
+
+ Assertions.assertNull(event.identifier());
+ Assertions.assertEquals("checkCurrentUser", event.methodName());
+ }
+
+ @Test
+ public void testExceptionCarriesUserAndMethodContext() {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent("alice", TABLE_IDENT, "loadTable", "TABLE:LOAD");
+
+ String message = event.exception().getMessage();
+ Assertions.assertTrue(
+ message.contains("alice"), "Exception message must reference the denied user");
+ Assertions.assertTrue(
+ message.contains("loadTable"), "Exception message must reference the denied operation");
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/server/TestHttpRequestFailureEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/server/TestHttpRequestFailureEvent.java
new file mode 100644
index 0000000000..c70dd08501
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/server/TestHttpRequestFailureEvent.java
@@ -0,0 +1,132 @@
+/*
+ * 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.gravitino.listener.api.event.server;
+
+import java.util.Map;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.OperationType;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestHttpRequestFailureEvent {
+
+ @Test
+ public void testFieldsStoredCorrectly() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", "203.0.113.5", "POST", "/api/metalakes", 401, EventSource.GRAVITINO_SERVER);
+
+ Assertions.assertEquals("alice", event.user());
+ Assertions.assertEquals("203.0.113.5", event.remoteAddress());
+ Assertions.assertEquals("POST", event.httpMethod());
+ Assertions.assertEquals("/api/metalakes", event.requestUri());
+ Assertions.assertEquals(401, event.statusCode());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, event.eventSource());
+ }
+
+ @Test
+ public void testOperationTypeIsAlwaysUnknown() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", "1.2.3.4", "GET", "/api/metalakes", 404, EventSource.GRAVITINO_SERVER);
+
+ Assertions.assertEquals(OperationType.UNKNOWN, event.operationType());
+ }
+
+ @Test
+ public void testIdentifierIsNull() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", "1.2.3.4", "GET", "/unknown", 404, EventSource.GRAVITINO_SERVER);
+
+ Assertions.assertNull(event.identifier());
+ }
+
+ @Test
+ public void testCustomInfoContainsHttpFields() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "bob", "10.0.0.1", "DELETE", "/api/metalakes/m1", 403, EventSource.GRAVITINO_SERVER);
+
+ Map<String, String> info = event.customInfo();
+ Assertions.assertEquals("DELETE", info.get("http.method"));
+ Assertions.assertEquals("/api/metalakes/m1", info.get("http.uri"));
+ Assertions.assertEquals("403", info.get("http.status"));
+ }
+
+ @Test
+ public void testNullRemoteAddressFallsBackToUnknown() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", null, "GET", "/api/metalakes", 401, EventSource.GRAVITINO_SERVER);
+
+ Assertions.assertEquals("unknown", event.remoteAddress());
+ }
+
+ @Test
+ public void testExceptionMessageContainsHttpContext() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", "1.2.3.4", "POST", "/api/metalakes", 400, EventSource.GRAVITINO_SERVER);
+
+ String message = event.exception().getMessage();
+ Assertions.assertTrue(message.contains("POST"), "Exception message must contain HTTP method");
+ Assertions.assertTrue(
+ message.contains("/api/metalakes"), "Exception message must contain request URI");
+ Assertions.assertTrue(message.contains("400"), "Exception message must contain status code");
+ }
+
+ @Test
+ public void testExceptionHasNoStackTrace() {
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ "alice", "1.2.3.4", "GET", "/api", 404, EventSource.GRAVITINO_SERVER);
+
+ Assertions.assertEquals(
+ 0,
+ event.exception().getStackTrace().length,
+ "HttpRequestException must suppress stack trace to avoid overhead");
+ }
+
+ @Test
+ public void testEventSourcePropagated() {
+ HttpRequestFailureEvent icebergEvent =
+ new HttpRequestFailureEvent(
+ "alice",
+ "1.2.3.4",
+ "GET",
+ "/iceberg/namespaces",
+ 404,
+ EventSource.GRAVITINO_ICEBERG_REST_SERVER);
+
+ Assertions.assertEquals(EventSource.GRAVITINO_ICEBERG_REST_SERVER, icebergEvent.eventSource());
+
+ HttpRequestFailureEvent lanceEvent =
+ new HttpRequestFailureEvent(
+ "alice",
+ "1.2.3.4",
+ "GET",
+ "/lance/namespaces",
+ 404,
+ EventSource.GRAVITINO_LANCE_REST_SERVER);
+
+ Assertions.assertEquals(EventSource.GRAVITINO_LANCE_REST_SERVER, lanceEvent.eventSource());
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java
index d536d01cd2..7e37b184cb 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java
@@ -31,6 +31,7 @@ import org.apache.gravitino.iceberg.common.IcebergConfig;
import org.apache.gravitino.iceberg.service.IcebergAuthenticationFilter;
import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergHealthCheckPathMatcher;
import org.apache.gravitino.iceberg.service.IcebergObjectMapperProvider;
import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
import org.apache.gravitino.iceberg.service.cleanup.IcebergCleanupJobStore;
@@ -51,9 +52,11 @@ import org.apache.gravitino.iceberg.service.metrics.IcebergMetricsManager;
import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;
import org.apache.gravitino.iceberg.service.provider.IcebergConfigProviderFactory;
import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.api.event.EventSource;
import org.apache.gravitino.metrics.MetricsSystem;
import org.apache.gravitino.metrics.source.MetricsSource;
import org.apache.gravitino.server.web.HealthAliasServlet;
+import org.apache.gravitino.server.web.HttpAuditFilter;
import org.apache.gravitino.server.web.HttpServerMetricsSource;
import org.apache.gravitino.server.web.JettyServer;
import org.apache.gravitino.server.web.JettyServerConfig;
@@ -201,6 +204,12 @@ public class RESTService implements GravitinoAuxiliaryService {
Servlet servlet = new ServletContainer(config);
server.addServlet(servlet, ICEBERG_SPEC);
+ server.addFilter(
+ new HttpAuditFilter(
+ eventBus,
+ EventSource.GRAVITINO_ICEBERG_REST_SERVER,
+ new IcebergHealthCheckPathMatcher()),
+ ICEBERG_SPEC);
server.addCustomFilters(ICEBERG_SPEC);
server.addSystemFilters(ICEBERG_SPEC);
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergAuthenticationFilter.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergAuthenticationFilter.java
index fa6ee8561c..68dfa7f830 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergAuthenticationFilter.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergAuthenticationFilter.java
@@ -21,8 +21,6 @@ package org.apache.gravitino.iceberg.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import javax.servlet.ServletRequest;
-import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.server.authentication.AuthenticationFilter;
@@ -42,14 +40,8 @@ public class IcebergAuthenticationFilter extends AuthenticationFilter {
private static final ObjectMapper MAPPER = IcebergObjectMapper.getInstance();
- @Override
- protected boolean isHealthCheckRequest(ServletRequest request) {
- if (super.isHealthCheckRequest(request)) {
- return true;
- }
-
- String path = ((HttpServletRequest) request).getRequestURI();
- return path.equals("/iceberg/health") || path.startsWith("/iceberg/health/");
+ public IcebergAuthenticationFilter() {
+ healthCheckMatcher = new IcebergHealthCheckPathMatcher();
}
@Override
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergHealthCheckPathMatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergHealthCheckPathMatcher.java
new file mode 100644
index 0000000000..49357b987c
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergHealthCheckPathMatcher.java
@@ -0,0 +1,44 @@
+/*
+ * 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.gravitino.iceberg.service;
+
+import org.apache.gravitino.server.web.HealthCheckPathMatcher;
+
+/**
+ * A {@link HealthCheckPathMatcher} for the Iceberg REST server that additionally recognises {@code
+ * /iceberg/health} and {@code /iceberg/health/*} as health check endpoints.
+ *
+ * <p>Pass an instance of this class to both {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (via {@code
+ * IcebergAuthenticationFilter}) and {@link org.apache.gravitino.server.web.HttpAuditFilter} when
+ * constructing the Iceberg REST server so that both filters agree on which paths are probe traffic.
+ */
+public class IcebergHealthCheckPathMatcher extends HealthCheckPathMatcher {
+
+ @Override
+ public boolean isHealthCheckPath(String path) {
+ if (super.isHealthCheckPath(path)) {
+ return true;
+ }
+ if (path == null) {
+ return false;
+ }
+ return path.equals("/iceberg/health") || path.startsWith("/iceberg/health/");
+ }
+}
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/LanceRESTService.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/LanceRESTService.java
index 62673e994c..407350c000 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/LanceRESTService.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/LanceRESTService.java
@@ -28,8 +28,11 @@ import org.apache.gravitino.auxiliary.GravitinoAuxiliaryService;
import org.apache.gravitino.lance.common.config.LanceConfig;
import org.apache.gravitino.lance.common.ops.LanceNamespaceBackend;
import org.apache.gravitino.lance.common.ops.NamespaceWrapper;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.api.event.EventSource;
import org.apache.gravitino.metrics.MetricsSystem;
import org.apache.gravitino.metrics.source.MetricsSource;
+import org.apache.gravitino.server.web.HttpAuditFilter;
import org.apache.gravitino.server.web.HttpServerMetricsSource;
import org.apache.gravitino.server.web.JettyServer;
import org.apache.gravitino.server.web.JettyServerConfig;
@@ -64,8 +67,9 @@ public class LanceRESTService implements GravitinoAuxiliaryService {
JettyServerConfig serverConfig = JettyServerConfig.fromConfig(lanceConfig);
server = new JettyServer();
- // Get MetricsSystem directly from GravitinoEnv for zero-overhead access
+ // Get MetricsSystem and EventBus from GravitinoEnv once at init time.
MetricsSystem metricsSystem = GravitinoEnv.getInstance().metricsSystem();
+ EventBus eventBus = GravitinoEnv.getInstance().eventBus();
server.initialize(serverConfig, SERVICE_NAME, false);
this.lanceNamespace = loadNamespaceImpl(lanceConfig);
@@ -89,6 +93,8 @@ public class LanceRESTService implements GravitinoAuxiliaryService {
Servlet container = new ServletContainer(resourceConfig);
server.addServlet(container, LANCE_SPEC);
+ server.addFilter(
+ new HttpAuditFilter(eventBus, EventSource.GRAVITINO_LANCE_REST_SERVER), LANCE_SPEC);
server.addCustomFilters(LANCE_SPEC);
server.addSystemFilters(LANCE_SPEC);
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java
index e2a1ac9245..bf4bbba784 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java
@@ -36,6 +36,7 @@ import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.UnauthorizedException;
+import org.apache.gravitino.server.web.HealthCheckPathMatcher;
import org.apache.gravitino.server.web.ObjectMapperProvider;
import org.apache.gravitino.utils.PrincipalUtils;
@@ -43,6 +44,12 @@ public class AuthenticationFilter implements Filter {
private final List<Authenticator> filterAuthenticators;
+ /**
+ * The matcher used to identify health check paths that bypass authentication. Subclasses may
+ * replace this with a server-specific matcher (e.g. {@code IcebergHealthCheckPathMatcher}).
+ */
+ protected HealthCheckPathMatcher healthCheckMatcher = new HealthCheckPathMatcher();
+
public AuthenticationFilter() {
filterAuthenticators = null;
}
@@ -150,7 +157,7 @@ public class AuthenticationFilter implements Filter {
/**
* Returns {@code true} if the request targets a health check endpoint that should bypass
- * authentication. Subclasses may override this to add additional bypass paths.
+ * authentication, as determined by the configured {@link #healthCheckMatcher}.
*
* @param request the incoming servlet request
* @return {@code true} if the request should skip authentication
@@ -159,17 +166,7 @@ public class AuthenticationFilter implements Filter {
if (!(request instanceof HttpServletRequest)) {
return false;
}
- String path = ((HttpServletRequest) request).getRequestURI();
- if (path == null) {
- return false;
- }
- // Also match /health, /health/*, and /health.html — root-level aliases that forward to
- // /api/health/*. During a forward, getRequestURI() returns the original URI, not the target.
- return path.equals("/health")
- || path.startsWith("/health/")
- || path.equals("/health.html")
- || path.equals("/api/health")
- || path.startsWith("/api/health/");
+ return healthCheckMatcher.isHealthCheckPath(((HttpServletRequest) request).getRequestURI());
}
@Override
diff --git a/server-common/src/main/java/org/apache/gravitino/server/web/HealthCheckPathMatcher.java b/server-common/src/main/java/org/apache/gravitino/server/web/HealthCheckPathMatcher.java
new file mode 100644
index 0000000000..d6db695faf
--- /dev/null
+++ b/server-common/src/main/java/org/apache/gravitino/server/web/HealthCheckPathMatcher.java
@@ -0,0 +1,61 @@
+/*
+ * 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.gravitino.server.web;
+
+/**
+ * Determines whether a URI path targets a health check endpoint.
+ *
+ * <p>The base implementation covers the canonical Gravitino health paths ({@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, {@code /api/health/*}). Server-specific
+ * subclasses (e.g. {@code IcebergHealthCheckPathMatcher}) extend this class to add additional
+ * health endpoints served by their respective REST servers.
+ *
+ * <p>Both {@link org.apache.gravitino.server.authentication.AuthenticationFilter} (to bypass
+ * authentication for probe traffic) and {@link HttpAuditFilter} (to skip audit logging for probe
+ * traffic) use an instance of this class. Passing the same subclass instance to both filters on a
+ * given server ensures they agree on which paths are health checks.
+ */
+public class HealthCheckPathMatcher {
+
+ /**
+ * Returns {@code true} if {@code path} targets a Gravitino health check endpoint.
+ *
+ * <p>Covers the canonical API path ({@code /api/health} and {@code /api/health/*}) and the
+ * root-level aliases ({@code /health}, {@code /health/*}, {@code /health.html}) that forward to
+ * the canonical paths. During a {@link javax.servlet.RequestDispatcher} forward, {@code
+ * getRequestURI()} returns the original URI rather than the target, so these aliases must be
+ * included here.
+ *
+ * <p>Subclasses should override this method and call {@code super.isHealthCheckPath(path)} first
+ * to preserve the base paths.
+ *
+ * @param path the URI path to test; may be {@code null}
+ * @return {@code true} if {@code path} is a health check endpoint
+ */
+ public boolean isHealthCheckPath(String path) {
+ if (path == null) {
+ return false;
+ }
+ return path.equals("/health")
+ || path.startsWith("/health/")
+ || path.equals("/health.html")
+ || path.equals("/api/health")
+ || path.startsWith("/api/health/");
+ }
+}
diff --git a/server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java b/server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java
new file mode 100644
index 0000000000..6f6d53202f
--- /dev/null
+++ b/server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java
@@ -0,0 +1,310 @@
+/*
+ * 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.gravitino.server.web;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import javax.servlet.DispatcherType;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.auth.AuthConstants;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
+import org.apache.gravitino.utils.RequestContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A servlet filter that emits an {@link HttpRequestFailureEvent} for every HTTP request that
+ * completes with a 4xx or 5xx status code and for which no operation-layer failure event was
+ * already dispatched on the same request thread.
+ *
+ * <p><strong>Filter chain position:</strong> this filter must be registered <em>after</em> {@link
+ * RequestContextFilter} (so the remote address is already populated) but <em>before</em> both
+ * custom filters and {@link org.apache.gravitino.server.authentication.AuthenticationFilter} (so it
+ * wraps every downstream filter and observes 401 authentication failures, custom-filter 403s, and
+ * other downstream 4xx/5xx responses). It is safe to install on servers that do not use {@code
+ * RequestContextFilter} (Iceberg REST, Lance REST) because it resolves the client address
+ * independently.
+ *
+ * <p><strong>DispatcherType.ERROR skip:</strong> when an uncaught exception escapes the filter
+ * chain, this filter fires an {@link HttpRequestFailureEvent} (status 500) in its {@code finally}
+ * block, then re-throws. The servlet container (Jetty) may subsequently re-invoke the filter chain
+ * with {@link DispatcherType#ERROR} to render an error page. This filter detects that case and
+ * passes the request straight through without emitting a second event, preventing double-logging.
+ *
+ * <p><strong>Double-logging prevention:</strong> when an operation-layer failure event (e.g. {@code
+ * LoadTableFailureEvent}, {@code AuthorizationDenialFailureEvent}) has already been dispatched via
+ * {@link EventBus}, {@link RequestContext#markOperationFailureFired()} is set on the request
+ * thread. This filter checks that flag in the {@code finally} block and skips emitting its own
+ * {@link HttpRequestFailureEvent} if the flag is set.
+ *
+ * <p><strong>Success + 5xx edge case:</strong> if an operation dispatcher emits a {@code
+ * SuccessEvent} (flag not set) but the HTTP layer subsequently fails with a 5xx (e.g. JSON
+ * serialization error), this filter will emit an {@link HttpRequestFailureEvent} in addition to the
+ * success event already in the audit log. Both entries are correct — the operation itself succeeded
+ * but the response delivery failed — and are intentionally preserved.
+ *
+ * <p><strong>Health check exclusion:</strong> requests matched by the configured {@link
+ * HealthCheckPathMatcher} are silently passed through without audit logging to avoid polluting the
+ * audit log with probe traffic. Pass a server-specific subclass (e.g. {@code
+ * IcebergHealthCheckPathMatcher}) when constructing this filter for a server that defines
+ * additional health endpoints.
+ *
+ * <p><strong>Exception escape:</strong> if an uncaught {@link Throwable} escapes from the filter
+ * chain and the captured status is still 200 (i.e. no downstream component set an error code), the
+ * captured status is promoted to 500 before the {@code finally} block runs, ensuring that the audit
+ * event reflects the actual error condition.
+ */
+public class HttpAuditFilter implements Filter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HttpAuditFilter.class);
+ private static final String X_FORWARDED_FOR = "X-Forwarded-For";
+
+ private final Optional<EventBus> eventBus;
+ private final EventSource eventSource;
+ private final HealthCheckPathMatcher healthCheckMatcher;
+
+ /**
+ * Constructs an {@code HttpAuditFilter} using the default {@link HealthCheckPathMatcher}.
+ *
+ * @param eventBus the event bus used to dispatch {@link HttpRequestFailureEvent}s; may be {@code
+ * null}, in which case the filter is a pass-through no-op (useful when no audit listener is
+ * configured).
+ * @param eventSource identifies which server this filter instance is installed on; included in
+ * every emitted {@link HttpRequestFailureEvent}.
+ */
+ public HttpAuditFilter(@Nullable EventBus eventBus, EventSource eventSource) {
+ this(eventBus, eventSource, new HealthCheckPathMatcher());
+ }
+
+ /**
+ * Constructs an {@code HttpAuditFilter} with a custom {@link HealthCheckPathMatcher}.
+ *
+ * @param eventBus the event bus used to dispatch {@link HttpRequestFailureEvent}s; may be {@code
+ * null}, in which case the filter is a pass-through no-op.
+ * @param eventSource identifies which server this filter instance is installed on.
+ * @param healthCheckMatcher determines which URI paths are health check probes; those paths are
+ * excluded from audit logging to avoid polluting the audit log with probe traffic.
+ */
+ public HttpAuditFilter(
+ @Nullable EventBus eventBus,
+ EventSource eventSource,
+ HealthCheckPathMatcher healthCheckMatcher) {
+ this.eventBus = Optional.ofNullable(eventBus);
+ this.eventSource = eventSource;
+ this.healthCheckMatcher = healthCheckMatcher;
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) {}
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ // Pass through when audit is not configured or request is not HTTP.
+ if (eventBus.isEmpty() || !(request instanceof HttpServletRequest)) {
+ chain.doFilter(request, response);
+ return;
+ }
+
+ HttpServletRequest httpRequest = (HttpServletRequest) request;
+ // Skip ERROR dispatches: after an uncaught exception, Jetty may re-invoke the filter chain
+ // with DispatcherType.ERROR to render an error page. The original REQUEST dispatch already
+ // fired an audit event (promoted to 500), so passing through here prevents double-logging.
+ if (httpRequest.getDispatcherType() == DispatcherType.ERROR) {
+ chain.doFilter(request, response);
+ return;
+ }
+ // Defensive cleanup at request entry in case a pooled thread leaked stale state.
+ RequestContext.resetOperationFailureFired();
+ if (healthCheckMatcher.isHealthCheckPath(httpRequest.getRequestURI())) {
+ try {
+ chain.doFilter(request, response);
+ } finally {
+ RequestContext.resetOperationFailureFired();
+ }
+ return;
+ }
+
+ StatusCapturingResponseWrapper wrappedResponse =
+ new StatusCapturingResponseWrapper((HttpServletResponse) response);
+ Throwable chainException = null;
+ try {
+ chain.doFilter(httpRequest, wrappedResponse);
+ } catch (Throwable t) {
+ chainException = t;
+ // Promote to 500 so the finally block emits an event for this escaped exception.
+ if (wrappedResponse.getCapturedStatus() < 400) {
+ wrappedResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ } finally {
+ try {
+ if (!RequestContext.isOperationFailureFired()) {
+ int status = wrappedResponse.getCapturedStatus();
+ if (status >= 400) {
+ String user = resolveUser(httpRequest);
+ String remoteAddress = resolveClientAddress(httpRequest);
+ HttpRequestFailureEvent event =
+ new HttpRequestFailureEvent(
+ user,
+ remoteAddress,
+ httpRequest.getMethod(),
+ httpRequest.getRequestURI(),
+ status,
+ eventSource);
+ eventBus.get().dispatchEvent(event);
+ }
+ }
+ } catch (Exception e) {
+ LOG.error(
+ "Failed to dispatch HTTP audit event for {} {}",
+ httpRequest.getMethod(),
+ httpRequest.getRequestURI(),
+ e);
+ } finally {
+ // Always clear the flag to prevent ThreadLocal leaks across pooled threads.
+ RequestContext.resetOperationFailureFired();
+ }
+ }
+
+ // Re-throw any exception that escaped the chain after cleanup is complete.
+ if (chainException instanceof Error) {
+ throw (Error) chainException;
+ } else if (chainException instanceof RuntimeException) {
+ throw (RuntimeException) chainException;
+ } else if (chainException instanceof IOException) {
+ throw (IOException) chainException;
+ } else if (chainException instanceof ServletException) {
+ throw (ServletException) chainException;
+ } else if (chainException != null) {
+ throw new ServletException(chainException);
+ }
+ }
+
+ @Override
+ public void destroy() {}
+
+ private String resolveUser(HttpServletRequest request) {
+ Object principalObj =
+ request.getAttribute(AuthConstants.AUTHENTICATED_PRINCIPAL_ATTRIBUTE_NAME);
+ if (principalObj instanceof Principal) {
+ return ((Principal) principalObj).getName();
+ }
+ // The attribute is only set when authentication succeeds (AuthenticationFilter calls
+ // request.setAttribute before chain.doFilter). Absent attribute means auth was rejected
+ // before any principal was established. PrincipalUtils.getCurrentUserName() must not be used
+ // here — it returns "anonymous" when no Subject.doAs is active, making a rejected request
+ // indistinguishable from a legitimately anonymous one. Returns "unknown" instead.
+ return "unknown";
+ }
+
+ private String resolveClientAddress(HttpServletRequest request) {
+ // Prefer the address already resolved by RequestContextFilter (installed on GravitinoServer).
+ // For servers that do not install RequestContextFilter (Iceberg REST, Lance REST), fall back to
+ // independent header parsing so the event still carries a meaningful client address.
+ String contextAddress = RequestContext.getRemoteAddress();
+ if (contextAddress != null) {
+ return contextAddress;
+ }
+ String xForwardedFor = request.getHeader(X_FORWARDED_FOR);
+ if (StringUtils.isNotBlank(xForwardedFor)) {
+ return xForwardedFor.split(",")[0].trim();
+ }
+ return request.getRemoteAddr();
+ }
+
+ /**
+ * A {@link HttpServletResponseWrapper} that intercepts all status-code-setting methods so that
+ * the final HTTP status is available after {@link FilterChain#doFilter} returns.
+ *
+ * <p>All five status-mutating entry points are overridden: {@link #setStatus(int)}, {@link
+ * #setStatus(int, String)}, {@link #sendError(int)}, {@link #sendError(int, String)}, and {@link
+ * #reset()} (which resets the captured status back to 200).
+ */
+ static final class StatusCapturingResponseWrapper extends HttpServletResponseWrapper {
+
+ private int capturedStatus = HttpServletResponse.SC_OK;
+
+ /**
+ * Constructs a wrapper around the given response.
+ *
+ * @param response the underlying HTTP response to delegate to
+ */
+ StatusCapturingResponseWrapper(HttpServletResponse response) {
+ super(response);
+ }
+
+ /**
+ * Returns the last HTTP status code recorded on this response. Defaults to {@code 200} if no
+ * status-mutating method has been called.
+ *
+ * @return the captured HTTP status code
+ */
+ int getCapturedStatus() {
+ return capturedStatus;
+ }
+
+ @Override
+ public void setStatus(int sc) {
+ capturedStatus = sc;
+ super.setStatus(sc);
+ }
+
+ @Override
+ @SuppressWarnings("deprecation")
+ public void setStatus(int sc, String sm) {
+ capturedStatus = sc;
+ super.setStatus(sc, sm);
+ }
+
+ @Override
+ public void sendError(int sc) throws IOException {
+ capturedStatus = sc;
+ super.sendError(sc);
+ }
+
+ @Override
+ public void sendError(int sc, String msg) throws IOException {
+ capturedStatus = sc;
+ super.sendError(sc, msg);
+ }
+
+ /**
+ * Resets the captured status to {@code 200} in addition to delegating to the wrapped response.
+ */
+ @Override
+ public void reset() {
+ capturedStatus = HttpServletResponse.SC_OK;
+ super.reset();
+ }
+ }
+}
diff --git a/server-common/src/test/java/org/apache/gravitino/server/web/TestHttpAuditFilter.java b/server-common/src/test/java/org/apache/gravitino/server/web/TestHttpAuditFilter.java
new file mode 100644
index 0000000000..5cd2c651bf
--- /dev/null
+++ b/server-common/src/test/java/org/apache/gravitino/server/web/TestHttpAuditFilter.java
@@ -0,0 +1,494 @@
+/*
+ * 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.gravitino.server.web;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.security.Principal;
+import javax.servlet.DispatcherType;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.gravitino.auth.AuthConstants;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.api.event.BaseEvent;
+import org.apache.gravitino.listener.api.event.EventSource;
+import org.apache.gravitino.listener.api.event.server.HttpRequestFailureEvent;
+import org.apache.gravitino.utils.RequestContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+public class TestHttpAuditFilter {
+
+ @AfterEach
+ public void cleanup() {
+ RequestContext.resetOperationFailureFired();
+ RequestContext.clear();
+ }
+
+ // ─── Null EventBus ───────────────────────────────────────────────────────────
+
+ @Test
+ public void testNullEventBusPassThrough() throws Exception {
+ HttpAuditFilter filter = new HttpAuditFilter(null, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "1.2.3.4");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = mock(FilterChain.class);
+
+ filter.doFilter(req, resp, chain);
+
+ verify(chain).doFilter(req, resp);
+ }
+
+ // ─── DispatcherType.ERROR pass-through ──────────────────────────────────────
+
+ @Test
+ public void testErrorDispatchTypePassesThrough() throws Exception {
+ // After an uncaught exception escapes the chain, Jetty may re-invoke the filter chain with
+ // DispatcherType.ERROR to render an error page. The original REQUEST dispatch already fired an
+ // audit event (promoted to 500). The filter must pass through silently here to avoid a second
+ // event for the same logical failure.
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "1.2.3.4");
+ when(req.getDispatcherType()).thenReturn(DispatcherType.ERROR);
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = mock(FilterChain.class);
+
+ filter.doFilter(req, resp, chain);
+
+ verify(eventBus, never()).dispatchEvent(any());
+ verify(chain).doFilter(req, resp);
+ }
+
+ // ─── Non-HTTP request ────────────────────────────────────────────────────────
+
+ @Test
+ public void testNonHttpRequestPassThrough() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ ServletRequest req = mock(ServletRequest.class);
+ ServletResponse resp = mock(ServletResponse.class);
+ FilterChain chain = mock(FilterChain.class);
+
+ filter.doFilter(req, resp, chain);
+
+ verify(chain).doFilter(req, resp);
+ verify(eventBus, never()).dispatchEvent(any());
+ }
+
+ // ─── Health check bypass ─────────────────────────────────────────────────────
+
+ @Test
+ public void testHealthCheckPathsSkipped() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+
+ for (String path :
+ new String[] {
+ "/health", "/health/live", "/health.html", "/api/health", "/api/health/ready"
+ }) {
+ HttpServletRequest req = mockRequest("GET", path, null, "1.2.3.4");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = mock(FilterChain.class);
+
+ filter.doFilter(req, resp, chain);
+
+ verify(chain).doFilter(req, resp);
+ }
+
+ verify(eventBus, never()).dispatchEvent(any());
+ }
+
+ // ─── Successful 200 — no event ───────────────────────────────────────────────
+
+ @Test
+ public void test200ResponseNoEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "1.2.3.4");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).setStatus(200);
+
+ filter.doFilter(req, resp, chain);
+
+ verify(eventBus, never()).dispatchEvent(any());
+ }
+
+ // ─── 4xx via sendError ───────────────────────────────────────────────────────
+
+ @Test
+ public void test401SendErrorEmitsEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("POST", "/api/metalakes", null, "10.0.0.1");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> ((HttpServletResponse) response).sendError(401, "Unauthorized");
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ Assertions.assertInstanceOf(HttpRequestFailureEvent.class, captor.getValue());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals(401, event.statusCode());
+ Assertions.assertEquals("POST", event.httpMethod());
+ Assertions.assertEquals("/api/metalakes", event.requestUri());
+ Assertions.assertEquals(EventSource.GRAVITINO_SERVER, event.eventSource());
+ }
+
+ @Test
+ public void test404SetStatusEmitsEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/unknown-route", null, "2.2.2.2");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).setStatus(404);
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals(404, event.statusCode());
+ Assertions.assertEquals("GET", event.httpMethod());
+ }
+
+ // ─── Double-logging prevention ───────────────────────────────────────────────
+
+ @Test
+ public void testOperationFailureFiredFlagPreventsEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("DELETE", "/api/metalakes/m1", null, "3.3.3.3");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ // Simulate an operation-layer FailureEvent having already been dispatched
+ FilterChain chain =
+ (request, response) -> {
+ RequestContext.markOperationFailureFired();
+ ((HttpServletResponse) response).sendError(403, "Forbidden");
+ };
+
+ filter.doFilter(req, resp, chain);
+
+ verify(eventBus, never()).dispatchEvent(any());
+ }
+
+ // ─── Exception escape ────────────────────────────────────────────────────────
+
+ @Test
+ public void testRuntimeExceptionEscapePromotesTo500AndEmitsEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "5.5.5.5");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> {
+ throw new RuntimeException("simulated crash");
+ };
+
+ Assertions.assertThrows(RuntimeException.class, () -> filter.doFilter(req, resp, chain));
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals(500, event.statusCode());
+ }
+
+ @Test
+ public void testServletExceptionEscapeIsRethrown() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "5.5.5.5");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> {
+ throw new ServletException("simulated servlet error");
+ };
+
+ Assertions.assertThrows(ServletException.class, () -> filter.doFilter(req, resp, chain));
+ }
+
+ @Test
+ public void testIoExceptionEscapeIsRethrown() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "5.5.5.5");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> {
+ throw new IOException("simulated IO error");
+ };
+
+ Assertions.assertThrows(IOException.class, () -> filter.doFilter(req, resp, chain));
+ }
+
+ // ─── ThreadLocal cleanup ─────────────────────────────────────────────────────
+
+ @Test
+ public void testFlagClearedAfterNormalCompletion() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "1.1.1.1");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> {
+ RequestContext.markOperationFailureFired();
+ ((HttpServletResponse) response).sendError(403);
+ };
+
+ filter.doFilter(req, resp, chain);
+
+ Assertions.assertFalse(
+ RequestContext.isOperationFailureFired(),
+ "operationFailureFired flag must be cleared after filter completes");
+ }
+
+ @Test
+ public void testFlagClearedAfterExceptionEscape() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "1.1.1.1");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> {
+ RequestContext.markOperationFailureFired();
+ throw new RuntimeException("crash with flag set");
+ };
+
+ Assertions.assertThrows(RuntimeException.class, () -> filter.doFilter(req, resp, chain));
+
+ Assertions.assertFalse(
+ RequestContext.isOperationFailureFired(),
+ "operationFailureFired flag must be cleared even when chain throws");
+ }
+
+ // ─── Remote address resolution ───────────────────────────────────────────────
+
+ @Test
+ public void testXForwardedForFirstEntryUsedAsRemoteAddress() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req =
+ mockRequest("GET", "/api/metalakes", "203.0.113.5, 10.1.1.1, 10.2.2.2", "10.0.0.1");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).sendError(401);
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals("203.0.113.5", event.remoteAddress());
+ }
+
+ @Test
+ public void testRawRemoteAddrUsedWhenNoXForwardedFor() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "192.168.0.42");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).sendError(401);
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals("192.168.0.42", event.remoteAddress());
+ }
+
+ @Test
+ public void testAuthenticatedPrincipalAttributeUsedForUser() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("POST", "/api/metalakes", null, "10.0.0.1");
+ Principal principal = () -> "alice";
+ when(req.getAttribute(AuthConstants.AUTHENTICATED_PRINCIPAL_ATTRIBUTE_NAME))
+ .thenReturn(principal);
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain =
+ (request, response) -> ((HttpServletResponse) response).sendError(400, "bad request");
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals("alice", event.user());
+ }
+
+ @Test
+ public void testNoAuthAttributeResolvesToUnknown() throws Exception {
+ // When the auth filter rejects a request (e.g. wrong token scheme → 401), it never calls
+ // request.setAttribute(AUTHENTICATED_PRINCIPAL_ATTRIBUTE_NAME, ...). The filter must report
+ // "unknown", not "anonymous" (which PrincipalUtils.getCurrentUserName() would return as its
+ // no-Subject fallback and is reserved for explicitly-anonymous authenticated requests).
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "10.0.0.1");
+ when(req.getAttribute(AuthConstants.AUTHENTICATED_PRINCIPAL_ATTRIBUTE_NAME)).thenReturn(null);
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).sendError(401);
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals("unknown", event.user());
+ }
+
+ // ─── Success + 5xx edge case ─────────────────────────────────────────────────
+
+ @Test
+ public void testSuccessEventFollowedBy5xxStillEmitsHttpFailureEvent() throws Exception {
+ // An operation dispatcher emits a SuccessEvent (operationFailureFired stays false),
+ // but the HTTP response ends up as 500 (e.g. JSON serialization failure).
+ // HttpAuditFilter must still emit HttpRequestFailureEvent for the HTTP-layer failure.
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes/m1", null, "1.2.3.4");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ // operationFailureFired is NOT set (success event path)
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).sendError(500);
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals(500, event.statusCode());
+ }
+
+ @Test
+ public void testStaleOperationFailureFlagDoesNotSuppressCurrentRequestEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter = new HttpAuditFilter(eventBus, EventSource.GRAVITINO_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/api/metalakes", null, "1.1.1.1");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).sendError(401);
+ // Simulate leaked state from a previous request on a pooled thread.
+ RequestContext.markOperationFailureFired();
+
+ filter.doFilter(req, resp, chain);
+
+ verify(eventBus).dispatchEvent(any());
+ }
+
+ // ─── EventSource propagation ─────────────────────────────────────────────────
+
+ @Test
+ public void testEventSourcePropagatedToEvent() throws Exception {
+ EventBus eventBus = mock(EventBus.class);
+ HttpAuditFilter filter =
+ new HttpAuditFilter(eventBus, EventSource.GRAVITINO_ICEBERG_REST_SERVER);
+ HttpServletRequest req = mockRequest("GET", "/iceberg/namespaces", null, "1.2.3.4");
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ FilterChain chain = (request, response) -> ((HttpServletResponse) response).sendError(404);
+
+ filter.doFilter(req, resp, chain);
+
+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);
+ verify(eventBus).dispatchEvent(captor.capture());
+ HttpRequestFailureEvent event = (HttpRequestFailureEvent) captor.getValue();
+ Assertions.assertEquals(EventSource.GRAVITINO_ICEBERG_REST_SERVER, event.eventSource());
+ }
+
+ // ─── StatusCapturingResponseWrapper ─────────────────────────────────────────
+
+ @Test
+ public void testStatusCapturingWrapperDefaultIs200() {
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ HttpAuditFilter.StatusCapturingResponseWrapper wrapper =
+ new HttpAuditFilter.StatusCapturingResponseWrapper(resp);
+
+ Assertions.assertEquals(200, wrapper.getCapturedStatus());
+ }
+
+ @Test
+ public void testStatusCapturingWrapperSetStatus() {
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ HttpAuditFilter.StatusCapturingResponseWrapper wrapper =
+ new HttpAuditFilter.StatusCapturingResponseWrapper(resp);
+
+ wrapper.setStatus(404);
+
+ Assertions.assertEquals(404, wrapper.getCapturedStatus());
+ }
+
+ @Test
+ public void testStatusCapturingWrapperSendErrorWithMessage() throws IOException {
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ HttpAuditFilter.StatusCapturingResponseWrapper wrapper =
+ new HttpAuditFilter.StatusCapturingResponseWrapper(resp);
+
+ wrapper.sendError(401, "Unauthorized");
+
+ Assertions.assertEquals(401, wrapper.getCapturedStatus());
+ }
+
+ @Test
+ public void testStatusCapturingWrapperSendErrorWithoutMessage() throws IOException {
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ HttpAuditFilter.StatusCapturingResponseWrapper wrapper =
+ new HttpAuditFilter.StatusCapturingResponseWrapper(resp);
+
+ wrapper.sendError(403);
+
+ Assertions.assertEquals(403, wrapper.getCapturedStatus());
+ }
+
+ @Test
+ public void testStatusCapturingWrapperResetRestoresTo200() throws IOException {
+ HttpServletResponse resp = mock(HttpServletResponse.class);
+ HttpAuditFilter.StatusCapturingResponseWrapper wrapper =
+ new HttpAuditFilter.StatusCapturingResponseWrapper(resp);
+
+ wrapper.sendError(500, "Internal Server Error");
+ Assertions.assertEquals(500, wrapper.getCapturedStatus());
+
+ wrapper.reset();
+ Assertions.assertEquals(200, wrapper.getCapturedStatus(), "reset() must restore status to 200");
+ }
+
+ // ─── Helper ──────────────────────────────────────────────────────────────────
+
+ private HttpServletRequest mockRequest(
+ String method, String uri, String xForwardedFor, String remoteAddr) {
+ HttpServletRequest req = mock(HttpServletRequest.class);
+ when(req.getMethod()).thenReturn(method);
+ when(req.getRequestURI()).thenReturn(uri);
+ when(req.getHeader("X-Forwarded-For")).thenReturn(xForwardedFor);
+ when(req.getRemoteAddr()).thenReturn(remoteAddr);
+ return req;
+ }
+}
diff --git a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
index 2b2f424c5a..e3825a7706 100644
--- a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
+++ b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
@@ -41,6 +41,7 @@ import org.apache.gravitino.job.JobOperationDispatcher;
import org.apache.gravitino.lineage.LineageConfig;
import org.apache.gravitino.lineage.LineageDispatcher;
import org.apache.gravitino.lineage.LineageService;
+import org.apache.gravitino.listener.api.event.EventSource;
import org.apache.gravitino.metalake.MetalakeDispatcher;
import org.apache.gravitino.metrics.MetricsSystem;
import org.apache.gravitino.metrics.source.MetricsSource;
@@ -49,6 +50,7 @@ import org.apache.gravitino.server.authentication.ServerAuthenticator;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.gravitino.server.web.ConfigServlet;
import org.apache.gravitino.server.web.HealthAliasServlet;
+import org.apache.gravitino.server.web.HttpAuditFilter;
import org.apache.gravitino.server.web.HttpServerMetricsSource;
import org.apache.gravitino.server.web.JettyServer;
import org.apache.gravitino.server.web.JettyServerConfig;
@@ -186,8 +188,10 @@ public class GravitinoServer extends ResourceConfig {
server.addServlet(new HealthAliasServlet(), "/health/*");
server.addServlet(new HealthAliasServlet(), "/health.html");
- server.addCustomFilters(API_ANY_PATH);
server.addFilter(new RequestContextFilter(), API_ANY_PATH);
+ server.addFilter(
+ new HttpAuditFilter(gravitinoEnv.eventBus(), EventSource.GRAVITINO_SERVER), API_ANY_PATH);
+ server.addCustomFilters(API_ANY_PATH);
server.addFilter(new VersioningFilter(), API_ANY_PATH);
server.addSystemFilters(API_ANY_PATH);
if (server.isWebUiEnabled()) {
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
index 0f229d85a4..82135aa463 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
@@ -38,12 +38,14 @@ import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.server.authorization.annotations.AuthorizationRequest;
import org.apache.gravitino.server.authorization.annotations.ExpressionCondition;
@@ -168,6 +170,8 @@ public class GravitinoInterceptionService implements InterceptionService {
} catch (NoSuchMetalakeException e) {
LOG.warn(
"Metalake {} does not exist when validating user {}", metalakeIdent, currentUser);
+ // Not a real authz denial — metalake is absent, not forbidden. Skip event dispatch;
+ // HttpAuditFilter will emit a generic HttpRequestFailureEvent for this 403.
return buildNoAuthResponse(expressionAnnotation, metadataContext, method, expression);
} catch (ForbiddenException ex) {
LOG.warn(
@@ -175,6 +179,7 @@ public class GravitinoInterceptionService implements InterceptionService {
currentUser,
metalakeIdent.name(),
ex.getMessage());
+ dispatchAuthzDenialEvent(currentUser, metalakeIdent, method.getName(), expression);
return Utils.forbidden(ex.getMessage(), ex);
} catch (Exception ex) {
LOG.error(
@@ -206,6 +211,14 @@ public class GravitinoInterceptionService implements InterceptionService {
secondaryExpressionCondition);
boolean authorizeResult = executor.execute(authorizationRequestContext);
if (!authorizeResult) {
+ MetadataObject.Type type = expressionAnnotation.accessMetadataType();
+ NameIdentifier accessMetadataName =
+ metadataContext.get(Entity.EntityType.valueOf(type.name()));
+ dispatchAuthzDenialEvent(
+ PrincipalUtils.getCurrentUserName(),
+ accessMetadataName,
+ method.getName(),
+ expression);
return buildNoAuthResponse(expressionAnnotation, metadataContext, method, expression);
}
}
@@ -247,6 +260,21 @@ public class GravitinoInterceptionService implements InterceptionService {
return buildNoAuthResponse(errorMessage, accessMetadataName, currentUser, methodName);
}
+ private void dispatchAuthzDenialEvent(
+ String user, NameIdentifier accessMetadataName, String methodName, String expression) {
+ try {
+ AuthorizationDenialFailureEvent event =
+ new AuthorizationDenialFailureEvent(user, accessMetadataName, methodName, expression);
+ GravitinoEnv.getInstance().eventBus().dispatchEvent(event);
+ } catch (Exception e) {
+ LOG.error(
+ "Failed to dispatch authorization denial event for user {} on operation {}",
+ user,
+ methodName,
+ e);
+ }
+ }
+
private Response buildNoAuthResponse(
String errorMessage,
NameIdentifier accessMetadataName,
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
index d59db13f58..3439287d8a 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
@@ -20,11 +20,15 @@ package org.apache.gravitino.server.web.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.Principal;
+import java.util.Collections;
import java.util.List;
import javax.ws.rs.core.Response;
import org.aopalliance.intercept.MethodInterceptor;
@@ -40,20 +44,33 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Privilege;
import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;
import org.apache.gravitino.metalake.MetalakeManager;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
import org.apache.gravitino.server.web.Utils;
import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.gravitino.utils.RequestContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.MockedStatic;
/** Test for {@link GravitinoInterceptionService}. */
public class TestGravitinoInterceptionService {
+ @AfterEach
+ public void clearRequestContext() {
+ RequestContext.resetOperationFailureFired();
+ RequestContext.clear();
+ }
+
@Test
public void testMetadataAuthorizationMethodInterceptor() throws Throwable {
try (MockedStatic<PrincipalUtils> principalUtilsMocked = mockStatic(PrincipalUtils.class);
@@ -250,6 +267,178 @@ public class TestGravitinoInterceptionService {
}
}
+ /**
+ * When the authorization executor returns {@code false}, {@code buildNoAuthResponse} is called
+ * with {@code emitEvent=true}. Verify that:
+ *
+ * <ul>
+ * <li>An {@link AuthorizationDenialFailureEvent} is dispatched via the EventBus.
+ * <li>{@code RequestContext.operationFailureFired} is set so {@code HttpAuditFilter} skips
+ * emitting a duplicate failure event for the same request.
+ * </ul>
+ */
+ @Test
+ public void testExecutorDenialDispatchesEventAndSetsFlag() throws Throwable {
+ try (MockedStatic<PrincipalUtils> principalUtilsMocked = mockStatic(PrincipalUtils.class);
+ MockedStatic<GravitinoAuthorizerProvider> authorizerMocked =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ MockedStatic<GravitinoEnv> envMocked = mockStatic(GravitinoEnv.class);
+ MockedStatic<MetalakeManager> metalakeManagerMocked = mockStatic(MetalakeManager.class)) {
+
+ principalUtilsMocked
+ .when(PrincipalUtils::getCurrentPrincipal)
+ .thenReturn(new UserPrincipal("tester"));
+ principalUtilsMocked.when(PrincipalUtils::getCurrentUserName).thenReturn("tester");
+
+ GravitinoAuthorizerProvider mockedProvider = mock(GravitinoAuthorizerProvider.class);
+ authorizerMocked.when(GravitinoAuthorizerProvider::getInstance).thenReturn(mockedProvider);
+ when(mockedProvider.getGravitinoAuthorizer()).thenReturn(new MockGravitinoAuthorizer());
+
+ GravitinoEnv mockEnv = mock(GravitinoEnv.class);
+ EntityStore mockStore = mock(EntityStore.class);
+ EventBus mockEventBus = spy(new EventBus(Collections.emptyList()));
+ envMocked.when(GravitinoEnv::getInstance).thenReturn(mockEnv);
+ when(mockEnv.entityStore()).thenReturn(mockStore);
+ when(mockEnv.eventBus()).thenReturn(mockEventBus);
+
+ metalakeManagerMocked
+ .when(() -> MetalakeManager.checkMetalake(ArgumentMatchers.any(), ArgumentMatchers.any()))
+ .thenAnswer(invocation -> null);
+
+ GravitinoInterceptionService service = new GravitinoInterceptionService();
+ Method testMethod = TestOperations.class.getMethods()[0];
+ MethodInterceptor interceptor = service.getMethodInterceptors(testMethod).get(0);
+
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(testMethod);
+ // testMetalake2 triggers denial in MockGravitinoAuthorizer
+ when(invocation.getArguments()).thenReturn(new Object[] {"testMetalake2"});
+
+ Assertions.assertFalse(RequestContext.isOperationFailureFired());
+ Response response = (Response) interceptor.invoke(invocation);
+
+ assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
+ // Event dispatched
+ ArgumentCaptor<AuthorizationDenialFailureEvent> captor =
+ ArgumentCaptor.forClass(AuthorizationDenialFailureEvent.class);
+ verify(mockEventBus).dispatchEvent(captor.capture());
+ AuthorizationDenialFailureEvent event = captor.getValue();
+ assertEquals("tester", event.user());
+ assertEquals("testMethod", event.methodName());
+ // Flag set so HttpAuditFilter skips duplicate
+ Assertions.assertTrue(RequestContext.isOperationFailureFired());
+ }
+ }
+
+ /**
+ * When {@code checkCurrentUser} throws {@link ForbiddenException} (user is not a metalake
+ * member), the interceptor must dispatch an {@link AuthorizationDenialFailureEvent} and set
+ * {@code operationFailureFired}.
+ */
+ @Test
+ public void testForbiddenExceptionDispatchesEventAndSetsFlag() throws Throwable {
+ try (MockedStatic<PrincipalUtils> principalUtilsMocked = mockStatic(PrincipalUtils.class);
+ MockedStatic<GravitinoAuthorizerProvider> authorizerMocked =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ MockedStatic<AuthorizationUtils> authUtilsMocked = mockStatic(AuthorizationUtils.class);
+ MockedStatic<GravitinoEnv> envMocked = mockStatic(GravitinoEnv.class)) {
+
+ principalUtilsMocked
+ .when(PrincipalUtils::getCurrentPrincipal)
+ .thenReturn(new UserPrincipal("outsider"));
+ principalUtilsMocked.when(PrincipalUtils::getCurrentUserName).thenReturn("outsider");
+
+ GravitinoAuthorizerProvider mockedProvider = mock(GravitinoAuthorizerProvider.class);
+ authorizerMocked.when(GravitinoAuthorizerProvider::getInstance).thenReturn(mockedProvider);
+ when(mockedProvider.getGravitinoAuthorizer()).thenReturn(new MockGravitinoAuthorizer());
+
+ authUtilsMocked
+ .when(
+ () ->
+ AuthorizationUtils.checkCurrentUser(
+ ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
+ .thenThrow(new ForbiddenException("User outsider is not a member"));
+
+ GravitinoEnv mockEnv = mock(GravitinoEnv.class);
+ EventBus mockEventBus = spy(new EventBus(Collections.emptyList()));
+ envMocked.when(GravitinoEnv::getInstance).thenReturn(mockEnv);
+ when(mockEnv.eventBus()).thenReturn(mockEventBus);
+
+ GravitinoInterceptionService service = new GravitinoInterceptionService();
+ Method testMethod = TestOperations.class.getMethods()[0];
+ MethodInterceptor interceptor = service.getMethodInterceptors(testMethod).get(0);
+
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(testMethod);
+ when(invocation.getArguments()).thenReturn(new Object[] {"testMetalake"});
+
+ Assertions.assertFalse(RequestContext.isOperationFailureFired());
+ Response response = (Response) interceptor.invoke(invocation);
+
+ assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
+ ArgumentCaptor<AuthorizationDenialFailureEvent> captor =
+ ArgumentCaptor.forClass(AuthorizationDenialFailureEvent.class);
+ verify(mockEventBus).dispatchEvent(captor.capture());
+ AuthorizationDenialFailureEvent event = captor.getValue();
+ assertEquals("outsider", event.user());
+ Assertions.assertTrue(RequestContext.isOperationFailureFired());
+ }
+ }
+
+ /**
+ * When {@code checkCurrentUser} throws {@link NoSuchMetalakeException}, the 403 is a
+ * resource-not-found masquerading as forbidden — no {@link AuthorizationDenialFailureEvent} is
+ * dispatched, leaving {@code operationFailureFired} false so that {@code HttpAuditFilter} can
+ * emit a generic {@code HttpRequestFailureEvent}.
+ */
+ @Test
+ public void testNoSuchMetalakeExceptionDoesNotDispatchEventAndFlagStaysFalse() throws Throwable {
+ try (MockedStatic<PrincipalUtils> principalUtilsMocked = mockStatic(PrincipalUtils.class);
+ MockedStatic<GravitinoAuthorizerProvider> authorizerMocked =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ MockedStatic<AuthorizationUtils> authUtilsMocked = mockStatic(AuthorizationUtils.class);
+ MockedStatic<GravitinoEnv> envMocked = mockStatic(GravitinoEnv.class)) {
+
+ principalUtilsMocked
+ .when(PrincipalUtils::getCurrentPrincipal)
+ .thenReturn(new UserPrincipal("tester"));
+ principalUtilsMocked.when(PrincipalUtils::getCurrentUserName).thenReturn("tester");
+
+ GravitinoAuthorizerProvider mockedProvider = mock(GravitinoAuthorizerProvider.class);
+ authorizerMocked.when(GravitinoAuthorizerProvider::getInstance).thenReturn(mockedProvider);
+ when(mockedProvider.getGravitinoAuthorizer()).thenReturn(new MockGravitinoAuthorizer());
+
+ authUtilsMocked
+ .when(
+ () ->
+ AuthorizationUtils.checkCurrentUser(
+ ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
+ .thenThrow(new NoSuchMetalakeException("Metalake gone does not exist"));
+
+ GravitinoEnv mockEnv = mock(GravitinoEnv.class);
+ EventBus mockEventBus = mock(EventBus.class);
+ envMocked.when(GravitinoEnv::getInstance).thenReturn(mockEnv);
+ when(mockEnv.eventBus()).thenReturn(mockEventBus);
+
+ GravitinoInterceptionService service = new GravitinoInterceptionService();
+ Method testMethod = TestOperations.class.getMethods()[0];
+ MethodInterceptor interceptor = service.getMethodInterceptors(testMethod).get(0);
+
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(testMethod);
+ when(invocation.getArguments()).thenReturn(new Object[] {"gone"});
+
+ Response response = (Response) interceptor.invoke(invocation);
+
+ assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
+ // No AuthorizationDenialFailureEvent dispatched — HttpAuditFilter handles this 403
+ verify(mockEventBus, never()).dispatchEvent(ArgumentMatchers.any());
+ Assertions.assertFalse(
+ RequestContext.isOperationFailureFired(),
+ "operationFailureFired must stay false so HttpAuditFilter emits the HTTP-level event");
+ }
+ }
+
public static class TestOperations {
@AuthorizationExpression(