aws-sdk-net: AmazonS3Client is missing `Create Presigned Post`

AmazonS3Client / IAmazonS3 is missing Create Presigned Post functionality found in JS/Python libraries. GetPreSignedURL does not appear to support POST. Therefore there seems to be no way to constrain max upload size when providing signed links using aws-sdk-net.

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 35
  • Comments: 26 (3 by maintainers)

Most upvoted comments

Hi, I have started working on implementing this

ashishdhingra It’s been a while, any update on this?

@ashishdhingra Hi, any updates about PresignedPost for .net?

Got the above snippet to work with localstack by adjusting the base URL:

Uri url = this.Config.ServiceURL != null
    ? new Uri($"{this.Config.ServiceURL.TrimEnd('/')}/{request.BucketName}")
    : new Uri($"https://{request.BucketName}.s3.{regionName}.amazonaws.com");

And for the upload to actually work, I used the following field name casings:

Dictionary<string, string> fields = new()
{
    { "key", request.Key },
    { "bucket", request.BucketName },
    { "Policy", policyEncoded },
    { "X-Amz-Signature", Convert.ToHexString(signature).ToLowerInvariant() },
    { "X-Amz-Algorithm", signingAlgorithm },
    { "X-Amz-Credential", parsedCredentials },
    { "X-Amz-Date", signingDate },
};

I ran up against this and was able to combine solutions and do a lot of tinkering on my own to hammer out an extended client that works with security tokens and ${filename} keys. Thank you so much for your contributions @greffgreff, @glen-84, and @zhuker. This should work fully as a copy-paste solution:

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Auth;
using Amazon.S3;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace Your.Namespace.Here;

/// <summary>
/// An extended Amazon S3 client, with added support for creating presigned posts.
/// </summary>
/// <seealso href="https://github.com/aws/aws-sdk-net/issues/1901">
/// AmazonS3Client is missing Create Presigned Post
/// </seealso>
public sealed class AmazonS3ExtendedClient : AmazonS3Client, IAmazonS3Extended {
    public AmazonS3ExtendedClient(AWSCredentials credentials, AmazonS3Config config)
        : base(credentials, config) {
    }

    public PresignedPost GeneratePreSignedPost(CreatePresignedPostUrlRequest request) {
        // This null check will occur if you're using local S3. This won't work with local S3 - and cannot as far as I can tell - but at least it won't break.
        var regionName = this.Config.RegionEndpoint?.SystemName ?? "us-east-1";
        var credentials = this.Credentials.GetCredentials();
        var signingDate = this.Config.CorrectedUtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
        const string signingAlgorithm = "AWS4-HMAC-SHA256";
        var shortDate = signingDate[..8];
        var credentialScope = $"{shortDate}/{regionName}/s3/aws4_request";
        var parsedCredentials = $"{credentials.AccessKey}/{credentialScope}";
        var url = new Uri($"https://{request.BucketName}.s3.{regionName}.amazonaws.com");

        request.Conditions.Add(new ExactMatchCondition("bucket", request.BucketName));
        request.Conditions.Add(new ExactMatchCondition("X-Amz-Algorithm", "AWS4-HMAC-SHA256"));
        request.Conditions.Add(new ExactMatchCondition("X-Amz-Credential", $"{credentials.AccessKey}/{credentialScope}"));
        request.Conditions.Add(new ExactMatchCondition("X-Amz-Date", signingDate));
        if (!string.IsNullOrWhiteSpace(credentials.Token)) {
            request.Conditions.Add(new ExactMatchCondition("X-Amz-Security-Token", credentials.Token));
        }

        if (request.Key.EndsWith("${filename}")) {
            var keyWithoutFilename = request.Key[..^"${filename}".Length];
            request.Conditions.Add(new StartsWithMatchCondition("$key", keyWithoutFilename));
        } else {
            request.Conditions.Add(new ExactMatchCondition("$key", request.Key));
        }

        var policy = new PostPolicy {
            Expiration = this.Config.CorrectedUtcNow.Add(request.Expires ?? TimeSpan.FromSeconds(3600)),
            Conditions = request.Conditions,
        };

        var policyJson = JsonSerializer.Serialize(policy);
        var policyEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(policyJson));

        var signingKey = AWS4Signer.ComposeSigningKey(credentials.SecretKey, regionName, shortDate, "s3");
        var signature = AWS4Signer.ComputeKeyedHash(SigningAlgorithm.HmacSHA256, signingKey, policyEncoded);

        var fields = new Dictionary<string, string> {
            { "Key", request.Key },
            { "Bucket", request.BucketName },
            { "Policy", policyEncoded },
            { "X-Amz-Signature", Convert.ToHexString(signature).ToLowerInvariant() },
            { "X-Amz-Algorithm", signingAlgorithm },
            { "X-Amz-Credential", parsedCredentials },
            { "X-Amz-Date", signingDate },
        };

        if (!string.IsNullOrWhiteSpace(credentials.Token)) {
            fields.Add("X-Amz-Security-Token", credentials.Token);
        }

        return new PresignedPost { Url = url.ToString(), Fields = fields, };
    }
}

public sealed record CreatePresignedPostUrlRequest {
    public required string BucketName { get; set; }
    public required string Key { get; set; }
    public IList<object> Conditions { get; set; } = new List<object>();
    public TimeSpan? Expires { get; set; }
}

public sealed record PostPolicy {
    [JsonPropertyName("expiration")] public DateTime Expiration { get; set; }

    [JsonPropertyName("conditions")] public IList<object> Conditions { get; set; } = new List<object>();
}

public sealed record PresignedPost {
    public required string Url { get; set; }
    public IDictionary<string, string>? Fields { get; set; }
}

public interface IAmazonS3Extended : IAmazonS3 {
    public PresignedPost GeneratePreSignedPost(CreatePresignedPostUrlRequest request);
}

[JsonDerivedType(typeof(ExactMatchCondition))]
[JsonDerivedType(typeof(StartsWithMatchCondition))]
[JsonDerivedType(typeof(RangeMatchCondition))]
public abstract record Condition {
}

[JsonConverter(typeof(ExactMatchConditionConverter))]
public sealed record ExactMatchCondition(string Key, string Value) : Condition;

[JsonConverter(typeof(StartsWithMatchConditionConverter))]
public sealed record StartsWithMatchCondition(string Key, string Value) : Condition;

[JsonConverter(typeof(RangeMatchConditionConverter))]
public sealed record RangeMatchCondition(string Key, int ValueStart, int ValueEnd) : Condition;

public sealed class ExactMatchConditionConverter : System.Text.Json.Serialization.JsonConverter<ExactMatchCondition> {
    public override ExactMatchCondition? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) {
        throw new NotImplementedException();
    }

    public override void Write(
        Utf8JsonWriter writer,
        ExactMatchCondition value,
        JsonSerializerOptions options) {
        writer.WriteStartObject();
        writer.WriteString(value.Key, value.Value);
        writer.WriteEndObject();
    }
}

public sealed class
    StartsWithMatchConditionConverter : System.Text.Json.Serialization.JsonConverter<StartsWithMatchCondition> {
    public override StartsWithMatchCondition? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) {
        throw new NotImplementedException();
    }

    public override void Write(
        Utf8JsonWriter writer,
        StartsWithMatchCondition value,
        JsonSerializerOptions options) {
        writer.WriteStartArray();
        writer.WriteStringValue("starts-with");
        writer.WriteStringValue(value.Key);
        writer.WriteStringValue(value.Value);
        writer.WriteEndArray();
    }
}

public sealed class RangeMatchConditionConverter : System.Text.Json.Serialization.JsonConverter<RangeMatchCondition> {
    public override RangeMatchCondition? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) {
        throw new NotImplementedException();
    }

    public override void Write(
        Utf8JsonWriter writer,
        RangeMatchCondition value,
        JsonSerializerOptions options) {
        writer.WriteStartArray();
        writer.WriteStringValue(value.Key);
        writer.WriteNumberValue(value.ValueStart);
        writer.WriteNumberValue(value.ValueEnd);
        writer.WriteEndArray();
    }
}

Usage should work identical to @glen-84’s example. I consider this code temporary, this issue was raised to p1 and I hope that means AWS will add official support soon and all of this can be replaced with just using the real thing.

I implemented this in an extended AmazonS3 client.

Install AWSSDK.S3 and AWSSDK.Extensions.NETCore.Setup.

using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Auth;
using Amazon.S3;

namespace Api.Framework.AmazonS3;

/// <summary>
/// An extended Amazon S3 client, with added support for creating presigned posts.
/// </summary>
/// <seealso href="https://github.com/aws/aws-sdk-net/issues/1901">
/// AmazonS3Client is missing Create Presigned Post
/// </seealso>
public sealed class AmazonS3ExtendedClient : AmazonS3Client, IAmazonS3Extended
{
    public AmazonS3ExtendedClient(AWSCredentials credentials, AmazonS3ExtendedConfig config)
        : base(credentials, config) { }

    public CreatePresignedPostResponse CreatePresignedPost(CreatePresignedPostRequest request)
    {
        var regionName = this.Config.RegionEndpoint.SystemName;

        var url = new Uri($"https://s3.{regionName}.amazonaws.com/{request.Bucket}");

        var signingDate = this.Config.CorrectedUtcNow
            .ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);

        var shortDate = signingDate[..8];

        var credentials = this.Credentials.GetCredentials();

        var credentialScope = $"{shortDate}/{regionName}/s3/aws4_request";

        var fields = request.Fields ?? new Dictionary<string, string>();

        fields.Add("key", request.Key);
        fields.Add("bucket", request.Bucket);
        fields.Add("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
        fields.Add("X-Amz-Credential", $"{credentials.AccessKey}/{credentialScope}");
        fields.Add("X-Amz-Date", signingDate);
        fields.Add("X-Amz-Security-Token", credentials.Token);

        var conditions = request.Conditions ?? new List<Condition>();

        foreach (var (key, value) in fields)
        {
            conditions.Add(new ExactMatchCondition(key, value));
        }

        var postPolicy = new PostPolicy(
            this.Config.CorrectedUtcNow.Add(request.Expires ?? TimeSpan.FromSeconds(3600)),
            conditions);

        var postPolicyJson = JsonSerializer.Serialize(
            postPolicy,
            AmazonS3SerializerContext.Default.PostPolicy);

        var postPolicyEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(postPolicyJson));

        fields.Add("Policy", postPolicyEncoded);

        var signingKey = AWS4Signer.ComposeSigningKey(
            credentials.SecretKey,
            regionName,
            shortDate,
            "s3");

        var signature =
            AWS4Signer.ComputeKeyedHash(SigningAlgorithm.HmacSHA256, signingKey, postPolicyEncoded);

        fields.Add("X-Amz-Signature", Convert.ToHexString(signature).ToLowerInvariant());

        return new CreatePresignedPostResponse(url, fields);
    }
}

public interface IAmazonS3Extended : IAmazonS3
{
    public CreatePresignedPostResponse CreatePresignedPost(CreatePresignedPostRequest request);
}

public sealed class AmazonS3ExtendedConfig : AmazonS3Config { }

public sealed record CreatePresignedPostRequest(
    string Bucket,
    string Key,
    IList<Condition>? Conditions = null,
    IDictionary<string, string>? Fields = null,
    TimeSpan? Expires = null);

public sealed record CreatePresignedPostResponse(Uri Url, IDictionary<string, string> Fields);

public sealed record PostPolicy(DateTime Expiration, IList<Condition> Conditions);

[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(PostPolicy))]
public sealed partial class AmazonS3SerializerContext : JsonSerializerContext { }

[JsonDerivedType(typeof(ExactMatchCondition))]
[JsonDerivedType(typeof(StartsWithMatchCondition))]
[JsonDerivedType(typeof(RangeMatchCondition))]
public abstract record Condition { }

[JsonConverter(typeof(ExactMatchConditionConverter))]
public sealed record ExactMatchCondition(string Key, string Value) : Condition;

[JsonConverter(typeof(StartsWithMatchConditionConverter))]
public sealed record StartsWithMatchCondition(string Key, string Value) : Condition;

[JsonConverter(typeof(RangeMatchConditionConverter))]
public sealed record RangeMatchCondition(string Key, int ValueStart, int ValueEnd) : Condition;

public sealed class ExactMatchConditionConverter : JsonConverter<ExactMatchCondition>
{
    public override ExactMatchCondition? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(
        Utf8JsonWriter writer,
        ExactMatchCondition value,
        JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        writer.WriteString(value.Key, value.Value);
        writer.WriteEndObject();
    }
}

public sealed class StartsWithMatchConditionConverter : JsonConverter<StartsWithMatchCondition>
{
    public override StartsWithMatchCondition? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(
        Utf8JsonWriter writer,
        StartsWithMatchCondition value,
        JsonSerializerOptions options)
    {
        writer.WriteStartArray();
        writer.WriteStringValue("starts-with");
        writer.WriteStringValue(value.Key);
        writer.WriteStringValue(value.Value);
        writer.WriteEndArray();
    }
}

public sealed class RangeMatchConditionConverter : JsonConverter<RangeMatchCondition>
{
    public override RangeMatchCondition? Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(
        Utf8JsonWriter writer,
        RangeMatchCondition value,
        JsonSerializerOptions options)
    {
        writer.WriteStartArray();
        writer.WriteStringValue(value.Key);
        writer.WriteNumberValue(value.ValueStart);
        writer.WriteNumberValue(value.ValueEnd);
        writer.WriteEndArray();
    }
}

In Program.cs:

builder.Services
    .AddAWSService<IAmazonS3Extended>(builder.Configuration.GetAWSOptions());

Usage:

// Inject an `IAmazonS3Extended` (s3Client).

this.s3Client.CreatePresignedPost(new(
    "YourBucketName",
    key,
    new List<Condition>()
    {
        // Limit file size.
        new RangeMatchCondition(
            "content-length-range",
            1,
            100_000)
    },
    Expires: TimeSpan.FromMinutes(10)));

Disclaimer: No support or liability.

does it still missing content-length-range?

This shouldn’t be necessary. This is actually my own namespace.

Haha yeah, you’re right, this was from my early attempts at making this all work. Updating it to its actual namespace seemed to be breaking something else, but I think it was a coincidence. Good call out, I’ve cleaned that bit up.

Yes, see also: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html?highlight=presigned#S3.Client.generate_presigned_post

I’m using PUT but (please correct me if I’m wrong) this does not provide for constraints like max file size or preventing update by link reuse.

This is a must.

Any updates? 🤦🏻

Fork repo and get writing? 😁

We ended up implementing our own S3 presigned POST in F#. Inspired by the AWS SDK for JS

+1 for pre-signed post we also need it here

We’re also in need of pre-signed POST support, as GetPreSignedURL doesn’t meet our requirements (limiting the size of the uploaded files, and allowing only certain content-types).