Skip to content

Commit

Permalink
feat(cors): Introduce S3 CORS and CF response headers
Browse files Browse the repository at this point in the history
  • Loading branch information
joli-sys committed Oct 11, 2024
1 parent a348e2d commit dc05b4f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
33 changes: 30 additions & 3 deletions main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@ module "s3_bucket" {
}
}

cors_rule = var.s3_cors_rule

tags = local.tags
}

Expand Down Expand Up @@ -248,9 +250,10 @@ resource "aws_cloudfront_distribution" "this" {
}

default_cache_behavior {
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
target_origin_id = var.s3_bucket_name
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
target_origin_id = var.s3_bucket_name
response_headers_policy_id = length(var.s3_cors_rule) > 0 ? aws_cloudfront_response_headers_policy.this[0].id : null

forwarded_values {
query_string = false
Expand Down Expand Up @@ -346,6 +349,30 @@ resource "aws_route53_record" "this" {
}
}

resource "aws_cloudfront_response_headers_policy" "this" {
count = length(var.s3_cors_rule) > 0 ? 1 : 0
name = "${var.s3_bucket_name} - response headers"
comment = "CloudFront response headers policy using S3 CORS rules"

cors_config {
access_control_allow_credentials = var.response_header_access_control_allow_credentials

access_control_allow_headers {
items = var.s3_cors_rule[0].allowed_headers
}

access_control_allow_methods {
items = var.s3_cors_rule[0].allowed_methods
}

access_control_allow_origins {
items = var.s3_cors_rule[0].allowed_origins
}

origin_override = var.response_header_origin_override
}
}

moved {
from = aws_kms_key.this
to = aws_kms_key.this[0]
Expand Down
22 changes: 22 additions & 0 deletions variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,25 @@ variable "aws_env_vars_suffix" {
type = string
default = ""
}

variable "s3_cors_rule" {
description = "List of maps containing rules for Cross-Origin Resource Sharing."
type = list(object({
allowed_headers = optional(list(string))
allowed_methods = optional(list(string))
allowed_origins = optional(list(string))
expose_headers = optional(list(string))
max_age_seconds = optional(number)
}))
default = []
}

variable "response_header_origin_override" {
type = bool
default = false
}

variable "response_header_access_control_allow_credentials" {
type = bool
default = false
}

0 comments on commit dc05b4f

Please sign in to comment.