This is an automated email from the ASF dual-hosted git repository.

adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new d4e3fb86158 HDDS-17406. Update STS revocation logic to incorporate 
cutoffs when deciding what to purge (#11810)
d4e3fb86158 is described below

commit d4e3fb861583922d518501548d3fa9c365e7376e
Author: fmorg-git <[email protected]>
AuthorDate: Wed Nov 4 13:43:24 2026 -0800

    HDDS-17406. Update STS revocation logic to incorporate cutoffs when 
deciding what to purge (#11810)
---
 .../src/main/proto/OmClientProtocol.proto          |   4 +-
 .../security/S3DeleteRevokedSTSTokensRequest.java  |  47 +++-
 .../om/service/RevokedSTSTokenCleanupService.java  |  54 +++--
 .../s3/security/TestS3RevokeSTSTokenRequest.java   | 260 ++++++++++++++++++++-
 .../service/TestRevokedSTSTokenCleanupService.java |  14 +-
 5 files changed, 348 insertions(+), 31 deletions(-)

diff --git 
a/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto 
b/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
index ff7b325b703..71df2e30d17 100644
--- a/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
+++ b/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
@@ -2684,10 +2684,12 @@ message RevokeSTSTokenResponse {
 
 /**
  This will contain a list of originalAccessKeyIds whose revocation entries 
should be removed from
- the s3RevokedStsTokenTable.
+ the s3RevokedStsTokenTable. An entry is deleted only if its current cutoff is 
older than
+ purgeBeforeMillis. Requests without purgeBeforeMillis delete all listed 
entries.
 */
 message DeleteRevokedSTSTokensRequest {
   repeated string originalAccessKeyId = 1;
+  optional uint64 purgeBeforeMillis = 2;
 }
 
 message DeleteRevokedSTSTokensResponse {
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/s3/security/S3DeleteRevokedSTSTokensRequest.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/s3/security/S3DeleteRevokedSTSTokensRequest.java
index 81558ec5850..d49a5518c4a 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/s3/security/S3DeleteRevokedSTSTokensRequest.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/s3/security/S3DeleteRevokedSTSTokensRequest.java
@@ -18,7 +18,11 @@
 package org.apache.hadoop.ozone.om.request.s3.security;
 
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.List;
+import org.apache.hadoop.hdds.utils.db.Table;
+import org.apache.hadoop.hdds.utils.db.cache.CacheKey;
+import org.apache.hadoop.hdds.utils.db.cache.CacheValue;
 import org.apache.hadoop.ozone.om.OzoneManager;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
 import org.apache.hadoop.ozone.om.execution.flowcontrol.ExecutionContext;
@@ -32,13 +36,19 @@
 import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
 import org.apache.hadoop.security.UserGroupInformation;
 import 
org.apache.hadoop.security.authentication.client.AuthenticationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Handles DeleteRevokedSTSTokens requests submitted by {@link 
RevokedSTSTokenCleanupService}.
- * Each request contains originalAccessKeyIds to remove from the revocation 
table.
+ * Each request lists originalAccessKeyIds to remove from the revocation 
table. When {@code purgeBeforeMillis} is set,
+ * an entry is removed only if its current cutoff is older than that 
threshold. Requests without
+ * {@code purgeBeforeMillis} delete all listed ids.
  */
 public class S3DeleteRevokedSTSTokensRequest extends OMClientRequest {
 
+  private static final Logger LOG = 
LoggerFactory.getLogger(S3DeleteRevokedSTSTokensRequest.class);
+
   public S3DeleteRevokedSTSTokensRequest(OMRequest omRequest) {
     super(omRequest);
   }
@@ -64,7 +74,40 @@ public OMClientResponse validateAndUpdateCache(OzoneManager 
ozoneManager, Execut
     final OMResponse.Builder omResponse = 
OmResponseUtil.getOMResponseBuilder(getOmRequest());
 
     final List<String> originalAccessKeyIds = 
request.getOriginalAccessKeyIdList();
-    return new S3DeleteRevokedSTSTokensResponse(originalAccessKeyIds, 
omResponse.build());
+    final Table<String, Long> table = 
ozoneManager.getMetadataManager().getS3RevokedStsTokenTable();
+    final List<String> deletedIds;
+    try {
+      if (!request.hasPurgeBeforeMillis()) {
+        // Delete all listed ids if the request does not have purgeBeforeMillis
+        deletedIds = originalAccessKeyIds;
+      } else {
+        final long purgeBeforeMillis = request.getPurgeBeforeMillis();
+        deletedIds = new ArrayList<>();
+        for (String originalAccessKeyId : originalAccessKeyIds) {
+          final Long revocationTimeMillis = 
table.getIfExist(originalAccessKeyId);
+          // A cutoff written after the scan, such as a newer revocation of 
the same key, is kept unless it is also
+          // older than purgeBeforeMillis.
+          if (revocationTimeMillis != null && revocationTimeMillis < 
purgeBeforeMillis) {
+            deletedIds.add(originalAccessKeyId);
+          }
+        }
+      }
+    } catch (IOException e) {
+      return new S3DeleteRevokedSTSTokensResponse(null, 
createErrorOMResponse(omResponse, e));
+    }
+
+    if (request.hasPurgeBeforeMillis() && deletedIds.size() < 
originalAccessKeyIds.size()) {
+      LOG.info(
+          "Skipped {} of {} revoked STS token purge entries because the cutoff 
is not older than the purge " +
+          "threshold or the entry was already removed.", 
originalAccessKeyIds.size() - deletedIds.size(),
+          originalAccessKeyIds.size());
+    }
+
+    // The full table cache only evicts delete markers, so without one a 
deleted key's old cutoff stays cached
+    for (String originalAccessKeyId : deletedIds) {
+      table.addCacheEntry(new CacheKey<>(originalAccessKeyId), 
CacheValue.get(context.getIndex()));
+    }
+    return new S3DeleteRevokedSTSTokensResponse(deletedIds, 
omResponse.build());
   }
 }
 
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/RevokedSTSTokenCleanupService.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/RevokedSTSTokenCleanupService.java
index b3062efbe5e..b5d7a1eb9a3 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/RevokedSTSTokenCleanupService.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/RevokedSTSTokenCleanupService.java
@@ -133,10 +133,13 @@ public BackgroundTaskResult call() throws Exception {
 
       final long startTime = Time.monotonicNow();
       runCount.incrementAndGet();
+      final long purgeBeforeMillis = CLOCK.millis() - CLEANUP_THRESHOLD;
       // Read the metadata manager on every run, since installing a checkpoint 
replaces it
       final Table<String, Long> revokedStsTokenTable = 
ozoneManager.getMetadataManager().getS3RevokedStsTokenTable();
 
-      long deletedInRun = 0;
+      // This is called submittedInRun because a submitted originalAccessKeyId 
might not actually get deleted if its
+      // cutoff is no longer older than purgeBeforeMillis when the request is 
applied.
+      long submittedInRun = 0;
       final List<String> batch = new ArrayList<>();
 
       try (Table.KeyValueIterator<String, Long> iterator = 
revokedStsTokenTable.iterator()) {
@@ -146,18 +149,18 @@ public BackgroundTaskResult call() throws Exception {
           final String originalAccessKeyId = entry.getKey();
           final Long revocationTimeMillis = entry.getValue();
 
-          if (shouldCleanup(revocationTimeMillis)) {
+          if (shouldCleanup(revocationTimeMillis, purgeBeforeMillis)) {
             // Calculate the size this originalAccessKeyId would add to the 
protobuf message.
             // Make a copy of the batch to do the size check
             final List<String> batchCopyWithCandidate = new ArrayList<>(batch);
             batchCopyWithCandidate.add(originalAccessKeyId);
-            int batchWithCandidateSize = 
getBatchSerializedSize(batchCopyWithCandidate);
+            int batchWithCandidateSize = 
getBatchSerializedSize(batchCopyWithCandidate, purgeBeforeMillis);
 
             // If adding this originalAccessKeyId would exceed the limit, 
submit the current batch
             if (batchWithCandidateSize > ratisByteLimit) {
               if (!batch.isEmpty()) {
-                if (submitCleanupRequest(batch)) {
-                  deletedInRun += batch.size();
+                if (submitCleanupRequest(batch, purgeBeforeMillis)) {
+                  submittedInRun += batch.size();
                 } else {
                   LOG.warn("Failed to submit batch of {} revoked tokens.", 
batch.size());
                 }
@@ -167,7 +170,7 @@ public BackgroundTaskResult call() throws Exception {
                 // to check if it exceeds the limit by itself.
                 final List<String> singleCandidateBatch = new ArrayList<>();
                 singleCandidateBatch.add(originalAccessKeyId);
-                batchWithCandidateSize = 
getBatchSerializedSize(singleCandidateBatch);
+                batchWithCandidateSize = 
getBatchSerializedSize(singleCandidateBatch, purgeBeforeMillis);
               }
 
               // Check if the single key exceeds the limit (either strictly 
single or after flush)
@@ -183,46 +186,44 @@ public BackgroundTaskResult call() throws Exception {
         }
       } catch (IOException e) {
         LOG.error("Failure while scanning s3RevokedStsTokenTable.  It will be 
retried in the next interval", e);
-        if (deletedInRun == 0) {
+        if (submittedInRun == 0) {
           return BackgroundTaskResult.EmptyTaskResult.newResult();
         }
       }
 
       // Submit any remaining tokens
       if (!batch.isEmpty()) {
-        if (submitCleanupRequest(batch)) {
-          deletedInRun += batch.size();
+        if (submitCleanupRequest(batch, purgeBeforeMillis)) {
+          submittedInRun += batch.size();
         } else {
           LOG.warn("Failed to submit final batch of {} revoked tokens.", 
batch.size());
         }
       }
 
       // Update stats
-      if (deletedInRun > 0) {
-        submittedDeletedEntryCount.addAndGet(deletedInRun);
-        LOG.info("Found and removed {} revoked STS token entries.", 
deletedInRun);
+      if (submittedInRun > 0) {
+        submittedDeletedEntryCount.addAndGet(submittedInRun);
+        LOG.info("Submitted {} revoked STS token entries for deletion.", 
submittedInRun);
       }
 
       final long elapsed = Time.monotonicNow() - startTime;
-      LOG.info("RevokedSTSTokenCleanupService run completed. 
deletedEntriesInRun={}, totalDeletedEntries={}, " +
-          "callIdCount={}, elapsedTimeMs={}", deletedInRun, 
submittedDeletedEntryCount.get(), callIdCount.get(),
+      LOG.info("RevokedSTSTokenCleanupService run completed. 
submittedEntriesInRun={}, totalSubmittedEntries={}, " +
+          "callIdCount={}, elapsedTimeMs={}", submittedInRun, 
submittedDeletedEntryCount.get(), callIdCount.get(),
           elapsed);
 
-      final long resultCount = deletedInRun;
+      final long resultCount = submittedInRun;
       return () -> (int) resultCount;
     }
 
     /**
-     * Returns true if the revocation cutoff is older than the cleanup 
threshold.
+     * Returns true if the revocation cutoff is older than the purge threshold.
      */
-    private boolean shouldCleanup(long revocationTimeMillis) {
-      final long now = CLOCK.millis();
-
-      if (now - revocationTimeMillis > CLEANUP_THRESHOLD) {
+    private boolean shouldCleanup(long revocationTimeMillis, long 
purgeBeforeMillis) {
+      if (revocationTimeMillis < purgeBeforeMillis) {
         if (LOG.isDebugEnabled()) {
           LOG.debug(
-              "Revoked STS token cutoff at {} is older than {} ms, will clean 
up. Current time: {}",
-              revocationTimeMillis, CLEANUP_THRESHOLD, now);
+              "Revoked STS token cutoff at {} is older than purge threshold 
{}, will clean up.",
+              revocationTimeMillis, purgeBeforeMillis);
         }
         return true;
       }
@@ -230,11 +231,13 @@ private boolean shouldCleanup(long revocationTimeMillis) {
     }
 
     /**
-     * Builds and submits an OMRequest to delete the provided 
originalAccessKeyId revocation entries.
+     * Builds and submits an OMRequest to delete the provided 
originalAccessKeyId revocation entries, each only if its
+     * cutoff is still older than the purge threshold.
      */
-    private boolean submitCleanupRequest(List<String> originalAccessKeyIds) {
+    private boolean submitCleanupRequest(List<String> originalAccessKeyIds, 
long purgeBeforeMillis) {
       final DeleteRevokedSTSTokensRequest request = 
DeleteRevokedSTSTokensRequest.newBuilder()
           .addAllOriginalAccessKeyId(originalAccessKeyIds)
+          .setPurgeBeforeMillis(purgeBeforeMillis)
           .build();
 
       final OMRequest omRequest = OMRequest.newBuilder()
@@ -254,9 +257,10 @@ private boolean submitCleanupRequest(List<String> 
originalAccessKeyIds) {
       }
     }
 
-    private int getBatchSerializedSize(List<String> originalAccessKeyIdBatch) {
+    private int getBatchSerializedSize(List<String> originalAccessKeyIdBatch, 
long purgeBeforeMillis) {
       final DeleteRevokedSTSTokensRequest request = 
DeleteRevokedSTSTokensRequest.newBuilder()
           .addAllOriginalAccessKeyId(originalAccessKeyIdBatch)
+          .setPurgeBeforeMillis(purgeBeforeMillis)
           .build();
 
       return request.getSerializedSize();
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/s3/security/TestS3RevokeSTSTokenRequest.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/s3/security/TestS3RevokeSTSTokenRequest.java
index 8c7832804c5..58a28539733 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/s3/security/TestS3RevokeSTSTokenRequest.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/s3/security/TestS3RevokeSTSTokenRequest.java
@@ -18,6 +18,8 @@
 package org.apache.hadoop.ozone.om.request.s3.security;
 
 import static 
org.apache.hadoop.security.authentication.util.KerberosName.DEFAULT_MECHANISM;
+import static org.apache.ozone.test.GenericTestUtils.waitFor;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -29,16 +31,27 @@
 import static org.mockito.Mockito.when;
 
 import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
 import java.util.Optional;
+import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.utils.db.BatchOperation;
 import org.apache.hadoop.hdds.utils.db.Table;
 import org.apache.hadoop.hdds.utils.db.cache.CacheKey;
 import org.apache.hadoop.ipc_.ExternalCall;
 import org.apache.hadoop.ipc_.Server;
 import org.apache.hadoop.ozone.OzoneConsts;
 import org.apache.hadoop.ozone.audit.AuditLogger;
+import org.apache.hadoop.ozone.om.OMConfigKeys;
 import org.apache.hadoop.ozone.om.OMMetadataManager;
 import org.apache.hadoop.ozone.om.OMMultiTenantManager;
+import org.apache.hadoop.ozone.om.OmMetadataManagerImpl;
 import org.apache.hadoop.ozone.om.OzoneManager;
 import org.apache.hadoop.ozone.om.S3SecretManager;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
@@ -46,6 +59,7 @@
 import org.apache.hadoop.ozone.om.request.OMClientRequest;
 import org.apache.hadoop.ozone.om.response.OMClientResponse;
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
+import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.DeleteRevokedSTSTokensRequest;
 import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Type;
 import org.apache.hadoop.security.UserGroupInformation;
@@ -53,15 +67,19 @@
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 /**
- * Tests for {@link S3RevokeSTSTokenRequest}.
+ * Tests for {@link S3RevokeSTSTokenRequest} and {@link 
S3DeleteRevokedSTSTokensRequest}.
  */
 public class TestS3RevokeSTSTokenRequest {
 
   private static final String TEST_KERBEROS_RULES =
       "RULE:[2:$1@$0](.*@EXAMPLE.COM)s/@.*//\n" + 
"RULE:[1:$1@$0](.*@EXAMPLE.COM)s/@.*//\n" + "DEFAULT";
 
+  @TempDir
+  private Path folder;
+
   private OMMultiTenantManager omMultiTenantManager;
   private String kerberosMechanismBeforeTest;
   private String kerberosRulesBeforeTest;
@@ -364,6 +382,246 @@ public void 
testPreExecuteRejectsClientSuppliedRevocationTimeMillis() throws Exc
     }
   }
 
+  @Test
+  public void testPurgeKeepsNewerCutoffOfSameKey() throws Exception {
+    // The cleanup scan read the older cutoff of keys a, b and c, then the 
purge is applied:
+    // - a: a newer cutoff is applied before the purge, so the purge must skip 
it.
+    // - b: the purge deletes it, then a newer cutoff is applied before the 
flush; the delete marker must not hide it.
+    // - c: the purge deletes it and nothing follows; its delete marker 
leaving the cache shows the cleanup has run.
+    final long olderCutoff = 1_700_000_000_000L;
+    final long newerCutoff = olderCutoff + TimeUnit.HOURS.toMillis(13);
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, "a", olderCutoff));
+      flush(omMetadataManager, 2L, revoke(ozoneManager, 2L, "b", olderCutoff));
+      flush(omMetadataManager, 3L, revoke(ozoneManager, 3L, "c", olderCutoff));
+      final OMClientResponse newerRevokeOfA = revoke(ozoneManager, 4L, "a", 
newerCutoff);
+      final OMClientResponse purge = new S3DeleteRevokedSTSTokensRequest(
+          buildPurgeOmRequest(Arrays.asList("a", "b", "c"), olderCutoff + 1))
+          .validateAndUpdateCache(ozoneManager, 5L);
+      final OMClientResponse newerRevokeOfB = revoke(ozoneManager, 6L, "b", 
newerCutoff);
+      flush(omMetadataManager, 4L, newerRevokeOfA);
+      flush(omMetadataManager, 5L, purge);
+      flush(omMetadataManager, 6L, newerRevokeOfB);
+
+      final Table<String, Long> table = 
omMetadataManager.getS3RevokedStsTokenTable();
+      assertThat(table.getSkipCache("a")).isEqualTo(newerCutoff);
+      assertThat(table.getSkipCache("c")).isNull();
+      waitFor(() -> !cachedKeys(table).contains("c"), 100, 5_000);
+      for (String originalAccessKeyId : Arrays.asList("a", "b")) {
+        
assertThat(table.getIfExist(originalAccessKeyId)).as(originalAccessKeyId).isEqualTo(newerCutoff);
+        
assertThat(table.getSkipCache(originalAccessKeyId)).as(originalAccessKeyId).isEqualTo(newerCutoff);
+      }
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  @Test
+  public void testPurgeRemovesUnchangedCutoffFromCacheAndDB() throws Exception 
{
+    final String originalAccessKeyId = "original-access-key-id";
+    final long cutoff = 1_700_000_000_000L;
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, 
originalAccessKeyId, cutoff));
+      flush(omMetadataManager, 2L, new S3DeleteRevokedSTSTokensRequest(
+          buildPurgeOmRequest(Collections.singletonList(originalAccessKeyId), 
cutoff + 1))
+          .validateAndUpdateCache(ozoneManager, 2L));
+
+      
assertRevokedEntryFullyRemoved(omMetadataManager.getS3RevokedStsTokenTable(), 
originalAccessKeyId);
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  @Test
+  public void testPurgeWithoutPurgeBeforeMillisDeletesListedEntries() throws 
Exception {
+    // A purge submitted without purgeBeforeMillis deletes the listed entries 
from the cache and the DB.
+    final String originalAccessKeyId = "original-access-key-id";
+    final long cutoff = 1_700_000_000_000L;
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, 
originalAccessKeyId, cutoff));
+      flush(omMetadataManager, 2L, new S3DeleteRevokedSTSTokensRequest(
+          
buildPurgeOmRequest(DeleteRevokedSTSTokensRequest.newBuilder().addOriginalAccessKeyId(originalAccessKeyId)))
+          .validateAndUpdateCache(ozoneManager, 2L));
+
+      
assertRevokedEntryFullyRemoved(omMetadataManager.getS3RevokedStsTokenTable(), 
originalAccessKeyId);
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  @Test
+  public void testPurgeWithoutPurgeBeforeMillisDeletesNewerCutoff() throws 
Exception {
+    // A purge submitted without purgeBeforeMillis deletes a listed entry even 
if a newer
+    // cutoff was applied after the scan
+    final String originalAccessKeyId = "original-access-key-id";
+    final long olderCutoff = 1_700_000_000_000L;
+    final long newerCutoff = olderCutoff + TimeUnit.HOURS.toMillis(13);
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, 
originalAccessKeyId, olderCutoff));
+      final OMClientResponse newerRevoke = revoke(ozoneManager, 2L, 
originalAccessKeyId, newerCutoff);
+      final OMClientResponse purge = new S3DeleteRevokedSTSTokensRequest(
+          
buildPurgeOmRequest(DeleteRevokedSTSTokensRequest.newBuilder().addOriginalAccessKeyId(originalAccessKeyId)))
+          .validateAndUpdateCache(ozoneManager, 3L);
+      flush(omMetadataManager, 2L, newerRevoke);
+      flush(omMetadataManager, 3L, purge);
+
+      
assertRevokedEntryFullyRemoved(omMetadataManager.getS3RevokedStsTokenTable(), 
originalAccessKeyId);
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  @Test
+  public void testPurgeSkipsIdAlreadyMarkedForDeletion() throws Exception {
+    // A second purge for the same id before flush sees the delete marker and 
does not delete again.
+    final String originalAccessKeyId = "original-access-key-id";
+    final long cutoff = 1_700_000_000_000L;
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, 
originalAccessKeyId, cutoff));
+      final OMRequest purgeOmRequest = 
buildPurgeOmRequest(Collections.singletonList(originalAccessKeyId), cutoff + 1);
+      final OMClientResponse firstPurge = new 
S3DeleteRevokedSTSTokensRequest(purgeOmRequest)
+          .validateAndUpdateCache(ozoneManager, 2L);
+      final OMClientResponse secondPurge = new 
S3DeleteRevokedSTSTokensRequest(purgeOmRequest)
+          .validateAndUpdateCache(ozoneManager, 3L);
+      final Table<String, Long> table = 
omMetadataManager.getS3RevokedStsTokenTable();
+      assertThat(table.getCacheValue(new 
CacheKey<>(originalAccessKeyId)).getEpoch()).isEqualTo(2L);
+      flush(omMetadataManager, 2L, firstPurge);
+      flush(omMetadataManager, 3L, secondPurge);
+
+      assertRevokedEntryFullyRemoved(table, originalAccessKeyId);
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  @Test
+  public void testPurgeDeletesReplacedCutoffThatIsAlsoExpired() throws 
Exception {
+    // A newer cutoff applied after the scan is still deleted when it is also 
older than purgeBeforeMillis, since no
+    // unexpired STS token can depend on it.
+    final String originalAccessKeyId = "original-access-key-id";
+    final long olderCutoff = 1_700_000_000_000L;
+    final long replacedCutoff = olderCutoff + TimeUnit.HOURS.toMillis(1);
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, 
originalAccessKeyId, olderCutoff));
+      final OMClientResponse replacedRevoke = revoke(ozoneManager, 2L, 
originalAccessKeyId, replacedCutoff);
+      final OMClientResponse purge = new S3DeleteRevokedSTSTokensRequest(
+          buildPurgeOmRequest(Collections.singletonList(originalAccessKeyId), 
olderCutoff + TimeUnit.HOURS.toMillis(2)))
+          .validateAndUpdateCache(ozoneManager, 3L);
+
+      flush(omMetadataManager, 2L, replacedRevoke);
+      flush(omMetadataManager, 3L, purge);
+
+      
assertRevokedEntryFullyRemoved(omMetadataManager.getS3RevokedStsTokenTable(), 
originalAccessKeyId);
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  @Test
+  public void testPurgeKeepsCutoffEqualToPurgeBeforeMillis() throws Exception {
+    // Only cutoffs strictly older than purgeBeforeMillis are deleted, so a 
cutoff equal to it stays in the cache and
+    // the DB.
+    final String originalAccessKeyId = "original-access-key-id";
+    final long cutoff = 1_700_000_000_000L;
+    final OmMetadataManagerImpl omMetadataManager = createMetadataManager();
+    try {
+      final OzoneManager ozoneManager = mockOzoneManager(omMetadataManager);
+      flush(omMetadataManager, 1L, revoke(ozoneManager, 1L, 
originalAccessKeyId, cutoff));
+      final OMClientResponse purge = new S3DeleteRevokedSTSTokensRequest(
+          buildPurgeOmRequest(Collections.singletonList(originalAccessKeyId), 
cutoff))
+          .validateAndUpdateCache(ozoneManager, 2L);
+      flush(omMetadataManager, 2L, purge);
+
+      final Table<String, Long> table = 
omMetadataManager.getS3RevokedStsTokenTable();
+      assertThat(table.getIfExist(originalAccessKeyId)).isEqualTo(cutoff);
+      assertThat(table.getSkipCache(originalAccessKeyId)).isEqualTo(cutoff);
+    } finally {
+      omMetadataManager.stop();
+    }
+  }
+
+  private OmMetadataManagerImpl createMetadataManager() throws IOException {
+    final OzoneConfiguration conf = new OzoneConfiguration();
+    conf.set(OMConfigKeys.OZONE_OM_DB_DIRS, 
folder.toAbsolutePath().toString());
+    return new OmMetadataManagerImpl(conf, null);
+  }
+
+  private static OzoneManager mockOzoneManager(OMMetadataManager 
omMetadataManager) {
+    final OzoneManager ozoneManager = mock(OzoneManager.class);
+    when(ozoneManager.getMetadataManager()).thenReturn(omMetadataManager);
+    when(ozoneManager.getAuditLogger()).thenReturn(mock(AuditLogger.class));
+    return ozoneManager;
+  }
+
+  /**
+   * Writes the response to the DB and cleans up the table cache, as the 
double buffer does.
+   */
+  private static void flush(OmMetadataManagerImpl omMetadataManager, long 
index, OMClientResponse response)
+      throws IOException {
+    try (BatchOperation batch = 
omMetadataManager.getStore().initBatchOperation()) {
+      response.checkAndUpdateDB(omMetadataManager, batch);
+      omMetadataManager.getStore().commitBatchOperation(batch);
+    }
+    
omMetadataManager.getS3RevokedStsTokenTable().cleanupCache(Collections.singletonList(index));
+  }
+
+  private static OMRequest buildReplicatedRevokeOmRequest(String 
originalAccessKeyId, long revocationTimeMillis) {
+    return OMRequest.newBuilder()
+        .setClientId(UUID.randomUUID().toString())
+        .setCmdType(Type.RevokeSTSToken)
+        
.setRevokeSTSTokenRequest(OzoneManagerProtocolProtos.RevokeSTSTokenRequest.newBuilder()
+            .setOriginalAccessKeyId(originalAccessKeyId)
+            .setRevocationTimeMillis(revocationTimeMillis))
+        .build();
+  }
+
+  private static OMRequest buildPurgeOmRequest(List<String> 
originalAccessKeyIds, long purgeBeforeMillis) {
+    return buildPurgeOmRequest(DeleteRevokedSTSTokensRequest.newBuilder()
+        .addAllOriginalAccessKeyId(originalAccessKeyIds)
+        .setPurgeBeforeMillis(purgeBeforeMillis));
+  }
+
+  private static OMRequest 
buildPurgeOmRequest(DeleteRevokedSTSTokensRequest.Builder purgeRequest) {
+    return OMRequest.newBuilder()
+        .setClientId(UUID.randomUUID().toString())
+        .setCmdType(Type.DeleteRevokedSTSTokens)
+        .setDeleteRevokedSTSTokensRequest(purgeRequest)
+        .build();
+  }
+
+  private static OMClientResponse revoke(OzoneManager ozoneManager, long 
index, String originalAccessKeyId,
+      long revocationTimeMillis) {
+    return new S3RevokeSTSTokenRequest(
+        buildReplicatedRevokeOmRequest(originalAccessKeyId, 
revocationTimeMillis))
+        .validateAndUpdateCache(ozoneManager, index);
+  }
+
+  private static Set<String> cachedKeys(Table<String, Long> table) {
+    final Set<String> keys = new HashSet<>();
+    table.cacheIterator().forEachRemaining(entry -> 
keys.add(entry.getKey().getCacheKey()));
+    return keys;
+  }
+
+  private static void assertRevokedEntryFullyRemoved(Table<String, Long> 
table, String originalAccessKeyId)
+      throws Exception {
+    assertThat(table.getIfExist(originalAccessKeyId)).isNull();
+    assertThat(table.getSkipCache(originalAccessKeyId)).isNull();
+    // The full table cache evicts flushed delete markers in the background
+    waitFor(() -> !table.cacheIterator().hasNext(), 100, 5_000);
+  }
+
   private static OMRequest buildRevokeOmRequest(String originalAccessKeyId) {
     final OzoneManagerProtocolProtos.RevokeSTSTokenRequest revokeRequest =
         OzoneManagerProtocolProtos.RevokeSTSTokenRequest.newBuilder()
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestRevokedSTSTokenCleanupService.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestRevokedSTSTokenCleanupService.java
index dd9b30454f5..8d4149bb807 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestRevokedSTSTokenCleanupService.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestRevokedSTSTokenCleanupService.java
@@ -38,6 +38,7 @@
 import org.apache.hadoop.ozone.om.OMConfigKeys;
 import org.apache.hadoop.ozone.om.OMMetadataManager;
 import org.apache.hadoop.ozone.om.OzoneManager;
+import org.apache.hadoop.ozone.om.helpers.S3STSUtils;
 import org.apache.hadoop.ozone.om.ratis.utils.OzoneManagerRatisUtils;
 import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.DeleteRevokedSTSTokensRequest;
 import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
@@ -101,6 +102,10 @@ public void submitsCleanupRequestForOnlyExpiredTokens() 
throws Exception {
       final DeleteRevokedSTSTokensRequest deleteRevokedSTSTokensRequest =
           omRequest.getDeleteRevokedSTSTokensRequest();
       
assertThat(deleteRevokedSTSTokensRequest.getOriginalAccessKeyIdList()).containsExactly("original-access-key-a");
+      final long cleanupThresholdMillis = 
TimeUnit.SECONDS.toMillis(S3STSUtils.MAX_DURATION_SECONDS);
+      
assertThat(deleteRevokedSTSTokensRequest.hasPurgeBeforeMillis()).isTrue();
+      assertThat(deleteRevokedSTSTokensRequest.getPurgeBeforeMillis())
+          .isBetween(nowMillis - cleanupThresholdMillis, 
System.currentTimeMillis() - cleanupThresholdMillis);
     }
   }
 
@@ -249,6 +254,10 @@ public void 
submitsMultipleRequestsWhenBatchSizeIsExceeded() throws Exception {
           .sum();
       assertThat(totalTokens).isEqualTo(10);
       
assertThat(revokedSTSTokenCleanupService.getSubmittedDeletedEntryCount()).isEqualTo(10);
+
+      // Every request of the run carries the same purgeBeforeMillis
+      
assertThat(capturedRequests.get(1).getDeleteRevokedSTSTokensRequest().getPurgeBeforeMillis())
+          
.isEqualTo(capturedRequests.get(0).getDeleteRevokedSTSTokensRequest().getPurgeBeforeMillis());
     }
   }
 
@@ -256,7 +265,7 @@ public void 
submitsMultipleRequestsWhenBatchSizeIsExceeded() throws Exception {
   public void testSingleOversizedExpiredTokenAndItIsTheOnlyExpiredToken() 
throws Exception {
     // One originalAccessKeyId is larger than the ratisByteLimit, and it is 
the only expired entry
     final long nowMillis = testClock.millis();
-    // Serialized size for largeToken is 102 > 90 (the effective 
ratisByteLimit) .
+    // Serialized size for largeToken is 109 > 90 (the effective 
ratisByteLimit) .
     final String largeToken = new String(new char[100]).replace('\0', 'a');
     revokedStsTokenTable.put(largeToken, nowMillis - 
TimeUnit.HOURS.toMillis(13));
 
@@ -336,7 +345,8 @@ public void 
testExpiredAndNonExpiredTokensWithSmallRatisByteLimit() throws Excep
   public void testExpiredTokenMatchesRatisByteLimitExactly() throws Exception {
     // Force small batch of 100 bytes and test when the batch size is exactly 
ratisByteLimit
     final long nowMillis = testClock.millis();
-    final String tokenMatchingRatisByteLimitWhenSerialized = new String(new 
char[88]).replace('\0', 'a');
+    // Serialized size is 90: 83 bytes for the originalAccessKeyId field and 7 
bytes for purgeBeforeMillis.
+    final String tokenMatchingRatisByteLimitWhenSerialized = new String(new 
char[81]).replace('\0', 'a');
 
     revokedStsTokenTable.put(tokenMatchingRatisByteLimitWhenSerialized, 
nowMillis - TimeUnit.HOURS.toMillis(13));
 


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to