# brokered-shell-access / aws / t0 "Quick start"
#
# A shell on any EC2 instance through Systems Manager Session Manager: no
# inbound port, no SSH key, no bastion. Every session is recorded to S3 and to
# CloudWatch Logs, with the name of whoever opened it.
#
#   terraform init && terraform apply
#
# Launch an instance with the instance profile and security group this prints.
# The security group has no inbound rules at all. Then:
#   aws ssm start-session --target <instance-id>
#
# Verify: run a command in the session, exit, and find the transcript in the
# bucket and the log group, under your own name.

terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  default_tags {
    tags = {
      owner               = "platform-engineering"
      environment         = "prod"
      data_classification = "confidential"
      managed_by          = "terraform"
    }
  }
}

data "aws_vpc" "default" {
  default = true
}

resource "aws_s3_bucket" "sessions" {
  bucket_prefix = "session-transcripts-"
  force_destroy = true
}

resource "aws_s3_bucket_public_access_block" "sessions" {
  bucket                  = aws_s3_bucket.sessions.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# Session Manager checks that the bucket encrypts by default before it will
# write, because the preferences below ask for it.
resource "aws_s3_bucket_server_side_encryption_configuration" "sessions" {
  bucket = aws_s3_bucket.sessions.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_cloudwatch_log_group" "sessions" {
  name              = "/ssm/sessions"
  retention_in_days = 365
}

# The account-wide Session Manager preferences live in a document with this
# exact name. If someone saved preferences in the console, it already exists:
# import it with terraform import aws_ssm_document.preferences SSM-SessionManagerRunShell.
resource "aws_ssm_document" "preferences" {
  name            = "SSM-SessionManagerRunShell"
  document_type   = "Session"
  document_format = "JSON"
  content = jsonencode({
    schemaVersion = "1.0"
    description   = "Record every session to S3 and CloudWatch Logs."
    sessionType   = "Standard_Stream"
    inputs = {
      s3BucketName                = aws_s3_bucket.sessions.bucket
      s3KeyPrefix                 = "sessions/"
      s3EncryptionEnabled         = true
      cloudWatchLogGroupName      = aws_cloudwatch_log_group.sessions.name
      cloudWatchEncryptionEnabled = false
      cloudWatchStreamingEnabled  = true
      idleSessionTimeout          = "20"
      runAsEnabled                = false
    }
  })
}

# The instance's own role writes the transcript, so it needs the Systems
# Manager basics plus write access to exactly these two places.
data "aws_iam_policy_document" "ec2_trust" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "instance" {
  name_prefix        = "ssm-instance-"
  assume_role_policy = data.aws_iam_policy_document.ec2_trust.json
}

resource "aws_iam_role_policy_attachment" "core" {
  role       = aws_iam_role.instance.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_role_policy" "transcripts" {
  name = "write-session-transcripts"
  role = aws_iam_role.instance.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      { Effect = "Allow", Action = ["s3:PutObject"], Resource = "${aws_s3_bucket.sessions.arn}/sessions/*" },
      { Effect = "Allow", Action = ["s3:GetEncryptionConfiguration"], Resource = aws_s3_bucket.sessions.arn },
      { Effect = "Allow", Action = ["logs:CreateLogStream", "logs:PutLogEvents", "logs:DescribeLogStreams"], Resource = "${aws_cloudwatch_log_group.sessions.arn}:*" },
      { Effect = "Allow", Action = ["logs:DescribeLogGroups"], Resource = "*" },
    ]
  })
}

resource "aws_iam_instance_profile" "instance" {
  name_prefix = "ssm-instance-"
  role        = aws_iam_role.instance.name
}

# No ingress blocks at all: nothing can connect in. The agent only makes
# outbound HTTPS connections to Systems Manager.
resource "aws_security_group" "no_inbound" {
  name_prefix = "no-inbound-"
  description = "No inbound rules. Shell access goes through Session Manager."
  vpc_id      = data.aws_vpc.default.id
  egress {
    description = "HTTPS out, for the Systems Manager agent"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

output "instance_profile" {
  description = "Launch instances with this profile."
  value       = aws_iam_instance_profile.instance.name
}

output "security_group" {
  description = "And this security group, which has no inbound rules."
  value       = aws_security_group.no_inbound.id
}

output "transcripts" {
  description = "Where each session's transcript lands."
  value       = "s3://${aws_s3_bucket.sessions.bucket}/sessions/ and log group ${aws_cloudwatch_log_group.sessions.name}"
}
