You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "jerryshao (via GitHub)" <gi...@apache.org> on 2026/06/12 05:05:52 UTC

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

jerryshao opened a new pull request, #11618:
URL: https://github.com/apache/gravitino/pull/11618

   ### What changes were proposed in this pull request?
   
   Adds an `HttpAuditFilter` servlet filter registered on the main Gravitino server
   (`/api/*`), Iceberg REST server (`/iceberg/*`), and Lance REST server (`/lance/*`).
   The filter emits `HttpRequestFailureEvent` for every HTTP 4xx/5xx response when no
   operation-layer failure event was already dispatched on the same thread, closing the
   audit coverage gap for authentication failures, malformed requests, and unknown routes.
   
   A new `AuthorizationDenialFailureEvent` is dispatched by
   `GravitinoInterceptionService` for executor denials and `ForbiddenException`,
   carrying the authenticated user, resource identifier, intercepted method name, and
   authorization expression for rich audit attribution. `NoSuchMetalakeException` (a
   resource-not-found masquerading as 403) intentionally falls through to the generic
   HTTP-level event to avoid information disclosure.
   
   Double-logging prevention: `EventBus.dispatchFailureEvent()` sets a
   `RequestContext.operationFailureFired` flag for every non-`HttpRequestFailureEvent`
   failure; `HttpAuditFilter` checks the flag in its `finally` block and skips emission
   if already set.
   
   ### Why are the changes needed?
   
   Fix: #11230
   
   HTTP-layer failures (401 auth rejections, 400 malformed JSON, 404 unknown routes,
   403 authorization denials) currently produce no audit record. Enterprise users running
   Gravitino in regulated environments require a complete audit trail — including failed
   access attempts — to satisfy compliance requirements.
   
   ### Does this PR introduce _any_ user-facing change?
   
   - New audit log entries for all HTTP 4xx/5xx failures with fields:
     `user`, `opType` (`UNKNOWN` or `AUTHORIZATION_DENIAL`), `identifier`, `status`,
     `source` (`GRAVITINO_SERVER` / `GRAVITINO_ICEBERG_REST_SERVER` / `GRAVITINO_LANCE_REST_SERVER`),
     `remoteAddr`, and `customInfo` (`http.method`, `http.uri`, `http.status` for HTTP
     events; `auth.method`, `auth.expression` for authorization denial events).
   - New `OperationType.AUTHORIZATION_DENIAL` and `AuditLog.Operation.AUTHORIZATION_DENIAL`
     enum values in the public audit API.
   - New `EventSource.GRAVITINO_LANCE_REST_SERVER` enum value.
   - New public event classes: `HttpRequestFailureEvent`, `AuthorizationDenialFailureEvent`.
   
   ### How was this patch tested?
   
   - Unit tests: `TestHttpAuditFilter` (6 cases), `TestEventBus` (2 new flag-marking
     cases), `TestGravitinoInterceptionService` (3 new cases for executor denial,
     `ForbiddenException`, and `NoSuchMetalakeException` paths).
   - Coverage tests: `TestOperation`, `TestCompatibilityUtils`, `TestSimpleAuditLogV2`,
     `TestAuthorizationDenialFailureEvent`, `TestHttpRequestFailureEvent`.
   - Integration tests: `HttpAuditFilterIT`, `HttpAuditAuthzDenialIT`.
   - Manual end-to-end: all 18 test cases (TC-A1–A4, TC-B1–B5, TC-C1–C8, TC-D1–D2)
     verified against the running distribution.


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4704448765

   @mchades @yuqi1129 can you please help to trigger the copilot review. Mine just ran out of quota.


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4714603681

   @mchades please help to review again.


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3405430082


##########
server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java:
##########
@@ -250,6 +267,180 @@ public void testEmptyExpressionSkipsAuthorization() throws Throwable {
     }
   }
 
+  /**
+   * 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<org.apache.gravitino.listener.api.event.Event> captor =
+          ArgumentCaptor.forClass(org.apache.gravitino.listener.api.event.Event.class);
+      verify(mockEventBus).dispatchEvent(captor.capture());
+      Assertions.assertInstanceOf(AuthorizationDenialFailureEvent.class, captor.getValue());
+      AuthorizationDenialFailureEvent event = (AuthorizationDenialFailureEvent) captor.getValue();
+      assertEquals("tester", event.user());

Review Comment:
   Fixed — both captors are now typed directly to `ArgumentCaptor<AuthorizationDenialFailureEvent>`, removing the FQN and the redundant `assertInstanceOf` + cast.



##########
server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java:
##########
@@ -250,6 +267,180 @@ public void testEmptyExpressionSkipsAuthorization() throws Throwable {
     }
   }
 
+  /**
+   * 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<org.apache.gravitino.listener.api.event.Event> captor =
+          ArgumentCaptor.forClass(org.apache.gravitino.listener.api.event.Event.class);
+      verify(mockEventBus).dispatchEvent(captor.capture());
+      Assertions.assertInstanceOf(AuthorizationDenialFailureEvent.class, captor.getValue());
+      AuthorizationDenialFailureEvent event = (AuthorizationDenialFailureEvent) 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<org.apache.gravitino.listener.api.event.Event> captor =
+          ArgumentCaptor.forClass(org.apache.gravitino.listener.api.event.Event.class);
+      verify(mockEventBus).dispatchEvent(captor.capture());
+      Assertions.assertInstanceOf(AuthorizationDenialFailureEvent.class, captor.getValue());
+      AuthorizationDenialFailureEvent event = (AuthorizationDenialFailureEvent) captor.getValue();
+      assertEquals("outsider", event.user());

Review Comment:
   Fixed — same as above.



##########
core/src/main/java/org/apache/gravitino/listener/api/event/server/AuthorizationDenialFailureEvent.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.exceptions.ForbiddenException;
+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 {@link
+ * ForbiddenException}.
+ *
+ * <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 ForbiddenException(
+            "Authorization denied for user '%s' on operation '%s'", user, methodName));
+    this.methodName = methodName;
+    this.expression = expression != null ? expression : "";
+    this.explicitEventSource = eventSource;
+  }
+
+  /** Returns {@link OperationType#AUTHORIZATION_DENIAL}. */

Review Comment:
   Fixed — replaced `ForbiddenException` with a lightweight `AuthorizationDenialException` inner class (modelled after `HttpRequestException` in `HttpRequestFailureEvent`) that suppresses stack trace collection via the 4-arg `RuntimeException` constructor. Authorization denials can be high-volume so the overhead saving is meaningful.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3401223862


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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 javax.annotation.Nullable;
+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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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 targeting {@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, and {@code /api/health/*} are silently
+ * passed through without audit logging to avoid polluting the audit log with probe traffic.
+ *
+ * <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";
+
+  @Nullable private final EventBus eventBus;
+  private final EventSource eventSource;
+
+  /**
+   * Constructs an {@code HttpAuditFilter}.
+   *
+   * @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 = eventBus;
+    this.eventSource = eventSource;
+  }
+
+  @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 == null || !(request instanceof HttpServletRequest)) {
+      chain.doFilter(request, response);
+      return;
+    }
+
+    HttpServletRequest httpRequest = (HttpServletRequest) request;
+    // Defensive cleanup at request entry in case a pooled thread leaked stale state.
+    RequestContext.resetOperationFailureFired();
+    if (isHealthCheckRequest(httpRequest)) {
+      chain.doFilter(request, response);
+      return;
+    }

Review Comment:
   The health-check bypass returns without clearing RequestContext.operationFailureFired. If a failure event is dispatched during `/api/health*`, the ThreadLocal flag can leak onto the Jetty thread and affect later requests.
   
   Wrap the health-check early-return in a try/finally that resets the flag (same as the main path).



##########
core/src/main/java/org/apache/gravitino/listener/api/event/server/AuthorizationDenialFailureEvent.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.exceptions.ForbiddenException;
+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 {@link
+ * ForbiddenException}.
+ *
+ * <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 ForbiddenException(
+            "Authorization denied for user '%s' on operation '%s'", user, methodName));
+    this.methodName = methodName;
+    this.expression = expression != null ? expression : "";
+    this.explicitEventSource = eventSource;
+  }
+
+  /** Returns {@link OperationType#AUTHORIZATION_DENIAL}. */

Review Comment:
   `AuthorizationDenialFailureEvent` constructs a new `ForbiddenException`, which captures a full stack trace. Authorization denials can be high-volume, and this exception is only a synthetic carrier for audit context, so the stack trace overhead is avoidable.
   
   Consider using a lightweight exception that suppresses stack trace (similar to `HttpRequestFailureEvent.HttpRequestException`).



##########
server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java:
##########
@@ -250,6 +267,180 @@ public void testEmptyExpressionSkipsAuthorization() throws Throwable {
     }
   }
 
+  /**
+   * 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<org.apache.gravitino.listener.api.event.Event> captor =
+          ArgumentCaptor.forClass(org.apache.gravitino.listener.api.event.Event.class);
+      verify(mockEventBus).dispatchEvent(captor.capture());
+      Assertions.assertInstanceOf(AuthorizationDenialFailureEvent.class, captor.getValue());
+      AuthorizationDenialFailureEvent event = (AuthorizationDenialFailureEvent) 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<org.apache.gravitino.listener.api.event.Event> captor =
+          ArgumentCaptor.forClass(org.apache.gravitino.listener.api.event.Event.class);
+      verify(mockEventBus).dispatchEvent(captor.capture());
+      Assertions.assertInstanceOf(AuthorizationDenialFailureEvent.class, captor.getValue());
+      AuthorizationDenialFailureEvent event = (AuthorizationDenialFailureEvent) captor.getValue();
+      assertEquals("outsider", event.user());

Review Comment:
   Same as above: avoid fully qualified class names here (AGENTS.md:26-30) and simplify the captor to the expected event type to remove the redundant `instanceof`/cast.



##########
server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java:
##########
@@ -250,6 +267,180 @@ public void testEmptyExpressionSkipsAuthorization() throws Throwable {
     }
   }
 
+  /**
+   * 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<org.apache.gravitino.listener.api.event.Event> captor =
+          ArgumentCaptor.forClass(org.apache.gravitino.listener.api.event.Event.class);
+      verify(mockEventBus).dispatchEvent(captor.capture());
+      Assertions.assertInstanceOf(AuthorizationDenialFailureEvent.class, captor.getValue());
+      AuthorizationDenialFailureEvent event = (AuthorizationDenialFailureEvent) captor.getValue();
+      assertEquals("tester", event.user());

Review Comment:
   Avoid using fully qualified class names in tests when there is no name conflict (AGENTS.md:26-30). Here the captor can be typed directly to `AuthorizationDenialFailureEvent`, which also removes the need for the `instanceof` + cast.



##########
core/src/main/java/org/apache/gravitino/listener/EventBus.java:
##########
@@ -129,17 +131,28 @@ private void dispatchPostEvent(Event postEvent) {
   }
 
   /**
-   * 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.

Review Comment:
   The Javadoc claims this method catches listener failures including `Error`, but the implementation only catches `Exception` (so `Error` would still propagate). Please align the comment with the actual behavior (or broaden the catch, if that is truly intended).



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4691387640

   Sorry, I mistakenly clicked the "approve" button instead of the "comment" button.


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3403368850


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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 javax.annotation.Nullable;
+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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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 targeting {@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, and {@code /api/health/*} are silently
+ * passed through without audit logging to avoid polluting the audit log with probe traffic.
+ *
+ * <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";
+
+  @Nullable private final EventBus eventBus;
+  private final EventSource eventSource;
+
+  /**
+   * Constructs an {@code HttpAuditFilter}.
+   *
+   * @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) {

Review Comment:
   Use optional instead?



##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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 javax.annotation.Nullable;
+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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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 targeting {@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, and {@code /api/health/*} are silently
+ * passed through without audit logging to avoid polluting the audit log with probe traffic.
+ *
+ * <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";
+
+  @Nullable private final EventBus eventBus;
+  private final EventSource eventSource;
+
+  /**
+   * Constructs an {@code HttpAuditFilter}.
+   *
+   * @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 = eventBus;
+    this.eventSource = eventSource;
+  }
+
+  @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 == null || !(request instanceof HttpServletRequest)) {
+      chain.doFilter(request, response);
+      return;
+    }
+
+    HttpServletRequest httpRequest = (HttpServletRequest) request;
+    // Defensive cleanup at request entry in case a pooled thread leaked stale state.
+    RequestContext.resetOperationFailureFired();
+    if (isHealthCheckRequest(httpRequest)) {
+      chain.doFilter(request, response);
+      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.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

Review Comment:
   The comments says `It returns anonymous` but we got `unknown`.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3405431421


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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 javax.annotation.Nullable;
+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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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 targeting {@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, and {@code /api/health/*} are silently
+ * passed through without audit logging to avoid polluting the audit log with probe traffic.
+ *
+ * <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";
+
+  @Nullable private final EventBus eventBus;
+  private final EventSource eventSource;
+
+  /**
+   * Constructs an {@code HttpAuditFilter}.
+   *
+   * @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) {

Review Comment:
   Fixed — the `@Nullable EventBus` field is now `Optional<EventBus>`, set in the constructor via `Optional.ofNullable(eventBus)`. The null-check in `doFilter` is replaced with `eventBus.isEmpty()` and the dispatch uses `eventBus.get()`.



##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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 javax.annotation.Nullable;
+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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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 targeting {@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, and {@code /api/health/*} are silently
+ * passed through without audit logging to avoid polluting the audit log with probe traffic.
+ *
+ * <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";
+
+  @Nullable private final EventBus eventBus;
+  private final EventSource eventSource;
+
+  /**
+   * Constructs an {@code HttpAuditFilter}.
+   *
+   * @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 = eventBus;
+    this.eventSource = eventSource;
+  }
+
+  @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 == null || !(request instanceof HttpServletRequest)) {
+      chain.doFilter(request, response);
+      return;
+    }
+
+    HttpServletRequest httpRequest = (HttpServletRequest) request;
+    // Defensive cleanup at request entry in case a pooled thread leaked stale state.
+    RequestContext.resetOperationFailureFired();
+    if (isHealthCheckRequest(httpRequest)) {
+      chain.doFilter(request, response);
+      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.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

Review Comment:
   Fixed — the comment now correctly says 'Returns `unknown` instead' to match what the code actually returns when no principal attribute is set on the request.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4706151814

   **Residual risk: Missing integration test for uncaught servlet errors**
   
   **Location:** `server-common/src/test/java/org/apache/gravitino/server/web/TestHttpAuditFilter.java` around line 408
   
   **Issue:** While the unit tests cover most scenarios, there's no integration test verifying correct audit event handling for:
   - Uncaught servlet errors (DispatcherType.ERROR)
   - Exception escaping without being caught by filters
   - Ensuring no duplicate or missing 500 audit events during error dispatch
   
   **Recommendation:** Add an integration test (`HttpAuditFilterIT` or similar) that:
   1. Triggers a true servlet error (e.g., JSP compilation error, uncaught exception in servlet initialization)
   2. Verifies exactly one audit event is emitted
   3. Confirms DispatcherType.ERROR requests don't bypass or double-log events
   
   This prevents the audit trail from missing or duplicating events when errors bubble up from the servlet layer.
   


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4706146475

   **[P2] Custom filters can bypass audit trail**
   
   **Files affected:**
   - `server/src/main/java/org/apache/gravitino/server/GravitinoServer.java` line 190-193
   - `iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java` line 208-212  
   - `lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/LanceRESTService.java` line 95-98
   
   **Issue:** HttpAuditFilter is registered AFTER `server.addCustomFilters()`. A custom filter that returns 401/403/5xx without calling `chain.doFilter()` can bypass HttpAuditFilter entirely, emitting no audit event.
   
   **Recommended fix:** Reorder filters so HttpAuditFilter comes BEFORE custom filters.
   
   For the main server (GravitinoServer), suggested order:
   1. RequestContextFilter (ThreadLocal initialization)
   2. HttpAuditFilter  
   3. Custom filters
   4. VersioningFilter
   5. System filters
   
   Iceberg and Lance REST servers should follow the same pattern: HttpAuditFilter before custom filters.
   


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3405428909


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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 javax.annotation.Nullable;
+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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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 targeting {@code /health}, {@code
+ * /health/*}, {@code /health.html}, {@code /api/health}, and {@code /api/health/*} are silently
+ * passed through without audit logging to avoid polluting the audit log with probe traffic.
+ *
+ * <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";
+
+  @Nullable private final EventBus eventBus;
+  private final EventSource eventSource;
+
+  /**
+   * Constructs an {@code HttpAuditFilter}.
+   *
+   * @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 = eventBus;
+    this.eventSource = eventSource;
+  }
+
+  @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 == null || !(request instanceof HttpServletRequest)) {
+      chain.doFilter(request, response);
+      return;
+    }
+
+    HttpServletRequest httpRequest = (HttpServletRequest) request;
+    // Defensive cleanup at request entry in case a pooled thread leaked stale state.
+    RequestContext.resetOperationFailureFired();
+    if (isHealthCheckRequest(httpRequest)) {
+      chain.doFilter(request, response);
+      return;
+    }

Review Comment:
   Fixed — the health-check early-return path is now wrapped in a `try/finally` that calls `RequestContext.resetOperationFailureFired()`, matching the cleanup performed by the main path.



##########
core/src/main/java/org/apache/gravitino/listener/EventBus.java:
##########
@@ -129,17 +131,28 @@ private void dispatchPostEvent(Event postEvent) {
   }
 
   /**
-   * 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.

Review Comment:
   Fixed — the Javadoc now says 'catches and logs all `Exception`s' to match the actual `catch (Exception e)` in the implementation. Broadening to `Throwable`/`Error` is intentionally not done here: `Error` indicates a JVM-level problem that should propagate up rather than be silently swallowed.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3410984941


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,295 @@
+/*
+ * 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.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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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;
+    // 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) {

Review Comment:
   What's the meaning of this problem, can you describe more? To promote to 500 is only for the failure case, if the operation succeeds, the http code will be less than 400, and it will not trigger an event.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4709887346

   OK, I will fix these two issues soon.


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#issuecomment-4688118975

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|67.01% **`+0.11%`**|:green_circle:|
   |:-|:-|:-:|
   |Files changed|74.84%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|1.72%|:red_circle:|
   |api|46.82%|:green_circle:|
   |authorization-common|85.96%|:green_circle:|
   |aws|3.66%|:red_circle:|
   |azure|2.47%|:red_circle:|
   |catalog-common|10.4%|:red_circle:|
   |catalog-fileset|80.23%|:green_circle:|
   |catalog-glue|66.91%|:green_circle:|
   |catalog-hive|79.44%|:green_circle:|
   |catalog-jdbc-clickhouse|80.02%|:green_circle:|
   |catalog-jdbc-common|44.22%|:green_circle:|
   |catalog-jdbc-doris|80.28%|:green_circle:|
   |catalog-jdbc-hologres|54.03%|:green_circle:|
   |catalog-jdbc-mysql|79.23%|:green_circle:|
   |catalog-jdbc-oceanbase|78.38%|:green_circle:|
   |catalog-jdbc-postgresql|82.29%|:green_circle:|
   |catalog-jdbc-starrocks|78.51%|:green_circle:|
   |catalog-kafka|77.01%|:green_circle:|
   |catalog-lakehouse-generic|58.53%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.79%|:green_circle:|
   |catalog-lakehouse-paimon|79.15%|:green_circle:|
   |catalog-model|77.72%|:green_circle:|
   |cli|44.51%|:green_circle:|
   |client-java|78.01%|:green_circle:|
   |common|49.9% **`+0.06%`**|:green_circle:|
   |core|82.46% **`+0.4%`**|:green_circle:|
   |filesystem-hadoop3|77.27%|:green_circle:|
   |flink|0.0%|:red_circle:|
   |flink-common|45.72%|:green_circle:|
   |flink-runtime|0.0%|:red_circle:|
   |gcp|14.12%|:red_circle:|
   |hadoop-common|10.39%|:red_circle:|
   |hive-metastore-common|53.9%|:green_circle:|
   |iceberg-common|57.41%|:green_circle:|
   |iceberg-rest-server|73.9% **`-2.07%`**|:green_circle:|
   |idp-basic|86.18%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|66.17%|:green_circle:|
   |lance-common|20.79%|:red_circle:|
   |lance-rest-server|60.13% **`-11.69%`**|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|82.95%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|85.97% **`-1.87%`**|:green_circle:|
   |server-common|73.68% **`+0.47%`**|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|41.66%|:green_circle:|
   |trino-connector|40.13%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |common|[ErrorResponse.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/common/src/main/java/org/apache/gravitino/dto/responses/ErrorResponse.java)|54.55%|:red_circle:|
   ||[ErrorConstants.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/common/src/main/java/org/apache/gravitino/dto/responses/ErrorConstants.java)|0.0%|:red_circle:|
   |core|[EventSource.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/listener/api/event/EventSource.java)|100.0%|:green_circle:|
   ||[OperationType.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java)|100.0%|:green_circle:|
   ||[AuthorizationDenialFailureEvent.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/listener/api/event/server/AuthorizationDenialFailureEvent.java)|100.0%|:green_circle:|
   ||[HttpRequestFailureEvent.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/listener/api/event/server/HttpRequestFailureEvent.java)|100.0%|:green_circle:|
   ||[RequestContext.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/utils/RequestContext.java)|100.0%|:green_circle:|
   ||[CompatibilityUtils.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java)|99.34%|:green_circle:|
   ||[AuditLog.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/audit/AuditLog.java)|97.52%|:green_circle:|
   ||[EventBus.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/core/src/main/java/org/apache/gravitino/listener/EventBus.java)|93.62%|:green_circle:|
   |iceberg-rest-server|[RESTService.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java)|0.0%|:red_circle:|
   |lance-rest-server|[LanceRESTService.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/LanceRESTService.java)|0.0%|:red_circle:|
   |server|[GravitinoInterceptionService.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java)|68.18%|:green_circle:|
   ||[GravitinoServer.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java)|60.77%|:green_circle:|
   |server-common|[HttpAuditFilter.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java)|85.54%|:green_circle:|
   ||[AuthenticationFilter.java](https://github.com/jerryshao/gravitino/blob/709e3ea33875671c4317781be9b5398fb380f85e/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java)|76.27%|:green_circle:|
   
   </details>


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3411840785


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,295 @@
+/*
+ * 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.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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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;
+    // 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) {

Review Comment:
   I see.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11618:
URL: https://github.com/apache/gravitino/pull/11618#discussion_r3410848524


##########
server-common/src/main/java/org/apache/gravitino/server/web/HttpAuditFilter.java:
##########
@@ -0,0 +1,295 @@
+/*
+ * 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.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> {@link
+ * org.apache.gravitino.server.authentication.AuthenticationFilter} (so it observes 401
+ * authentication failures as well as downstream 403 authorization denials). 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>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;
+    // 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) {

Review Comment:
   You have increased the status that less than `400`, so when the condition wil be `false`?



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


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

Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades merged PR #11618:
URL: https://github.com/apache/gravitino/pull/11618


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org