Skip to content

Instantly share code, notes, and snippets.

@ethan-gallant
Created February 22, 2022 17:48
Show Gist options
  • Save ethan-gallant/21014d6b685da11b7e4a3a31c66c5441 to your computer and use it in GitHub Desktop.
Save ethan-gallant/21014d6b685da11b7e4a3a31c66c5441 to your computer and use it in GitHub Desktop.
A Java snippet for generating Temporary Signed URLs with OpenStack SWIFT S3 Storage
commons-codec:commons-codec:1.15
package org.acme;
import io.vertx.core.http.HttpMethod;
import org.apache.commons.codec.digest.HmacUtils;
import java.time.Instant;
import static org.apache.commons.codec.digest.HmacAlgorithms.HMAC_SHA_1;
public class Main {
static final String HOST = "https://s3.gra.cloud.ovh.net";
static final String BASE_PATH = "BASE_PATH_GO_HERE";
static final String PRESIGN_SECRET = "SECRET_GO_HERE";
public static void main(String[] args) {
String url = presignUrl("testing-tenant", "Concept2.png", HttpMethod.GET, Instant.now().plusSeconds(60));
}
public static String presignUrl(String tenant, String path, HttpMethod method, Instant expiresAt) {
// This helps avoid "tenant-escape" attacks
if (tenant == null || tenant.isEmpty() || !tenant.matches("^[a-z0-9-]+$")) {
throw new RuntimeException("Tenant must be specified!");
}
if (path.contains("..")) {
throw new RuntimeException("Invalid path!");
}
// Generate OpenStack Swift Temp URL
path = String.format("%s/%s/%s", BASE_PATH, tenant, path);
// Expiration is in epoch seconds
String expires = String.valueOf(expiresAt.getEpochSecond());
// We sign the method, expiration and path seperated by \n
String hmacBody = "%s\n%s\n%s"; // (method, expires, path)
// Create the HMAC signature with the PRESIGN_SECRET
HmacUtils hmacUtils = new HmacUtils(HMAC_SHA_1, PRESIGN_SECRET);
String signature = "";
try {
// Generate the signature based on method, expiration and path
signature = hmacUtils.hmacHex(String.format(hmacBody, method, expires, path));
} catch (Exception e) {
e.printStackTrace();
}
// Asemble the URL and add the required query params
String url = String.format("%s%s?temp_url_sig=%s&temp_url_expires=%s", HOST, path, signature, expires);
return url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment