mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(iam): anchor Marker on the last item returned instead of a list index (#6096)
* fix(iam): anchor Marker on the last item returned instead of a list index * fix(iam): refuse an anchored Marker the handler did not issue * test(iam): pin ListPolicies resuming after a deleted customer-managed policy * refactor: share signed pagination markers between IAM and Lambda layers
This commit is contained in:
1 parent
6e5b3c6c1d
commit
4519aea69f
5 files changed
+289
-75
No files matched your search
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Pagination markers that name a cursor, as AWS's opaque tokens do. Each marker is signed with a
|
||||
* key generated for this instance, so a fabricated or edited marker is not recognised, and one
|
||||
* from an earlier run is stale, as an expired AWS token would be.
|
||||
*/
|
||||
public final class SignedMarkers {
|
||||
|
||||
private static final char SEPARATOR = '.';
|
||||
|
||||
private final byte[] key = newKey();
|
||||
|
||||
public String issue(String cursor) {
|
||||
return Base64Url.encode(cursor + SEPARATOR + sign(cursor));
|
||||
}
|
||||
|
||||
/** The cursor a marker names, or null when this instance did not issue it. */
|
||||
public String cursorOf(String marker) {
|
||||
String decoded;
|
||||
try {
|
||||
decoded = new String(Base64.getUrlDecoder().decode(marker), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException notIssued) {
|
||||
// Not base64url, so not a marker this instance issued.
|
||||
return null;
|
||||
}
|
||||
int separator = decoded.lastIndexOf(SEPARATOR);
|
||||
if (separator < 0) {
|
||||
return null;
|
||||
}
|
||||
String cursor = decoded.substring(0, separator);
|
||||
byte[] presented = decoded.substring(separator + 1).getBytes(StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(presented, sign(cursor).getBytes(StandardCharsets.UTF_8))) {
|
||||
return null;
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
private String sign(String cursor) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return Base64Url.encode(mac.doFinal(cursor.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("HmacSHA256 is required to sign pagination markers", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] newKey() {
|
||||
byte[] key = new byte[32];
|
||||
new SecureRandom().nextBytes(key);
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -86,6 +87,8 @@ public class IamQueryHandler {
|
||||
private final DelegationRequestService delegationRequestService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders;
|
||||
/** Signs each page's Marker, so only a marker this handler issued names an item. */
|
||||
private final SignedMarkers markers = new SignedMarkers();
|
||||
|
||||
@Inject
|
||||
public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator,
|
||||
@@ -460,7 +463,8 @@ public class IamQueryHandler {
|
||||
*/
|
||||
private Response handleListVirtualMFADevices(MultivaluedMap<String, String> params) {
|
||||
Page<VirtualMfaDevice> page = paginate(
|
||||
iamService.listVirtualMfaDevices(getParam(params, "AssignmentStatus")), params);
|
||||
iamService.listVirtualMfaDevices(getParam(params, "AssignmentStatus")),
|
||||
VirtualMfaDevice::getSerialNumber, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("VirtualMFADevices");
|
||||
for (VirtualMfaDevice device : page.items()) {
|
||||
xml.start("member").elem("SerialNumber", device.getSerialNumber());
|
||||
@@ -509,7 +513,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListMFADevices(MultivaluedMap<String, String> params, String authorization) {
|
||||
String userName = resolveUserName(params, authorization);
|
||||
Page<VirtualMfaDevice> page = paginate(iamService.listMfaDevices(userName), params);
|
||||
Page<VirtualMfaDevice> page = paginate(iamService.listMfaDevices(userName), VirtualMfaDevice::getSerialNumber, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("MFADevices");
|
||||
for (VirtualMfaDevice device : page.items()) {
|
||||
xml.start("member")
|
||||
@@ -543,7 +547,7 @@ public class IamQueryHandler {
|
||||
*/
|
||||
private Response handleListMFADeviceTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> tags = new TreeMap<>(iamService.listMfaDeviceTags(getParam(params, "SerialNumber")));
|
||||
Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), params);
|
||||
Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), Map.Entry::getKey, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("Tags");
|
||||
for (Map.Entry<String, String> tag : page.items()) {
|
||||
xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
|
||||
@@ -840,7 +844,8 @@ public class IamQueryHandler {
|
||||
*/
|
||||
private Response handleListServerCertificates(MultivaluedMap<String, String> params) {
|
||||
Page<ServerCertificate> page = paginate(
|
||||
iamService.listServerCertificates(getParam(params, "PathPrefix")), params);
|
||||
iamService.listServerCertificates(getParam(params, "PathPrefix")),
|
||||
ServerCertificate::getServerCertificateName, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("ServerCertificateMetadataList");
|
||||
for (ServerCertificate certificate : page.items()) {
|
||||
xml.start("member").raw(serverCertificateMetadataXml(certificate)).end("member");
|
||||
@@ -883,7 +888,8 @@ public class IamQueryHandler {
|
||||
String userName = allUsers ? null : resolveUserName(params, authorization);
|
||||
Page<ServiceSpecificCredential> page = paginate(
|
||||
iamService.listServiceSpecificCredentials(
|
||||
userName, getParam(params, "ServiceName"), allUsers), params);
|
||||
userName, getParam(params, "ServiceName"), allUsers),
|
||||
ServiceSpecificCredential::getServiceSpecificCredentialId, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("ServiceSpecificCredentials");
|
||||
for (ServiceSpecificCredential credential : page.items()) {
|
||||
xml.start("member").raw(serviceCredentialXml(credential, false)).end("member");
|
||||
@@ -1006,7 +1012,8 @@ public class IamQueryHandler {
|
||||
private Response handleListSshPublicKeys(MultivaluedMap<String, String> params,
|
||||
String authorization) {
|
||||
Page<SshPublicKey> page = paginate(
|
||||
iamService.listSshPublicKeys(resolveUserName(params, authorization)), params);
|
||||
iamService.listSshPublicKeys(resolveUserName(params, authorization)),
|
||||
SshPublicKey::getSshPublicKeyId, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("SSHPublicKeys");
|
||||
for (SshPublicKey key : page.items()) {
|
||||
xml.start("member")
|
||||
@@ -1067,7 +1074,8 @@ public class IamQueryHandler {
|
||||
private Response handleListSigningCertificates(MultivaluedMap<String, String> params,
|
||||
String authorization) {
|
||||
Page<SigningCertificate> page = paginate(
|
||||
iamService.listSigningCertificates(resolveUserName(params, authorization)), params);
|
||||
iamService.listSigningCertificates(resolveUserName(params, authorization)),
|
||||
SigningCertificate::getCertificateId, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("Certificates");
|
||||
for (SigningCertificate certificate : page.items()) {
|
||||
xml.start("member").raw(signingCertificateXml(certificate)).end("member");
|
||||
@@ -1120,7 +1128,7 @@ public class IamQueryHandler {
|
||||
private Response handleListServerCertificateTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> tags = new TreeMap<>(iamService.listServerCertificateTags(
|
||||
getParam(params, "ServerCertificateName")));
|
||||
Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), params);
|
||||
Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), Map.Entry::getKey, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("Tags");
|
||||
for (Map.Entry<String, String> tag : page.items()) {
|
||||
xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
|
||||
@@ -1405,7 +1413,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleListRoles(MultivaluedMap<String, String> params) {
|
||||
Page<IamRole> page = paginate(iamService.listRoles(getParam(params, "PathPrefix")), params);
|
||||
Page<IamRole> page = paginate(iamService.listRoles(getParam(params, "PathPrefix")), IamRole::getRoleName, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("Roles");
|
||||
for (IamRole r : page.items()) {
|
||||
xml.start("member").raw(roleXml(r, false)).end("member");
|
||||
@@ -1493,7 +1501,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListPolicies(MultivaluedMap<String, String> params) {
|
||||
Page<IamPolicy> page = paginate(iamService.listPolicies(
|
||||
getParam(params, "Scope"), getParam(params, "PathPrefix")), params);
|
||||
getParam(params, "Scope"), getParam(params, "PathPrefix")), IamQueryHandler::policyKey, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("Policies");
|
||||
for (IamPolicy p : page.items()) {
|
||||
xml.start("member").raw(policyXml(p, false)).end("member");
|
||||
@@ -2280,7 +2288,7 @@ public class IamQueryHandler {
|
||||
String authorization) {
|
||||
ServiceLastAccessedJob job = serviceLastAccessedService.get(
|
||||
accountResolver.resolve(authorization), requireParam(params, "JobId"));
|
||||
Page<String> page = paginate(job.getServiceNamespaces(), params);
|
||||
Page<String> page = paginate(job.getServiceNamespaces(), Function.identity(), params);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("JobStatus", "COMPLETED")
|
||||
.elem("JobType", job.getGranularity())
|
||||
@@ -2357,7 +2365,7 @@ public class IamQueryHandler {
|
||||
.build())).build();
|
||||
}
|
||||
List<String> namespaces = sortedByKey(job.getServiceNamespaces(), sortKey);
|
||||
Page<String> page = paginate(namespaces, params);
|
||||
Page<String> page = paginate(namespaces, Function.identity(), params);
|
||||
xml.elem("NumberOfServicesAccessible", namespaces.size())
|
||||
.elem("NumberOfServicesNotAccessed", namespaces.size())
|
||||
.start("AccessDetails");
|
||||
@@ -2427,7 +2435,7 @@ public class IamQueryHandler {
|
||||
// The report named the services it covers, so an entity is only reported for one of those.
|
||||
List<ServiceLastAccessedEntity> reported = job.getServiceNamespaces().contains(namespace)
|
||||
? job.getEntities() : List.of();
|
||||
Page<ServiceLastAccessedEntity> page = paginate(reported, params);
|
||||
Page<ServiceLastAccessedEntity> page = paginate(reported, ServiceLastAccessedEntity::getArn, params);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("JobStatus", "COMPLETED")
|
||||
.elem("JobCreationDate", isoDate(job.getJobCreationDate()))
|
||||
@@ -2468,7 +2476,7 @@ public class IamQueryHandler {
|
||||
List<GrantingPolicy> candidates = policiesForIdentity(accountId, arn);
|
||||
// The response list carries one entry per requested namespace, so that is what a Marker
|
||||
// walks through.
|
||||
Page<String> page = paginateByMarker(namespaces, params);
|
||||
Page<String> page = paginateByMarker(namespaces, Function.identity(), params);
|
||||
XmlBuilder xml = new XmlBuilder().start("PoliciesGrantingServiceAccess");
|
||||
for (String namespace : page.items()) {
|
||||
xml.start("member").elem("ServiceNamespace", namespace).start("Policies");
|
||||
@@ -2601,7 +2609,8 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListDelegationRequests(MultivaluedMap<String, String> params) {
|
||||
Page<DelegationRequest> page = paginate(delegationRequestService.list(
|
||||
regionResolver.getAccountId(), getParam(params, "OwnerId")), params);
|
||||
regionResolver.getAccountId(), getParam(params, "OwnerId")),
|
||||
DelegationRequest::getDelegationRequestId, params);
|
||||
XmlBuilder xml = new XmlBuilder().start("DelegationRequests");
|
||||
for (DelegationRequest request : page.items()) {
|
||||
xml.start("member").raw(delegationRequestXml(request)).end("member");
|
||||
@@ -2768,12 +2777,13 @@ public class IamQueryHandler {
|
||||
private record Page<T>(List<T> items, boolean truncated, String marker) {}
|
||||
|
||||
/**
|
||||
* Applies {@code MaxItems} and {@code Marker}. The marker is the index the next page starts at,
|
||||
* which is all a caller is meant to do with it: AWS documents it as opaque and only ever hands
|
||||
* back one it produced itself.
|
||||
* Applies {@code MaxItems} and {@code Marker}. The marker names the last item of the page
|
||||
* before by {@code keyOf}, so the next page continues after that item wherever it now sits:
|
||||
* the API reference documents it as the place "where the next call should start", and an item
|
||||
* created or deleted ahead of it skips nothing and repeats nothing.
|
||||
*/
|
||||
private <T> Page<T> paginate(List<T> items, MultivaluedMap<String, String> params) {
|
||||
return paginate(items, params, true);
|
||||
private <T> Page<T> paginate(List<T> items, Function<T, String> keyOf, MultivaluedMap<String, String> params) {
|
||||
return paginate(items, keyOf, params, true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2781,14 +2791,16 @@ public class IamQueryHandler {
|
||||
* {@code Marker} but no {@code MaxItems}, and honouring a member AWS does not declare would be
|
||||
* inventing one.
|
||||
*/
|
||||
private <T> Page<T> paginateByMarker(List<T> items, MultivaluedMap<String, String> params) {
|
||||
return paginate(items, params, false);
|
||||
private <T> Page<T> paginateByMarker(List<T> items, Function<T, String> keyOf,
|
||||
MultivaluedMap<String, String> params) {
|
||||
return paginate(items, keyOf, params, false);
|
||||
}
|
||||
|
||||
private <T> Page<T> paginate(List<T> items, MultivaluedMap<String, String> params, boolean maxItemsModeled) {
|
||||
private <T> Page<T> paginate(List<T> items, Function<T, String> keyOf, MultivaluedMap<String, String> params,
|
||||
boolean maxItemsModeled) {
|
||||
// Every input is validated before the bounds check, so a malformed request is rejected
|
||||
// rather than answered emptily just because the marker happens to sit past the end.
|
||||
int from = markerIndex(params);
|
||||
int from = resumeIndex(items, keyOf, params);
|
||||
// An omitted MaxItems is not "no limit": the API reference states the count "defaults to
|
||||
// 100" on each reader paged here, so a list wider than that is truncated with a Marker as
|
||||
// it would be against AWS. Operations that model no MaxItems at all pass through whole.
|
||||
@@ -2820,15 +2832,48 @@ public class IamQueryHandler {
|
||||
int to = from + Math.min(limit, items.size() - from);
|
||||
boolean truncated = to < items.size();
|
||||
return new Page<>(List.copyOf(items.subList(from, to)), truncated,
|
||||
truncated ? Integer.toString(to) : null);
|
||||
truncated ? markers.issue(keyOf.apply(items.get(to - 1))) : null);
|
||||
}
|
||||
|
||||
/** The index a {@code Marker} resumes at. Only a marker this handler produced is valid. */
|
||||
private int markerIndex(MultivaluedMap<String, String> params) {
|
||||
/**
|
||||
* Where a {@code Marker} resumes: after the item it names. When that item is gone, at the first
|
||||
* item whose key sorts after it, since every list whose items can be deleted is ordered by the
|
||||
* key its reader passes. A marker this handler did not issue is read as an index, as before.
|
||||
*/
|
||||
private <T> int resumeIndex(List<T> items, Function<T, String> keyOf, MultivaluedMap<String, String> params) {
|
||||
String marker = params.getFirst("Marker");
|
||||
if (marker == null || marker.isBlank()) {
|
||||
return 0;
|
||||
}
|
||||
String anchor = markers.cursorOf(marker.trim());
|
||||
if (anchor == null) {
|
||||
return markerIndex(marker);
|
||||
}
|
||||
for (int i = 0; i < items.size(); i++) {
|
||||
if (keyOf.apply(items.get(i)).equals(anchor)) {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < items.size(); i++) {
|
||||
if (keyOf.apply(items.get(i)).compareTo(anchor) > 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return items.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* ListPolicies lists customer-managed policies by name, then the AWS-managed catalog, which
|
||||
* never changes. The key keeps that order, so a deleted customer-managed policy resumes at the
|
||||
* next one, and names the managed policy by ARN, as a customer policy may share its name.
|
||||
*/
|
||||
private static String policyKey(IamPolicy policy) {
|
||||
return AwsManagedPolicies.isManagedPolicyArn(policy.getArn())
|
||||
? "1" + policy.getArn() : "0" + policy.getPolicyName();
|
||||
}
|
||||
|
||||
/** The index a marker this handler did not issue resumes at, as markers were read before. */
|
||||
private static int markerIndex(String marker) {
|
||||
int index;
|
||||
try {
|
||||
index = Integer.parseInt(marker.trim());
|
||||
|
||||
@@ -3,10 +3,10 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.FileTrees;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SignedMarkers;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
|
||||
import io.github.hectorvent.floci.services.lambda.zip.DeploymentPackage;
|
||||
@@ -16,14 +16,8 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -57,10 +51,8 @@ public class LambdaLayerService {
|
||||
private static final int MAX_LAYER_VERSION_ARN_LENGTH = 140;
|
||||
private static final int MAX_ITEMS_LIMIT = 50;
|
||||
|
||||
private static final char MARKER_SEPARATOR = '.';
|
||||
|
||||
/** Signing key for pagination markers, per process; see {@link #encodeMarker}. */
|
||||
private static final byte[] MARKER_KEY = newMarkerKey();
|
||||
/** Signs pagination markers; see {@link #decodeMarker}. */
|
||||
private final SignedMarkers markers = new SignedMarkers();
|
||||
|
||||
private static final List<String> COMPATIBLE_ARCHITECTURES = List.of("x86_64", "arm64");
|
||||
|
||||
@@ -285,7 +277,7 @@ public class LambdaLayerService {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static <T> PaginatedResult<T> page(List<T> items, Function<T, String> cursorOf,
|
||||
private <T> PaginatedResult<T> page(List<T> items, Function<T, String> cursorOf,
|
||||
Integer maxItems, String marker) {
|
||||
String after = decodeMarker(marker);
|
||||
List<T> remaining = after == null ? items
|
||||
@@ -294,7 +286,7 @@ public class LambdaLayerService {
|
||||
.limit(maxItems != null ? maxItems : MAX_ITEMS_LIMIT)
|
||||
.toList();
|
||||
String nextMarker = pageItems.size() < remaining.size()
|
||||
? encodeMarker(cursorOf.apply(pageItems.get(pageItems.size() - 1)))
|
||||
? markers.issue(cursorOf.apply(pageItems.get(pageItems.size() - 1)))
|
||||
: null;
|
||||
return new PaginatedResult<>(pageItems, nextMarker);
|
||||
}
|
||||
@@ -358,49 +350,17 @@ public class LambdaLayerService {
|
||||
* silently skipped or empty page. A marker from an earlier run is stale for the same
|
||||
* reason, matching a client that replays an expired token against AWS.
|
||||
*/
|
||||
private static String encodeMarker(String cursor) {
|
||||
String signed = cursor + MARKER_SEPARATOR + sign(cursor);
|
||||
return Base64Url.encode(signed);
|
||||
}
|
||||
|
||||
private static String decodeMarker(String marker) {
|
||||
private String decodeMarker(String marker) {
|
||||
if (marker == null) {
|
||||
return null;
|
||||
}
|
||||
String decoded;
|
||||
try {
|
||||
decoded = new String(Base64.getUrlDecoder().decode(marker), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalidPaginationKey();
|
||||
}
|
||||
int separator = decoded.lastIndexOf(MARKER_SEPARATOR);
|
||||
if (separator < 0) {
|
||||
throw invalidPaginationKey();
|
||||
}
|
||||
String cursor = decoded.substring(0, separator);
|
||||
byte[] presented = decoded.substring(separator + 1).getBytes(StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(presented, sign(cursor).getBytes(StandardCharsets.UTF_8))) {
|
||||
String cursor = markers.cursorOf(marker);
|
||||
if (cursor == null) {
|
||||
throw invalidPaginationKey();
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
private static String sign(String cursor) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(MARKER_KEY, "HmacSHA256"));
|
||||
return Base64Url.encode(mac.doFinal(cursor.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("HmacSHA256 is required to paginate layers", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] newMarkerKey() {
|
||||
byte[] key = new byte[32];
|
||||
new SecureRandom().nextBytes(key);
|
||||
return key;
|
||||
}
|
||||
|
||||
private static AwsException invalidPaginationKey() {
|
||||
return new AwsException("InvalidParameterValueException", "Invalid pagination key.", 400);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
class SignedMarkersTest {
|
||||
|
||||
private final SignedMarkers markers = new SignedMarkers();
|
||||
|
||||
@Test
|
||||
void anIssuedMarkerNamesItsCursor() {
|
||||
assertEquals("role.with.dots", markers.cursorOf(markers.issue("role.with.dots")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMarkerIssuedByAnotherInstanceIsNotRecognised() {
|
||||
assertNull(markers.cursorOf(new SignedMarkers().issue("role-b")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsignedOrUndecodableMarkerIsNotRecognised() {
|
||||
assertNull(markers.cursorOf(Base64Url.encode("role-b")));
|
||||
assertNull(markers.cursorOf(Base64Url.encode("role-b.forged")));
|
||||
assertNull(markers.cursorOf("not base64!"));
|
||||
}
|
||||
}
|
||||
+119
@@ -5,7 +5,9 @@ import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
@@ -243,4 +245,121 @@ class IamListPaginationIntegrationTest {
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The API reference documents Marker as the place "where the next call should start", so a
|
||||
* continuation returns the roles after the ones already seen, whatever happened ahead of it.
|
||||
*/
|
||||
@Test
|
||||
void aRoleDeletedAheadOfTheMarkerSkipsNoRoleOnTheNextPage() {
|
||||
String tag = suffix();
|
||||
String path = "/pg-anchor-deleted-" + tag + "/";
|
||||
List<String> names = roleNames(tag, 5);
|
||||
names.forEach(name -> createRole(name, path));
|
||||
List<String> remaining = new ArrayList<>(names);
|
||||
try {
|
||||
Page first = rolePage(path, "2", null);
|
||||
assertEquals(names.subList(0, 2), first.names());
|
||||
|
||||
deleteRole(names.getFirst());
|
||||
remaining.remove(names.getFirst());
|
||||
|
||||
assertEquals(names.subList(2, 5), flatten(walk(marker -> rolePage(path, "2",
|
||||
marker == null ? first.marker() : marker))));
|
||||
} finally {
|
||||
remaining.forEach(IamListPaginationIntegrationTest::deleteRole);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleCreatedAheadOfTheMarkerReturnsNoRoleTwice() {
|
||||
String tag = suffix();
|
||||
String path = "/pg-anchor-created-" + tag + "/";
|
||||
List<String> names = roleNames(tag, 5);
|
||||
names.subList(1, 5).forEach(name -> createRole(name, path));
|
||||
try {
|
||||
Page first = rolePage(path, "2", null);
|
||||
assertEquals(names.subList(1, 3), first.names());
|
||||
|
||||
createRole(names.getFirst(), path);
|
||||
|
||||
assertEquals(names.subList(3, 5), flatten(walk(marker -> rolePage(path, "2",
|
||||
marker == null ? first.marker() : marker))));
|
||||
} finally {
|
||||
names.forEach(IamListPaginationIntegrationTest::deleteRole);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLastRoleOfAPageDeletedBeforeTheNextPageSkipsNoRole() {
|
||||
String tag = suffix();
|
||||
String path = "/pg-anchor-gone-" + tag + "/";
|
||||
List<String> names = roleNames(tag, 5);
|
||||
names.forEach(name -> createRole(name, path));
|
||||
List<String> remaining = new ArrayList<>(names);
|
||||
try {
|
||||
Page first = rolePage(path, "2", null);
|
||||
assertEquals(names.subList(0, 2), first.names());
|
||||
|
||||
deleteRole(names.get(1));
|
||||
remaining.remove(names.get(1));
|
||||
|
||||
assertEquals(names.subList(2, 5), flatten(walk(marker -> rolePage(path, "2",
|
||||
marker == null ? first.marker() : marker))));
|
||||
} finally {
|
||||
remaining.forEach(IamListPaginationIntegrationTest::deleteRole);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ListPolicies lists customer-managed policies before the AWS-managed catalog. A marker naming
|
||||
* the last customer-managed policy, deleted before the next page, resumes at the first
|
||||
* AWS-managed one, although its name sorts after every managed policy's ARN.
|
||||
*/
|
||||
@Test
|
||||
void aDeletedCustomerManagedPolicyResumesAtTheNextPolicyInListPoliciesOrder() {
|
||||
String name = "zzzz-pg-anchor-" + suffix();
|
||||
String arn = createPolicy(name, "/pg-anchor-policy/");
|
||||
boolean deleted = false;
|
||||
try {
|
||||
List<String> all = flatten(walk(marker -> policyPage("All", null, "1000", marker)));
|
||||
int index = all.indexOf(arn);
|
||||
assertTrue(index >= 0, "the created policy is listed");
|
||||
String following = all.get(index + 1);
|
||||
assertTrue(following.startsWith("arn:aws:iam::aws:policy/"),
|
||||
"the policy is the last customer-managed one: " + following);
|
||||
|
||||
Page first = policyPage("All", null, Integer.toString(index + 1), null);
|
||||
assertEquals(arn, first.names().getLast());
|
||||
|
||||
deletePolicy(arn);
|
||||
deleted = true;
|
||||
|
||||
assertEquals(List.of(following), policyPage("All", null, "1", first.marker()).names());
|
||||
} finally {
|
||||
if (!deleted) {
|
||||
deletePolicy(arn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A marker shaped like an issued one but never issued is refused, as any other unissued marker is. */
|
||||
@Test
|
||||
void listRolesRejectsAnAnchoredMarkerItDidNotIssue() {
|
||||
String forged = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString("pg-anchor-forged.not-a-signature".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
iam("ListRoles").formParam("Marker", forged)
|
||||
.when().post("/").then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
|
||||
}
|
||||
|
||||
private static List<String> roleNames(String tag, int count) {
|
||||
List<String> names = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
names.add("pg-anchor-" + tag + "-" + i);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user