s3Presign

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2023 License: MIT Imports: 13 Imported by: 1

README

aws-presignpost-s3

AWS Presign Post Policy for S3

There is many presign post policy for AWS S3 golang out there, but the one that i need is not yet available, so i created one myself. Usually they only have bare minimum policy that can be generated. but with this package, i can add all options in AWS S3 Post Policy.

How To Use

you can check file s3policy_test.go to see how to use it. but anyway.

  1. Install the package to your project

go get github.com/fari-99/aws-presignpost-s3-go

  1. Import the package to your project
import "github.com/fari-99/aws-presignpost-s3-go"
  1. Generate policy with data you want.

Note: All data that send to when creating policy is generated or given by You. We didn't check if the data is valid or not. ex: Rest API policy such as Encoding and Disposition

package main
import (
	"github.com/fari-99/aws-presignpost-s3-go"
	"log"
	"time"
)

func main() {
	// this value is not real, if you want to test with the real one
	// please change all this data to your aws s3 data
	awsConfig := s3Presign.AwsConfig{
		AwsAccessKey: "AKIAIOSFODNN7EXAMPLE",
		AwsRegion:    "us-east-1",
		AwsSecretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
		AwsBucket:    "sigv4examplebucket",
	}

	timeExpired, _ := time.Parse(s3Presign.ExpirationFormat, "2015-12-30T12:00:00.000Z")

	s3PolicyBase := s3Presign.NewS3Policy(awsConfig)
	s3PolicyBase.SetAclPolicy(s3Presign.ConditionMatchingExactMatch, "public-read")
	s3PolicyBase.SetContentLengthPolicy(0, 10485760)
	s3PolicyBase.SetKeyPolicy(s3Presign.ConditionMatchingExactMatch, "user/user1/test.jpeg")
	s3PolicyBase.SetSuccessActionRedirectPolicy(s3Presign.ConditionMatchingExactMatch, "https://www.google.com")
	s3PolicyBase.SetSuccessActionStatusPolicy(s3Presign.ConditionMatchingStartWith, "204")
	s3PolicyBase.SetXAmzSecurityTokenPolicy(s3Presign.ConditionMatchingExactMatch, "eW91dHViZQ==", "b0hnNVNKWVJIQTA=")

	// rest api
	s3PolicyBase.SetCacheControlPolicy(s3Presign.ConditionMatchingStartWith, "no-cache")
	s3PolicyBase.SetContentTypePolicy(s3Presign.ConditionMatchingExactMatch, "image/jpeg")
	s3PolicyBase.SetContentDispositionPolicy(s3Presign.ConditionMatchingExactMatch, "Attachment; filename=test.jpeg")
	s3PolicyBase.SetContentEncodingPolicy(s3Presign.ConditionMatchingExactMatch, "token")
	s3PolicyBase.SetExpiresPolicy(timeExpired)

	// custom key
	s3PolicyBase.SetXAmzMeta("uuid", s3Presign.ConditionMatchingExactMatch, "bc2035bf-72b6-4bad-9e1f-c6c8732ac1a4")
	s3PolicyBase.SetXAmzMeta("tag", s3Presign.ConditionMatchingStartWith, "")
	// add more custom policy data

	// amazon key
	s3PolicyBase.SetXAmz("x-amz-server-side-encryption", s3Presign.ConditionMatchingExactMatch, "AES256")
	// other amazon related policy please refer to 
	// https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
	
	encodedPolicy, signature, formsData := s3PolicyBase.GeneratePolicy()
	log.Printf("Encoded Policy := \n%s", encodedPolicy)
	log.Printf("Signature := \n%s", signature)
	log.Printf("Data for your custom forms := \n%v", formsData)
	
	// if you want to generate html forms
	htmlDocumentString, err := s3Presign.GenerateFormHtml(formsData)
	if err != nil {
		panic(err.Error())
	}
	log.Printf(htmlDocumentString)
}

Documentation

Index

Constants

View Source
const AmzAlgorithm = "AWS4-HMAC-SHA256"
View Source
const AmzDateFormat = "20060102T150405Z"
View Source
const ConditionMatchingExactMatch = "eq"

All condition matching detail can be checked here https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html#sigv4-ConditionMatching

View Source
const ConditionMatchingStartWith = "starts-with"
View Source
const ConditionSpecifyingRange = "content-length-range"
View Source
const ExpirationFormat = "2006-01-02T15:04:05.000Z"
View Source
const ExpiredHeaderFormat = "Mon, 02 Jan 2006 15:04:05 MST"
View Source
const SignatureDateFormat = "20060102"
View Source
const XAmzKey = "x-amz-"
View Source
const XAmzMetaKey = "x-amz-meta-"

Variables

This section is empty.

Functions

func GenerateFormHtml

func GenerateFormHtml(formData Forms) (string, error)

Types

type AwsConfig

type AwsConfig struct {
	AwsAccessKey string // used for creating signature
	AwsRegion    string // used for creating signature
	AwsSecretKey string // used for creating signature
	AwsBucket    string
}

func (AwsConfig) Validate

func (config AwsConfig) Validate() error

type BaseS3Policy

type BaseS3Policy struct {
	AwsConfig   AwsConfig
	AwsService  string    // default "s3" for storages, used for creating signature
	Date        time.Time // used for creating signature
	ExpiredDate time.Time
	Policy      *Policy
}

func NewS3Policy

func NewS3Policy(config AwsConfig) *BaseS3Policy

func (*BaseS3Policy) GeneratePolicy

func (base *BaseS3Policy) GeneratePolicy() (policy, signature string, form Forms)

func (*BaseS3Policy) SetAclPolicy

func (base *BaseS3Policy) SetAclPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetBucketPolicy

func (base *BaseS3Policy) SetBucketPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetCacheControlPolicy

func (base *BaseS3Policy) SetCacheControlPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetContentDispositionPolicy

func (base *BaseS3Policy) SetContentDispositionPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetContentEncodingPolicy

func (base *BaseS3Policy) SetContentEncodingPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetContentLengthPolicy

func (base *BaseS3Policy) SetContentLengthPolicy(min, max uint64) *BaseS3Policy

func (*BaseS3Policy) SetContentTypePolicy

func (base *BaseS3Policy) SetContentTypePolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetExpirationDate

func (base *BaseS3Policy) SetExpirationDate(expirationDate time.Time) *BaseS3Policy

func (*BaseS3Policy) SetExpiresPolicy

func (base *BaseS3Policy) SetExpiresPolicy(value time.Time) *BaseS3Policy

func (*BaseS3Policy) SetKeyPolicy

func (base *BaseS3Policy) SetKeyPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetSuccessActionRedirectPolicy

func (base *BaseS3Policy) SetSuccessActionRedirectPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetSuccessActionStatusPolicy

func (base *BaseS3Policy) SetSuccessActionStatusPolicy(conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetXAmz

func (base *BaseS3Policy) SetXAmz(key, conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetXAmzMeta

func (base *BaseS3Policy) SetXAmzMeta(key, conditionMatch, value string) *BaseS3Policy

func (*BaseS3Policy) SetXAmzSecurityTokenPolicy

func (base *BaseS3Policy) SetXAmzSecurityTokenPolicy(conditionMatch, userToken, productToken string) *BaseS3Policy

type ConditionMatching

type ConditionMatching struct {
	ExactMatch      bool `json:"eq"`
	StartWith       bool `json:"starts-with"`
	SpecifyingRange bool `json:"content-length-range"`
}

type ExactMatch

type ExactMatch map[string]string

ExactMatch The form field value must match the value specified. This example indicates that the ACL must be set to public-read: {"acl": "public-read" }

type FormData

type FormData struct {
	FormName  string
	FormValue string
}

type Forms

type Forms struct {
	Url      string
	FormData []FormData
}

type Policy

type Policy struct {
	// The specified Amazon S3 access control list (ACL).
	Acl PolicyConditions `json:"acl" is_valid_form:"true"`

	// Specifies the acceptable bucket name.
	Bucket PolicyConditions `json:"bucket"`

	// The minimum and maximum allowable size for the uploaded content.
	ContentLengthRange PolicyConditions `json:"content_length_range"`

	// REST-specific headers. For more information,
	// see https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html.
	CacheControl       PolicyConditions `json:"Cache-Control"`
	ContentType        PolicyConditions `json:"Content-Type"`
	ContentDisposition PolicyConditions `json:"Content-Disposition"`
	ContentEncoding    PolicyConditions `json:"Content-Encoding"`
	Expires            PolicyConditions `json:"Expires"`

	// The acceptable key name or a prefix of the uploaded object.
	// This example indicates that the object key must start with user/mary:
	// ["starts-with", "$key", "user/mary/"]
	Key PolicyConditions `json:"key"`

	// The URL to which the client is redirected upon successful upload.
	SuccessActionRedirect PolicyConditions `json:"success_action_redirect"`

	// The status code returned to the client upon successful upload if success_action_redirect is not specified.
	SuccessActionStatus PolicyConditions `json:"success_action_status"`

	// The signing algorithm that must be used during signature calculation.
	// For AWS Signature Version 4, the value is AWS4-HMAC-SHA256.
	XAmzAlgorithm PolicyConditions `json:"x-amz-algorithm"`

	// The credentials that you used to calculate the signature.
	// It provides access key ID and scope information identifying region and service for which the signature is valid.
	// This should be the same scope you used in calculating the signing key for signature calculation.
	// It is a string of the following form:
	// <your-access-key-id>/<date:YYYYMMDD>/<aws-region>/<aws-service>/aws4_request
	// example := AKIAIOSFODNN7EXAMPLE/20130728/us-east-1/s3/aws4_request
	XAmzCredential PolicyConditions `json:"x-amz-credential"`

	// The date value specified in the ISO8601 formatted string.
	// For example, 20130728T000000Z.
	// The date must be same that you used in creating the signing key for signature calculation.
	XAmzDate PolicyConditions `json:"x-amz-date"`

	// Amazon DevPay security token.
	// Each request that uses Amazon DevPay requires two x-amz-security-token form fields:
	// One for the product token and one for the user token.
	// As a result, the values must be separated by commas.
	// For example, if the user token is eW91dHViZQ== and the product token is b0hnNVNKWVJIQTA=,
	// you set the POST policy entry to: { "x-amz-security-token": "eW91dHViZQ==,b0hnNVNKWVJIQTA=" }.
	XAmzSecurityToken PolicyConditions `json:"x-amz-security-token"`

	// x-amz-meta-*
	// Headers starting with this prefix are user-defined metadata.
	// Each one is stored and returned as a set of key-value pairs.
	// -Amazon S3 doesn't validate or interpret user-defined metadata-
	XAmzMeta map[string]PolicyConditions `json:"x_amz_meta"`

	// x-amz-*
	// Headers starting with this prefix are for any x-amz-* headers
	// See https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html, for more details
	XAmz map[string]PolicyConditions `json:"x_amz"`
}

func (Policy) Validate

func (policy Policy) Validate() error

type PolicyConditions

type PolicyConditions struct {
	Conditions    ConditionMatching
	ConditionUsed string

	PolicyValue      string
	PolicyStartRange uint64
	PolicyStopRange  uint64
}

type PolicyConfig

type PolicyConfig struct {
	PolicyData *Policy
}

type PolicyData

type PolicyData interface {
	PolicyConditions | map[string]PolicyConditions | map[string]interface{}
}

type SpecifyingRange

type SpecifyingRange []interface{}

SpecifyingRange For form fields that accept a range, separate the upper and lower limit with a comma. This example allows a file size from 1 to 10 MiB: ["content-length-range", 1048576, 10485760]

type StartWith

type StartWith []string

StartWith The value must start with the specified value. This example indicates that the object key must start with user/user1: ["starts-with", "$key", "user/user1/"]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL