|
| 1 | +package io.apimatic.core.security; |
| 2 | + |
| 3 | +import io.apimatic.coreinterfaces.http.request.Request; |
| 4 | +import io.apimatic.coreinterfaces.security.SignatureVerifier; |
| 5 | +import io.apimatic.coreinterfaces.security.VerificationResult; |
| 6 | + |
| 7 | +import javax.crypto.Mac; |
| 8 | +import javax.crypto.spec.SecretKeySpec; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | +import java.security.MessageDigest; |
| 11 | +import java.util.Map; |
| 12 | +import java.util.concurrent.CompletableFuture; |
| 13 | +import java.util.function.Function; |
| 14 | + |
| 15 | +/** |
| 16 | + * HMAC-based signature verifier for HTTP requests. |
| 17 | + * <p> |
| 18 | + * Supports signature templates such as: |
| 19 | + * <ul> |
| 20 | + * <li>{@code Sha256={digest}}</li> |
| 21 | + * <li>{@code Sha256={digest}=abc}</li> |
| 22 | + * <li>{@code signature="{digest}"; ts=1690000000}</li> |
| 23 | + * </ul> |
| 24 | + * The template is matched inside the header value (noise tolerated before/after). |
| 25 | + */ |
| 26 | +public class HmacSignatureVerifier implements SignatureVerifier { |
| 27 | + private static final String SIGNATURE_VALUE_PLACEHOLDER = "{digest}"; |
| 28 | + |
| 29 | + /** Name of the header carrying the provided signature (lookup is case-insensitive). */ |
| 30 | + private final String signatureHeaderName; |
| 31 | + |
| 32 | + /** HMAC algorithm used for signature generation (default: HmacSHA256). */ |
| 33 | + private final String algorithm; |
| 34 | + |
| 35 | + /** Initialized key spec; used to create a new Mac per verification call. */ |
| 36 | + private final SecretKeySpec keySpec; |
| 37 | + |
| 38 | + /** Template containing "{digest}". */ |
| 39 | + private final String signatureValueTemplate; |
| 40 | + |
| 41 | + /** Resolves the bytes to sign from the request. */ |
| 42 | + private final Function<Request, byte[]> requestBytesResolver; |
| 43 | + |
| 44 | + /** Codec used to decode (and possibly encode) digest text ↔ bytes (e.g., hex/base64). */ |
| 45 | + private final DigestCodec digestCodec; |
| 46 | + |
| 47 | + /** |
| 48 | + * Initializes a new instance of the HmacSignatureVerifier class. |
| 49 | + * |
| 50 | + * @param secretKey Secret key for HMAC computation. |
| 51 | + * @param signatureHeaderName Name of the header containing the signature. |
| 52 | + * @param digestCodec Encoding type for the signature. |
| 53 | + * @param requestBytesResolver Optional custom resolver for extracting data to sign. |
| 54 | + * @param algorithm Algorithm (default HmacSHA256). |
| 55 | + * @param signatureValueTemplate Template for signature format. |
| 56 | + */ |
| 57 | + public HmacSignatureVerifier( |
| 58 | + final String secretKey, |
| 59 | + final String signatureHeaderName, |
| 60 | + final DigestCodec digestCodec, |
| 61 | + final Function<Request, byte[]> requestBytesResolver, |
| 62 | + final String algorithm, |
| 63 | + final String signatureValueTemplate |
| 64 | + ) { |
| 65 | + |
| 66 | + if (secretKey == null || secretKey.trim().isEmpty()) { |
| 67 | + throw new IllegalArgumentException("Secret key cannot be null or Empty."); |
| 68 | + } |
| 69 | + if (signatureHeaderName == null || signatureHeaderName.trim().isEmpty()) { |
| 70 | + throw new IllegalArgumentException("Signature header cannot be null or Empty."); |
| 71 | + } |
| 72 | + if (signatureValueTemplate == null || signatureValueTemplate.trim().isEmpty()) { |
| 73 | + throw new IllegalArgumentException("Signature value template cannot be null or Empty."); |
| 74 | + } |
| 75 | + if (requestBytesResolver == null) { |
| 76 | + throw new IllegalArgumentException( |
| 77 | + "Request signature template resolver function cannot be null."); |
| 78 | + } |
| 79 | + if (digestCodec == null) { |
| 80 | + throw new IllegalArgumentException("Digest encoding cannot be null."); |
| 81 | + } |
| 82 | + if (algorithm == null || algorithm.trim().isEmpty()) { |
| 83 | + throw new IllegalArgumentException("Algorithm cannot be null or Empty."); |
| 84 | + } |
| 85 | + |
| 86 | + this.signatureHeaderName = signatureHeaderName; |
| 87 | + this.algorithm = algorithm; |
| 88 | + this.keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), algorithm); |
| 89 | + this.signatureValueTemplate = signatureValueTemplate; |
| 90 | + this.requestBytesResolver = requestBytesResolver; |
| 91 | + this.digestCodec = digestCodec; |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * Verifies the HMAC signature of the specified HTTP request. |
| 96 | + * |
| 97 | + * @param request The HTTP request to verify. |
| 98 | + * @return A CompletableFuture containing the verification result. |
| 99 | + */ |
| 100 | + @Override |
| 101 | + public CompletableFuture<VerificationResult> verifyAsync(final Request request) { |
| 102 | + return CompletableFuture.supplyAsync(() -> { |
| 103 | + try { |
| 104 | + String headerValue = request.getHeaders().asSimpleMap().entrySet().stream() |
| 105 | + .filter(e -> e.getKey() != null |
| 106 | + && e.getKey().equalsIgnoreCase(signatureHeaderName)) |
| 107 | + .map(Map.Entry::getValue) |
| 108 | + .findFirst() |
| 109 | + .orElse(null); |
| 110 | + |
| 111 | + if (headerValue == null) { |
| 112 | + return VerificationResult.failure( |
| 113 | + "Signature header '" + signatureHeaderName + "' is missing."); |
| 114 | + } |
| 115 | + |
| 116 | + byte[] provided = extractSignature(headerValue); |
| 117 | + if (provided == null || provided.length == 0) { |
| 118 | + return VerificationResult.failure( |
| 119 | + "Malformed signature header '" + signatureHeaderName + "'."); |
| 120 | + } |
| 121 | + |
| 122 | + byte[] message = requestBytesResolver.apply(request); |
| 123 | + // HMAC per call (thread-safe) |
| 124 | + Mac mac = Mac.getInstance(algorithm); |
| 125 | + mac.init(keySpec); |
| 126 | + byte[] computed = mac.doFinal(message); |
| 127 | + |
| 128 | + return MessageDigest.isEqual(provided, computed) |
| 129 | + ? VerificationResult.success() |
| 130 | + : VerificationResult.failure("Signature verification failed."); |
| 131 | + } catch (Exception ex) { |
| 132 | + return VerificationResult.failure("Exception: " + ex.getMessage()); |
| 133 | + } |
| 134 | + }); |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Extracts the digest value from the signature header according to the template |
| 139 | + * and decodes the signature from the header value. |
| 140 | + * |
| 141 | + * @param headerValue The value of the signature header. |
| 142 | + * @return The decoded signature as a byte array, or null if extraction fails. |
| 143 | + */ |
| 144 | + private byte[] extractSignature(final String headerValue) { |
| 145 | + try { |
| 146 | + int index = signatureValueTemplate.indexOf(SIGNATURE_VALUE_PLACEHOLDER); |
| 147 | + if (index < 0) { |
| 148 | + return new byte[0]; |
| 149 | + } |
| 150 | + |
| 151 | + String prefix = signatureValueTemplate.substring(0, index); |
| 152 | + String suffix = signatureValueTemplate.substring( |
| 153 | + index + SIGNATURE_VALUE_PLACEHOLDER.length()); |
| 154 | + |
| 155 | + // find prefix anywhere (case-insensitive) |
| 156 | + int prefixAt = indexOfIgnoreCase(headerValue, prefix, 0); |
| 157 | + if (prefixAt < 0) { |
| 158 | + return new byte[0]; |
| 159 | + } |
| 160 | + |
| 161 | + int digestStart = prefixAt + prefix.length(); |
| 162 | + |
| 163 | + // find suffix after the digest start (case-insensitive) |
| 164 | + final int digestEnd; |
| 165 | + if (suffix.isEmpty()) { |
| 166 | + digestEnd = headerValue.length(); |
| 167 | + } else { |
| 168 | + digestEnd = indexOfIgnoreCase(headerValue, suffix, digestStart); |
| 169 | + if (digestEnd < 0) { |
| 170 | + return new byte[0]; |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + if (digestEnd < digestStart) { |
| 175 | + return new byte[0]; |
| 176 | + } |
| 177 | + |
| 178 | + String digest = headerValue.substring(digestStart, digestEnd).trim(); |
| 179 | + // strip optional quotes |
| 180 | + if (digest.length() >= 2 && digest.charAt(0) == '"' |
| 181 | + && digest.charAt(digest.length() - 1) == '"') { |
| 182 | + digest = digest.substring(1, digest.length() - 1); |
| 183 | + } |
| 184 | + |
| 185 | + byte[] decoded = digestCodec.decode(digest); |
| 186 | + return (decoded == null || decoded.length == 0) ? null : decoded; |
| 187 | + } catch (Exception e) { |
| 188 | + return new byte[0]; |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + /** |
| 193 | + * Finds the index of the first case-insensitive {@code needle} in {@code haystack} |
| 194 | + * starting from {@code fromIndex}, or -1 if not found. |
| 195 | + * |
| 196 | + * @param haystack The string to search in. |
| 197 | + * @param needle The substring to search for. |
| 198 | + * @param fromIndex The index to start searching from. |
| 199 | + * @return The index of the first occurrence, or -1 if not found. |
| 200 | + */ |
| 201 | + private static int indexOfIgnoreCase( |
| 202 | + final String haystack, |
| 203 | + final String needle, |
| 204 | + final int fromIndex |
| 205 | + ) { |
| 206 | + if (needle.isEmpty()) { |
| 207 | + return fromIndex; |
| 208 | + } |
| 209 | + int max = haystack.length() - needle.length(); |
| 210 | + for (int i = Math.max(0, fromIndex); i <= max; i++) { |
| 211 | + if (haystack.regionMatches(true, i, needle, 0, needle.length())) { |
| 212 | + return i; |
| 213 | + } |
| 214 | + } |
| 215 | + return -1; |
| 216 | + } |
| 217 | +} |
0 commit comments