Search in sources :

Example 1 with PostFieldsV4

use of com.google.cloud.storage.PostPolicyV4.PostFieldsV4 in project java-storage by googleapis.

the class StorageImpl method generateSignedPostPolicyV4.

@Override
public PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, PostFieldsV4 fields, PostConditionsV4 conditions, PostPolicyV4Option... options) {
    EnumMap<SignUrlOption.Option, Object> optionMap = Maps.newEnumMap(SignUrlOption.Option.class);
    // Convert to a map of SignUrlOptions so we can re-use some utility methods
    for (PostPolicyV4Option option : options) {
        optionMap.put(SignUrlOption.Option.valueOf(option.getOption().name()), option.getValue());
    }
    optionMap.put(SignUrlOption.Option.SIGNATURE_VERSION, SignUrlOption.SignatureVersion.V4);
    ServiceAccountSigner credentials = (ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED);
    if (credentials == null) {
        checkState(this.getOptions().getCredentials() instanceof ServiceAccountSigner, "Signing key was not provided and could not be derived");
        credentials = (ServiceAccountSigner) this.getOptions().getCredentials();
    }
    checkArgument(!(optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE) && optionMap.containsKey(SignUrlOption.Option.PATH_STYLE) && optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)), "Only one of VIRTUAL_HOSTED_STYLE, PATH_STYLE, or BUCKET_BOUND_HOST_NAME SignUrlOptions can be" + " specified.");
    String bucketName = slashlessBucketNameFromBlobInfo(blobInfo);
    boolean usePathStyle = shouldUsePathStyleForSignedUrl(optionMap);
    String url;
    if (usePathStyle) {
        url = STORAGE_XML_URI_SCHEME + "://" + STORAGE_XML_URI_HOST_NAME + "/" + bucketName + "/";
    } else {
        url = STORAGE_XML_URI_SCHEME + "://" + bucketName + "." + STORAGE_XML_URI_HOST_NAME + "/";
    }
    if (optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)) {
        url = optionMap.get(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME) + "/";
    }
    SimpleDateFormat googDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat expirationFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    googDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    yearMonthDayFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    expirationFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    long timestamp = getOptions().getClock().millisTime();
    String date = googDateFormat.format(timestamp);
    String signingCredential = credentials.getAccount() + "/" + yearMonthDayFormat.format(timestamp) + "/auto/storage/goog4_request";
    Map<String, String> policyFields = new HashMap<>();
    PostConditionsV4.Builder conditionsBuilder = conditions.toBuilder();
    for (Map.Entry<String, String> entry : fields.getFieldsMap().entrySet()) {
        // Every field needs a corresponding policy condition, so add them if they're missing
        conditionsBuilder.addCustomCondition(ConditionV4Type.MATCHES, entry.getKey(), entry.getValue());
        policyFields.put(entry.getKey(), entry.getValue());
    }
    PostConditionsV4 v4Conditions = conditionsBuilder.addBucketCondition(ConditionV4Type.MATCHES, blobInfo.getBucket()).addKeyCondition(ConditionV4Type.MATCHES, blobInfo.getName()).addCustomCondition(ConditionV4Type.MATCHES, "x-goog-date", date).addCustomCondition(ConditionV4Type.MATCHES, "x-goog-credential", signingCredential).addCustomCondition(ConditionV4Type.MATCHES, "x-goog-algorithm", "GOOG4-RSA-SHA256").build();
    PostPolicyV4Document document = PostPolicyV4Document.of(expirationFormat.format(timestamp + unit.toMillis(duration)), v4Conditions);
    String policy = BaseEncoding.base64().encode(document.toJson().getBytes());
    String signature = BaseEncoding.base16().encode(credentials.sign(policy.getBytes())).toLowerCase();
    for (PostPolicyV4.ConditionV4 condition : v4Conditions.getConditions()) {
        if (condition.type == ConditionV4Type.MATCHES) {
            policyFields.put(condition.operand1, condition.operand2);
        }
    }
    policyFields.put("key", blobInfo.getName());
    policyFields.put("x-goog-credential", signingCredential);
    policyFields.put("x-goog-algorithm", "GOOG4-RSA-SHA256");
    policyFields.put("x-goog-date", date);
    policyFields.put("x-goog-signature", signature);
    policyFields.put("policy", policy);
    policyFields.remove("bucket");
    return PostPolicyV4.of(url, policyFields);
}
Also used : PostConditionsV4(com.google.cloud.storage.PostPolicyV4.PostConditionsV4) HashMap(java.util.HashMap) StorageObject(com.google.api.services.storage.model.StorageObject) ServiceAccountSigner(com.google.auth.ServiceAccountSigner) PostPolicyV4Document(com.google.cloud.storage.PostPolicyV4.PostPolicyV4Document) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) EnumMap(java.util.EnumMap) HashMap(java.util.HashMap)

Example 2 with PostFieldsV4

use of com.google.cloud.storage.PostPolicyV4.PostFieldsV4 in project google-cloud-java by GoogleCloudPlatform.

the class GenerateSignedPostPolicyV4 method generateSignedPostPolicyV4.

/**
 * Generating a signed POST policy requires Credentials which implement ServiceAccountSigner.
 * These can be set explicitly using the Storage.PostPolicyV4Option.signWith(ServiceAccountSigner)
 * option. If you don't, you could also pass a service account signer to StorageOptions, i.e.
 * StorageOptions().newBuilder().setCredentials(ServiceAccountSignerCredentials). In this example,
 * neither of these options are used, which means the following code only works when the
 * credentials are defined via the environment variable GOOGLE_APPLICATION_CREDENTIALS, and those
 * credentials are authorized to sign a policy. See the documentation for
 * Storage.generateSignedPostPolicyV4 for more details.
 */
public static void generateSignedPostPolicyV4(String projectId, String bucketName, String blobName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";
    // The ID of the GCS bucket to upload to
    // String bucketName = "your-bucket-name"
    // The name to give the object uploaded to GCS
    // String blobName = "your-object-name"
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    PostPolicyV4.PostFieldsV4 fields = PostPolicyV4.PostFieldsV4.newBuilder().AddCustomMetadataField("test", "data").build();
    PostPolicyV4 policy = storage.generateSignedPostPolicyV4(BlobInfo.newBuilder(bucketName, blobName).build(), 10, TimeUnit.MINUTES, fields);
    StringBuilder htmlForm = new StringBuilder("<form action='" + policy.getUrl() + "' method='POST' enctype='multipart/form-data'>\n");
    for (Map.Entry<String, String> entry : policy.getFields().entrySet()) {
        htmlForm.append("  <input name='" + entry.getKey() + "' value='" + entry.getValue() + "' type='hidden' />\n");
    }
    htmlForm.append("  <input type='file' name='file'/><br />\n");
    htmlForm.append("  <input type='submit' value='Upload File'/><br />\n");
    htmlForm.append("</form>\n");
    System.out.println("You can use the following HTML form to upload an object to bucket " + bucketName + " for the next ten minutes:");
    System.out.println(htmlForm.toString());
}
Also used : PostPolicyV4(com.google.cloud.storage.PostPolicyV4) Storage(com.google.cloud.storage.Storage) Map(java.util.Map)

Example 3 with PostFieldsV4

use of com.google.cloud.storage.PostPolicyV4.PostFieldsV4 in project java-storage by googleapis.

the class ITStorageTest method testSignedPostPolicyV4.

@Test
public void testSignedPostPolicyV4() throws Exception {
    PostFieldsV4 fields = PostFieldsV4.newBuilder().setAcl("public-read").build();
    PostPolicyV4 policy = storage.generateSignedPostPolicyV4(BlobInfo.newBuilder(BUCKET, "my-object").build(), 7, TimeUnit.DAYS, fields);
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost(policy.getUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (Map.Entry<String, String> entry : policy.getFields().entrySet()) {
        builder.addTextBody(entry.getKey(), entry.getValue());
    }
    File file = File.createTempFile("temp", "file");
    Files.write(file.toPath(), "hello world".getBytes());
    builder.addBinaryBody("file", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName());
    request.setEntity(builder.build());
    client.execute(request);
    assertEquals("hello world", new String(storage.get(BUCKET, "my-object").getContent()));
}
Also used : PostPolicyV4(com.google.cloud.storage.PostPolicyV4) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpClient(org.apache.http.client.HttpClient) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) File(java.io.File) FileInputStream(java.io.FileInputStream) PostFieldsV4(com.google.cloud.storage.PostPolicyV4.PostFieldsV4) Test(org.junit.Test)

Aggregations

Map (java.util.Map)3 PostPolicyV4 (com.google.cloud.storage.PostPolicyV4)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 HashMap (java.util.HashMap)2 StorageObject (com.google.api.services.storage.model.StorageObject)1 ServiceAccountSigner (com.google.auth.ServiceAccountSigner)1 PostConditionsV4 (com.google.cloud.storage.PostPolicyV4.PostConditionsV4)1 PostFieldsV4 (com.google.cloud.storage.PostPolicyV4.PostFieldsV4)1 PostPolicyV4Document (com.google.cloud.storage.PostPolicyV4.PostPolicyV4Document)1 Storage (com.google.cloud.storage.Storage)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 SimpleDateFormat (java.text.SimpleDateFormat)1 EnumMap (java.util.EnumMap)1 HttpClient (org.apache.http.client.HttpClient)1 HttpPost (org.apache.http.client.methods.HttpPost)1 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)1 Test (org.junit.Test)1