# Static hosting for https://substandard.blog: the Astro-built frontpage # plus the OAuth client metadata at /client-metadata.json. # # scripts/deploy-site.sh uploads each build as an immutable tree under # s3://substandard.blog/releases// and writes the sha to # terraform.tfvars.json; the apply here only flips CloudFront's origin_path # to that tree. Roll back by setting release_sha to a previously uploaded # sha and re-applying. # # After the first apply, set the name servers from the zone_name_servers # output at the registrar for substandard.blog; certificate validation and # the rest of the apply complete once delegation is live. locals { domain = "substandard.blog" } variable "release_sha" { description = "Git sha of the releases/ tree in S3 that CloudFront serves; written to terraform.tfvars.json by scripts/deploy-site.sh" type = string validation { condition = can(regex("^[0-9a-f]{12}(-dirty)?$", var.release_sha)) error_message = "Run scripts/deploy-site.sh, which writes the deployed commit's short sha to terraform.tfvars.json." } } variable "panoptiblog_image_tag" { description = "ECR image tag for the scheduled panoptiblog job; scripts/panoptiblog/deploy.sh writes the commit sha here" type = string default = "latest" validation { condition = can(regex("^([0-9a-f]{12}|latest)$", var.panoptiblog_image_tag)) error_message = "Use a 12-character commit sha, or latest before the first image is pushed." } } resource "aws_route53_zone" "substandard" { name = local.domain } resource "aws_acm_certificate" "substandard" { domain_name = local.domain # The panoptiblog sub-page is its own address; one certificate covers both # names rather than a second distribution and a second certificate. subject_alternative_names = ["panoptiblog.${local.domain}"] validation_method = "DNS" lifecycle { create_before_destroy = true } } resource "aws_route53_record" "cert_validation" { for_each = { for dvo in aws_acm_certificate.substandard.domain_validation_options : dvo.domain_name => { name = dvo.resource_record_name type = dvo.resource_record_type record = dvo.resource_record_value } } zone_id = aws_route53_zone.substandard.zone_id name = each.value.name type = each.value.type records = [each.value.record] ttl = 300 } resource "aws_acm_certificate_validation" "substandard" { certificate_arn = aws_acm_certificate.substandard.arn validation_record_fqdns = [for r in aws_route53_record.cert_validation : r.fqdn] } resource "aws_s3_bucket" "substandard" { bucket = local.domain } resource "aws_s3_bucket_public_access_block" "substandard" { bucket = aws_s3_bucket.substandard.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true } resource "aws_cloudfront_origin_access_control" "substandard" { name = "substandard" origin_access_control_origin_type = "s3" signing_behavior = "always" signing_protocol = "sigv4" } # Astro emits directory output but links without trailing slashes (see # web/astro.config.mjs): viewer-request.js rewrites /posts/x to the # posts/x/index.html object and redirects /posts/x/ to the canonical # /posts/x. resource "aws_cloudfront_function" "trailing_slash" { name = "substandard-trailing-slash" runtime = "cloudfront-js-2.0" publish = true code = file("${path.module}/viewer-request.js") } # Security response headers for the frontpage. # # The CSP is not a guess: it was validated against the real built site by # serving web/dist with this exact header and loading /, /privacy and /posts in # headless Chrome, with a deliberately over-strict policy as a negative control # to prove violations would have been seen. The script hash below is the inline # PostHog snippet, and web/scripts/verify-dist.mjs recomputes it at build time # and fails the build if it drifts from this value — a stale hash would # silently kill analytics rather than break anything visible. # # Deliberately not set: HSTS preload (a commitment that is painful to reverse), # and X-XSS-Protection (deprecated, and its filter has caused bugs of its own). locals { # Keep in step with csp_script_hash in web/scripts/verify-dist.mjs. posthog_script_hash = "sha256-pNJpiMM+bfVBeb4RNMyUydqv40pYVTtA/IGT1xpTGgs=" content_security_policy = join(" ", [ "default-src 'self';", "script-src 'self' '${local.posthog_script_hash}' https://eu-assets.i.posthog.com;", "style-src 'self';", # Publication icons are blobs on their authors' PDS hosts. The card # renderer uses referrerpolicy="no-referrer" and lazy loading; the # extension has always loaded these same hosts. "img-src 'self' data: https:;", "connect-src 'self' https://eu.i.posthog.com https://eu-assets.i.posthog.com;", "font-src 'self';", "object-src 'none';", "base-uri 'none';", "form-action 'none';", "frame-ancestors 'none';", "worker-src 'self' blob:;", "upgrade-insecure-requests", ]) } resource "aws_cloudfront_response_headers_policy" "security" { name = "substandard-security-headers" comment = "HSTS, CSP, nosniff, referrer and frame policy for substandard.blog" security_headers_config { strict_transport_security { # Two years, matching the usual preload-eligible value even though we do # not preload; subdomains included because none are in use, so nothing # can be broken by covering them now. access_control_max_age_sec = 63072000 include_subdomains = true preload = false override = true } content_type_options { override = true } frame_options { frame_option = "DENY" override = true } referrer_policy { referrer_policy = "strict-origin-when-cross-origin" override = true } content_security_policy { content_security_policy = local.content_security_policy override = true } } custom_headers_config { # Not covered by security_headers_config. The site uses none of these, and # saying so keeps a future dependency from quietly turning one on. items { header = "Permissions-Policy" value = "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()" override = true } } } resource "aws_cloudfront_distribution" "substandard" { enabled = true aliases = [local.domain, "panoptiblog.${local.domain}"] price_class = "PriceClass_100" comment = "substandard frontpage, panoptiblog and OAuth client metadata" default_root_object = "index.html" origin { domain_name = aws_s3_bucket.substandard.bucket_regional_domain_name origin_id = "s3" origin_path = "/releases/${var.release_sha}" origin_access_control_id = aws_cloudfront_origin_access_control.substandard.id } # The scheduled job writes outside the immutable release trees: it uploads # panoptiblog/data.json to the bucket root, and a behavior below points this # origin at it. A release tree is a function of a commit; a ranking is not. origin { domain_name = aws_s3_bucket.substandard.bucket_regional_domain_name origin_id = "s3-data" origin_access_control_id = aws_cloudfront_origin_access_control.substandard.id } default_cache_behavior { target_origin_id = "s3" viewer_protocol_policy = "redirect-to-https" allowed_methods = ["GET", "HEAD"] cached_methods = ["GET", "HEAD"] # AWS managed CachingOptimized policy cache_policy_id = "658327ea-f89d-4fab-a63d-7e88639e58f6" response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id function_association { event_type = "viewer-request" function_arn = aws_cloudfront_function.trailing_slash.arn } } # One path comes from the bucket root rather than a release tree: the # dataset the scheduled job replaces. Everything else stays on the release # origin, so a ranking refresh never needs a site release. ordered_cache_behavior { # data.json is the top-100 file the site and extension read; all.json is # the full account corpus the labeler reads. path_pattern = "/panoptiblog/*.json" target_origin_id = "s3-data" viewer_protocol_policy = "redirect-to-https" allowed_methods = ["GET", "HEAD"] cached_methods = ["GET", "HEAD"] cache_policy_id = "658327ea-f89d-4fab-a63d-7e88639e58f6" response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id } # The bucket is private behind the origin access control, so S3 answers a key # that is not in the release tree with 403 AccessDenied, not 404. Unmapped, # every typo'd or stale link — and the Chrome Web Store listing points people # at this site — renders as raw XML that reads like a permissions failure on # a private site rather than a missing page. Map both codes to the built 404 # document and answer 404, so readers and crawlers are told the page is gone. # # response_page_path is the S3 key, not a viewer address: CloudFront fetches # it from the origin itself, and viewer-request.js does not run on that # fetch, so nothing rewrites it to /404.html/index.html. Astro special-cases # the status-code pages and emits 404.astro at the top level even though # every other page builds as a directory; web/scripts/verify-dist.mjs reads # this path back out of here and fails a build that does not ship it. # # A short caching TTL: an error cached at the edge outlives the deploy that # fixes it, and these are cheap to re-ask for. custom_error_response { error_code = 403 response_code = 404 response_page_path = "/404.html" error_caching_min_ttl = 10 } custom_error_response { error_code = 404 response_code = 404 response_page_path = "/404.html" error_caching_min_ttl = 10 } restrictions { geo_restriction { restriction_type = "none" } } viewer_certificate { acm_certificate_arn = aws_acm_certificate_validation.substandard.certificate_arn ssl_support_method = "sni-only" minimum_protocol_version = "TLSv1.2_2021" } } resource "aws_s3_bucket_policy" "cloudfront_read" { bucket = aws_s3_bucket.substandard.id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Principal = { Service = "cloudfront.amazonaws.com" } Action = "s3:GetObject" Resource = "${aws_s3_bucket.substandard.arn}/*" Condition = { StringEquals = { "AWS:SourceArn" = aws_cloudfront_distribution.substandard.arn } } } ] }) } resource "aws_route53_record" "substandard_a" { zone_id = aws_route53_zone.substandard.zone_id name = local.domain type = "A" alias { name = aws_cloudfront_distribution.substandard.domain_name zone_id = aws_cloudfront_distribution.substandard.hosted_zone_id evaluate_target_health = false } } resource "aws_route53_record" "substandard_aaaa" { zone_id = aws_route53_zone.substandard.zone_id name = local.domain type = "AAAA" alias { name = aws_cloudfront_distribution.substandard.domain_name zone_id = aws_cloudfront_distribution.substandard.hosted_zone_id evaluate_target_health = false } } # panoptiblog's own address. viewer-request.js rewrites its root to # /panoptiblog/index.html; every other path is the same release tree. resource "aws_route53_record" "panoptiblog_a" { zone_id = aws_route53_zone.substandard.zone_id name = "panoptiblog.${local.domain}" type = "A" alias { name = aws_cloudfront_distribution.substandard.domain_name zone_id = aws_cloudfront_distribution.substandard.hosted_zone_id evaluate_target_health = false } } resource "aws_route53_record" "panoptiblog_aaaa" { zone_id = aws_route53_zone.substandard.zone_id name = "panoptiblog.${local.domain}" type = "AAAA" alias { name = aws_cloudfront_distribution.substandard.domain_name zone_id = aws_cloudfront_distribution.substandard.hosted_zone_id evaluate_target_health = false } } # Google site verification: proves ownership of substandard.blog to Google # Search Console (https://support.google.com/webmasters/answer/9008080). resource "aws_route53_record" "google_site_verification" { zone_id = aws_route53_zone.substandard.zone_id name = local.domain type = "TXT" records = ["google-site-verification=eB4jsNdK-gM3r9y3Qbz98v2nhq3r0SNcVSNbenw7XEA"] ttl = 300 } # ATProto handle verification: lets substandard.blog resolve as a handle for # the account behind this DID (https://atproto.com/specs/handle). resource "aws_route53_record" "atproto_handle" { zone_id = aws_route53_zone.substandard.zone_id name = "_atproto.${local.domain}" type = "TXT" records = ["did=did:plc:jlle5fhgsrzlqybnpfysavg4"] ttl = 300 } # --- panoptiblog: the scheduled index job ---------------------------------- # # One Fargate task a day reads the network and replaces s3:/// # panoptiblog/data.json. It runs in the default VPC because this account has # no other one and the job needs only outbound access. The task role can write # exactly that prefix; the execution role is the ordinary ECS one. # # The image is built and pushed by scripts/panoptiblog/deploy.sh, which also # writes the commit tag into panoptiblog_image_tag. data "aws_vpc" "default" { default = true } data "aws_subnets" "default" { filter { name = "vpc-id" values = [data.aws_vpc.default.id] } } data "aws_iam_policy_document" "ecs_tasks_assume" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["ecs-tasks.amazonaws.com"] } } } data "aws_iam_policy_document" "events_assume" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["events.amazonaws.com"] } } } resource "aws_ecr_repository" "panoptiblog" { name = "substandard-panoptiblog" image_tag_mutability = "MUTABLE" image_scanning_configuration { scan_on_push = true } } resource "aws_ecr_lifecycle_policy" "panoptiblog" { repository = aws_ecr_repository.panoptiblog.name policy = jsonencode({ rules = [{ rulePriority = 1 description = "Keep the last 30 job images" selection = { tagStatus = "any" countType = "imageCountMoreThan" countNumber = 30 } action = { type = "expire" } }] }) } resource "aws_cloudwatch_log_group" "panoptiblog" { name = "/ecs/panoptiblog" retention_in_days = 30 } resource "aws_iam_role" "panoptiblog_execution" { name = "substandard-panoptiblog-execution" assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json } resource "aws_iam_role_policy_attachment" "panoptiblog_execution" { role = aws_iam_role.panoptiblog_execution.name policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" } resource "aws_iam_role" "panoptiblog_task" { name = "substandard-panoptiblog-task" assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json } resource "aws_iam_role_policy" "panoptiblog_task" { role = aws_iam_role.panoptiblog_task.id policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Action = ["s3:PutObject"] Resource = "${aws_s3_bucket.substandard.arn}/panoptiblog/*" }] }) } resource "aws_iam_role" "panoptiblog_events" { name = "substandard-panoptiblog-events" assume_role_policy = data.aws_iam_policy_document.events_assume.json } resource "aws_iam_role_policy" "panoptiblog_events" { role = aws_iam_role.panoptiblog_events.id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["ecs:RunTask"] Resource = [aws_ecs_task_definition.panoptiblog.arn] }, { Effect = "Allow" Action = ["iam:PassRole"] Resource = [aws_iam_role.panoptiblog_execution.arn, aws_iam_role.panoptiblog_task.arn] }, ] }) } resource "aws_security_group" "panoptiblog" { name_prefix = "substandard-panoptiblog-" description = "Scheduled panoptiblog job: outbound only" vpc_id = data.aws_vpc.default.id egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_ecs_cluster" "panoptiblog" { name = "substandard-panoptiblog" } resource "aws_ecs_task_definition" "panoptiblog" { family = "substandard-panoptiblog" requires_compatibilities = ["FARGATE"] network_mode = "awsvpc" cpu = "1024" memory = "2048" execution_role_arn = aws_iam_role.panoptiblog_execution.arn task_role_arn = aws_iam_role.panoptiblog_task.arn container_definitions = jsonencode([{ name = "panoptiblog" image = "${aws_ecr_repository.panoptiblog.repository_url}:${var.panoptiblog_image_tag}" essential = true environment = [ { name = "PANOPTIBLOG_BUCKET", value = aws_s3_bucket.substandard.bucket }, { name = "PANOPTIBLOG_KEY", value = "panoptiblog/data.json" }, ] logConfiguration = { logDriver = "awslogs" options = { "awslogs-group" = aws_cloudwatch_log_group.panoptiblog.name "awslogs-region" = "us-east-1" "awslogs-stream-prefix" = "panoptiblog" } } }]) } resource "aws_cloudwatch_event_rule" "panoptiblog" { name = "substandard-panoptiblog-daily" description = "Refresh the panoptiblog dataset" schedule_expression = "cron(17 4 * * ? *)" } resource "aws_cloudwatch_event_target" "panoptiblog" { rule = aws_cloudwatch_event_rule.panoptiblog.name arn = aws_ecs_cluster.panoptiblog.arn role_arn = aws_iam_role.panoptiblog_events.arn ecs_target { task_count = 1 task_definition_arn = aws_ecs_task_definition.panoptiblog.arn launch_type = "FARGATE" network_configuration { subnets = data.aws_subnets.default.ids security_groups = [aws_security_group.panoptiblog.id] assign_public_ip = true } } retry_policy { maximum_retry_attempts = 2 maximum_event_age_in_seconds = 3600 } } # Two failures worth naming: EventBridge could not start the task at all, and # the task ran but refused to publish an incomplete dataset (the indexer logs # that exact phrase and exits non-zero). resource "aws_cloudwatch_metric_alarm" "panoptiblog_invoke" { alarm_name = "substandard-panoptiblog-failed-invocations" alarm_description = "The daily panoptiblog task could not be started" namespace = "AWS/Events" metric_name = "FailedInvocations" dimensions = { RuleName = aws_cloudwatch_event_rule.panoptiblog.name } statistic = "Sum" period = 300 evaluation_periods = 1 threshold = 1 comparison_operator = "GreaterThanOrEqualToThreshold" treat_missing_data = "notBreaching" } resource "aws_cloudwatch_log_metric_filter" "panoptiblog_failure_rate" { name = "substandard-panoptiblog-failure-rate" log_group_name = aws_cloudwatch_log_group.panoptiblog.name pattern = "\"exceeds --max-failure-rate\"" metric_transformation { name = "PanoptiblogFailureRate" namespace = "substandard/panoptiblog" value = "1" } } resource "aws_cloudwatch_metric_alarm" "panoptiblog_failure_rate" { alarm_name = "substandard-panoptiblog-failure-rate" alarm_description = "The panoptiblog index refused to publish an incomplete dataset" namespace = "substandard/panoptiblog" metric_name = "PanoptiblogFailureRate" statistic = "Sum" period = 300 evaluation_periods = 1 threshold = 1 comparison_operator = "GreaterThanOrEqualToThreshold" treat_missing_data = "notBreaching" } output "panoptiblog_repository_url" { value = aws_ecr_repository.panoptiblog.repository_url } output "panoptiblog_cluster" { value = aws_ecs_cluster.panoptiblog.name } output "panoptiblog_task_definition" { value = aws_ecs_task_definition.panoptiblog.arn } output "panoptiblog_subnet" { description = "One default-VPC subnet for a manual one-off run" value = data.aws_subnets.default.ids[0] } output "panoptiblog_security_group" { value = aws_security_group.panoptiblog.id } output "panoptiblog_data_url" { value = "https://substandard.blog/panoptiblog/data.json" }