Basics

Basics #

To apply a policy we recommend using one of the AWS SDKs (in your favorite language) or the awscli:

❯ python -m pip install awscli

Both include validation and error handling which make working with these API a much better experience than building signatures yourself and piping calls to curl.

AWSCLI #

Create/save your policy to policy.json and then apply it using the following command:

❯ aws s3api put-bucket-policy \
 --bucket bucket-name.example.org \
 --policy file://policy.json

SDK Example #

For this demonstration, we utilized Golang, but the method calls will be quite similar with the SDK in your preferred programming language. To maintain brevity in the examples, we won’t reproduce this fully functional program on each individual page.

package main

import (
  "json"

  "github.com/aws/aws-sdk-go/aws"
  "github.com/aws/aws-sdk-go/aws/credentials"
  "github.com/aws/aws-sdk-go/aws/session"
  "github.com/aws/aws-sdk-go/service/s3"
)

func main() {
  // initialize the credential session
  sess := session.Must(session.NewSession(&aws.Config{
    Region:                    aws.String("unused"),
    Credentials:               credentials.NewStaticCredentials(
      "your-key-id",
      "your-secret",
      ""),
    S3ForcePathStyle:          aws.Bool(true),
    DisableEndpointHostPrefix: aws.Bool(true),
  }))

  // create service client
  svc := s3.New(sess, aws.NewConfig().
    WithEndpoint("https://s3.storage.planetary-networks.de"))

  bucket := "bucket-name.example.org"

  rawPolicy := map[string]interface{}{
    "Version": "2012-10-17",
    "Statement": []map[string]interface{}{
      {
        "Effect": "Allow",
        "Action": []string{
          "s3:ListBucket",
          "s3:GetObject",
        },
        "Resource": []string{
          "arn:aws:s3:::" + bucket,
          "arn:aws:s3:::" + bucket + "/*",
        },
        "Principal": "*",
      },
    },
  }

  // encode to json
  policy, _ := json.Marshal(rawPolicy)

  // set policy
  svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
    Bucket: &bucket,
    Policy: aws.String(string(policy)),
  })