diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..86e884b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..1a899bc --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,31 @@ +name: release + +on: + push: + branches: + - main + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + + - name: Bump Version + id: tag_version + uses: mathieudutour/github-tag-action@d28fa2ccfbd16e871a4bdf35e11b3ad1bd56c0c1 # v6.2 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + default_bump: minor + custom_release_rules: bug:patch:Fixes,chore:patch:Chores,docs:patch:Documentation,feat:minor:Features,refactor:minor:Refactors,test:patch:Tests,ci:patch:Development,dev:patch:Development + + - name: Create Release + uses: ncipollo/release-action@b7eabc95ff50cbeeedec83973935c8f306dfcd0b # v1.20.0 + with: + tag: ${{ steps.tag_version.outputs.new_tag }} + name: ${{ steps.tag_version.outputs.new_tag }} + body: ${{ steps.tag_version.outputs.changelog }} diff --git a/.github/workflows/semantic-check.yml b/.github/workflows/semantic-check.yml new file mode 100644 index 0000000..da1dad8 --- /dev/null +++ b/.github/workflows/semantic-check.yml @@ -0,0 +1,26 @@ +name: semantic-check +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + contents: read + pull-requests: read + +jobs: + main: + name: Semantic Commit Message Check + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + - name: Check PR for Semantic Commit Message + uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + requireScope: false + validateSingleCommit: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7d6cf73 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,62 @@ +name: test + +on: + pull_request: + branches: [ main ] + push: + branches: [ main ] + +permissions: + contents: read + pull-requests: write + +env: + TF_IN_AUTOMATION: true + +jobs: + lint: + name: lint + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + - name: Setup Terraform + uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3.1.2 + - name: Cache Terraform Plugins + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/.terraform.d/plugin-cache + key: tf-plugins-${{ runner.os }}-${{ hashFiles('**/.terraform.lock.hcl') }} + - name: Initialize Terraform + run: terraform init + - name: Suggest Terraform Format + if: github.event_name == 'pull_request' + uses: reviewdog/action-suggester@fc4b06f8697e1e66bd66703f660005079be0b3dc # v1.24.0 + with: + tool_name: terraform-fmt + level: warning + github_token: ${{ secrets.GITHUB_TOKEN }} + fail_level: error + - name: Check Terraform Format + if: github.event_name == 'push' + run: terraform fmt -recursive -check + - name: Validate Terraform + uses: reviewdog/action-terraform-validate@6f4d41dfe9cf0c095aec3d341110eadb4c90c360 # v1.16.1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + reporter: github-pr-review + level: warning + fail_level: error + # - name: Lint Terraform + # uses: reviewdog/action-tflint@9cbfc0aeae4af75fb73e8d5b6efbcd82e9483532 # v1.25.0 + # with: + # reporter: github-pr-review + # filter_mode: nofilter + # fail_level: error + - name: Lint GitHub Actions + uses: reviewdog/action-actionlint@2ca4336c1821eaff87db1f72fd3923b3250e0427 # v1.69.0 + with: + reporter: github-pr-check + fail_level: error + filter_mode: nofilter diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c979019 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +# terraform files +.terraform +.terraform.* +.terraformrc +terraform.rc +*.tfvars +*.tfvars.json +*.tfstate +*.tfstate.* +*tfplan* + +override.tf +override.tf.json +*_override.tf +*_override.tf.json + +# Crash log files +crash.log +crash.*.log + +# IDE +.idea/ +.vscode/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Environment variables +.env +.env.local + +# Build artifacts +dist/ +*.zip diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9021852 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Crux Stack + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index bd3eeec..937a2b2 100644 --- a/README.md +++ b/README.md @@ -1 +1,255 @@ # terraform-aws-github-ops-app + +Terraform module that deploys the [GitHub Ops App](https://github.com/cruxstack/github-ops-app) +to AWS Lambda with API Gateway for webhook handling. + +## Features + +- **Okta Group Sync** - Automatically syncs Okta groups to GitHub teams based + on configurable rules +- **Orphaned User Detection** - Identifies org members not in any synced Okta + teams +- **PR Compliance Monitoring** - Detects when PRs bypass branch protection + rules +- **Automatic Reconciliation** - Detects external team changes and triggers + sync +- **Slack Notifications** - Rich messages for violations and sync reports + +## Usage + +```hcl +module "github_ops_app" { + source = "github.com/cruxstack/terraform-aws-github-ops-app?ref=v1.0.0" + + name = "github-ops" + + # github app configuration (required) + # webhook_secret is optional - if not provided, one will be auto-generated + github_app_config = { + app_id = "123456" + private_key = var.github_app_private_key + installation_id = "12345678" + org = "my-org" + } + + # okta configuration (optional) + okta_config = { + enabled = true + domain = "mycompany.okta.com" + client_id = var.okta_client_id + private_key = var.okta_private_key + github_user_field = "login" + sync_safety_threshold = 0.5 + sync_rules = [ + { + okta_group = "engineering-team" + github_team = "engineers" + } + ] + } + + # schedule okta sync every hour + okta_sync_schedule = { + enabled = true + schedule_expression = "rate(1 hour)" + } + + # pr compliance monitoring + pr_compliance_config = { + enabled = true + monitored_branches = ["main", "master"] + } + + # slack notifications (optional) + slack_config = { + enabled = true + token = var.slack_token + channel = "#github-ops" + channel_pr_bypass = "#security-alerts" # optional: override for PR bypass alerts + channel_okta_sync = "#team-sync" # optional: override for sync reports + channel_orphaned_users = "#security-alerts" # optional: override for orphaned user alerts + } +} +``` + +## Quick Start + +- **Create a GitHub App** with the required permissions + - [GitHub Ops App documentation](https://github.com/cruxstack/github-ops-app)) +- **Deploy this module** with your GitHub App credentials +- **Configure the webhook URL** in your GitHub App settings using the + `webhook_url` output +- **Optionally configure Okta** for team synchronization +- **Optionally configure Slack** for notifications + +## Examples + +- [Complete Example](examples/complete) - Full configuration with all features + enabled + +## Inputs + +| Name | Description | Type | Default | Required | +|-------------------------------|------------------------------------------------------------------------------|----------------|------------------------------------------------------|:--------:| +| `github_app_config` | GitHub App configuration for authentication and webhook handling | `object` | n/a | yes | +| `bot_version` | Version of the GitHub Ops App to use (`latest` or specific tag like `v0.1.0`)| `string` | `"latest"` | no | +| `bot_repo` | GitHub repository URL for the GitHub Ops App source code | `string` | `"https://github.com/cruxstack/github-ops-app.git"` | no | +| `bot_force_rebuild_id` | ID to force rebuilding the Lambda function source code | `string` | `""` | no | +| `lambda_config` | Configuration for the Lambda function | `object` | `{}` | no | +| `lambda_log_retention_days` | Number of days to retain Lambda function logs | `number` | `30` | no | +| `lambda_environment_variables`| Additional environment variables for the Lambda function | `map(string)` | `{}` | no | +| `okta_config` | Okta configuration for user and group synchronization | `object` | `{}` | no | +| `okta_sync_schedule` | EventBridge schedule configuration for automatic Okta sync | `object` | `{}` | no | +| `pr_compliance_config` | Configuration for PR compliance monitoring | `object` | `{}` | no | +| `slack_config` | Slack integration configuration for notifications | `object` | `{}` | no | +| `api_gateway_config` | Configuration for the API Gateway | `object` | `{}` | no | +| `ssm_parameter_arns` | List of SSM Parameter Store ARNs for secrets retrieval | `list(string)` | `[]` | no | + +### GitHub App Config + +```hcl +github_app_config = { + app_id = string # GitHub App ID + private_key = string # GitHub App private key (PEM format) + installation_id = string # GitHub App installation ID + org = string # GitHub organization name + webhook_secret = string # (optional) GitHub webhook secret - auto-generated if not provided +} +``` + +### Okta Config + +```hcl +okta_config = { + enabled = bool # Enable Okta integration (default: false) + domain = string # Okta domain (e.g., "mycompany.okta.com") + client_id = string # Okta OAuth client ID + private_key = string # Okta private key for OAuth + key_id = string # (optional) Okta private key ID + github_user_field = string # Okta field containing GitHub username (default: "login") + sync_rules = list(any) # List of sync rules mapping Okta groups to GitHub teams + sync_safety_threshold = number # Safety threshold to prevent mass removal (default: 0.5) + orphaned_user_notifications = bool # Notify about users not in any synced team (default: true) +} +``` + +#### Sync Rules + +Sync rules support both simple and pattern-based formats: + +```hcl +# Simple format - direct mapping +sync_rules = [ + { + okta_group = "engineering-team" + github_team = "engineers" + } +] + +# Pattern-based format - for multiple groups +sync_rules = [ + { + name = "sync-engineering-teams" + enabled = true + okta_group_pattern = "^github-eng-.*" + github_team_prefix = "eng-" + strip_prefix = "github-eng-" + sync_members = true + create_team_if_missing = true + } +] +``` + +See the [GitHub Ops App documentation](https://github.com/cruxstack/github-ops-app/blob/main/docs/okta-setup.md#step-10-configure-sync-rules) for detailed sync rule configuration. + +### Lambda Config + +```hcl +lambda_config = { + memory_size = number # Memory in MB (default: 256) + timeout = number # Timeout in seconds (default: 30) + runtime = string # Lambda runtime (default: "provided.al2023") + architecture = string # CPU architecture (default: "x86_64") + reserved_concurrent_executions = number # Reserved concurrency (default: -1, unreserved) +} +``` + +### Slack Config + +```hcl +slack_config = { + enabled = bool # Enable Slack integration (default: false) + token = string # Slack bot token (xoxb-...) + channel = string # Default Slack channel ID for notifications + channel_pr_bypass = string # (optional) Channel for PR bypass alerts + channel_okta_sync = string # (optional) Channel for sync reports + channel_orphaned_users = string # (optional) Channel for orphaned user alerts +} +``` + +Per-notification channels are optional and fall back to the default `channel` if not specified. + +## Outputs + +| Name | Description | +|----------------------------------|------------------------------------------------------| +| `lambda_function_arn` | ARN of the GitHub Ops App Lambda function | +| `lambda_function_name` | Name of the GitHub Ops App Lambda function | +| `lambda_function_qualified_arn` | Qualified ARN of the Lambda function | +| `lambda_function_invoke_arn` | Invoke ARN of the Lambda function | +| `lambda_role_arn` | ARN of the IAM role used by the Lambda function | +| `lambda_role_name` | Name of the IAM role used by the Lambda function | +| `cloudwatch_log_group_name` | Name of the CloudWatch Log Group | +| `cloudwatch_log_group_arn` | ARN of the CloudWatch Log Group | +| `api_gateway_id` | ID of the API Gateway HTTP API | +| `api_gateway_arn` | ARN of the API Gateway HTTP API | +| `api_gateway_endpoint` | Base URL of the API Gateway | +| `api_gateway_execution_arn` | Execution ARN of the API Gateway | +| `webhook_url` | Full webhook URL to configure in GitHub App settings | +| `webhook_secret` | Webhook secret to configure in GitHub App | +| `eventbridge_rule_arn` | ARN of the EventBridge rule for scheduled Okta sync | +| `eventbridge_rule_name` | Name of the EventBridge rule | + +## Architecture + +``` + +------------------+ + | GitHub App | + +--------+---------+ + | + | Webhooks + v ++------------------+ +----------+---------+ +| EventBridge | | API Gateway | +| (Scheduled) | | HTTP API | ++--------+---------+ +----------+---------+ + | | + | /scheduled/okta-sync | /webhooks + | | + +----------------+------------------+ + | + v + +----------+---------+ + | Lambda | + | GitHub Ops App | + +----------+---------+ + | + +---------------+---------------+ + | | | + v v v + +------+------+ +------+------+ +------+------+ + | GitHub | | Okta | | Slack | + | API | | API | | API | + +-------------+ +-------------+ +-------------+ +``` + +## Requirements + +| Name | Version | +|-----------|---------| +| terraform | >= 1.3 | +| aws | >= 5.0 | + +## License + +MIT Licensed. See [LICENSE](LICENSE) for full details. diff --git a/assets/lambda-function/Dockerfile b/assets/lambda-function/Dockerfile new file mode 100644 index 0000000..d1b04a3 --- /dev/null +++ b/assets/lambda-function/Dockerfile @@ -0,0 +1,31 @@ +# --------------------------------------------------------------------- base --- + +FROM golang:1.24-alpine AS base + +ARG BOT_VERSION=latest +ARG BOT_REPO=https://github.com/cruxstack/github-ops-app.git + +WORKDIR /build + +RUN apk add --no-cache git make zip + +RUN if [ "${BOT_VERSION}" = "latest" ]; then \ + git clone --depth 1 ${BOT_REPO} .; \ + else \ + git clone --depth 1 --branch ${BOT_VERSION} ${BOT_REPO} .; \ + fi + +RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build \ + -ldflags="-s -w" \ + -o bootstrap \ + ./cmd/lambda + +# ------------------------------------------------------------------ package --- + +FROM alpine:latest AS package + +COPY --from=base /build/bootstrap /opt/app/dist/bootstrap + +RUN apk add zip \ + && cd /opt/app/dist \ + && zip -r /tmp/package.zip . diff --git a/context.tf b/context.tf new file mode 100644 index 0000000..2592ce2 --- /dev/null +++ b/context.tf @@ -0,0 +1,246 @@ +module "this" { + source = "cloudposse/label/null" + version = "0.25.0" + + enabled = var.enabled + namespace = var.namespace + tenant = var.tenant + environment = var.environment + stage = var.stage + name = var.name + delimiter = var.delimiter + attributes = var.attributes + tags = var.tags + additional_tag_map = var.additional_tag_map + regex_replace_chars = var.regex_replace_chars + label_order = var.label_order + id_length_limit = var.id_length_limit + label_key_case = var.label_key_case + label_value_case = var.label_value_case + descriptor_formats = var.descriptor_formats + labels_as_tags = var.labels_as_tags + + context = var.context +} + +variable "context" { + type = any + default = { + enabled = true + namespace = null + tenant = null + environment = null + stage = null + name = null + delimiter = null + attributes = [] + tags = {} + additional_tag_map = {} + regex_replace_chars = null + label_order = [] + id_length_limit = null + label_key_case = null + label_value_case = null + descriptor_formats = {} + labels_as_tags = ["unset"] + } + description = <<-EOT + Single object for setting entire context at once. + See description of individual variables for details. + Leave string and numeric variables as `null` to use default value. + Individual variable settings (non-null) override settings in context object, + except for attributes, tags, and additional_tag_map, which are merged. + EOT + + validation { + condition = lookup(var.context, "label_key_case", null) == null ? true : contains(["lower", "title", "upper"], var.context["label_key_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`." + } + + validation { + condition = lookup(var.context, "label_value_case", null) == null ? true : contains(["lower", "title", "upper", "none"], var.context["label_value_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "enabled" { + type = bool + default = null + description = "Set to false to prevent the module from creating any resources" +} + +variable "namespace" { + type = string + default = null + description = "ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique" +} + +variable "tenant" { + type = string + default = null + description = "ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for" +} + +variable "environment" { + type = string + default = null + description = "ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'" +} + +variable "stage" { + type = string + default = null + description = "ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'" +} + +variable "name" { + type = string + default = null + description = <<-EOT + ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'. + This is the only ID element not also included as a `tag`. + The "name" tag is set to the full `id` string. There is no tag with the value of the `name` input. + EOT +} + +variable "delimiter" { + type = string + default = null + description = <<-EOT + Delimiter to be used between ID elements. + Defaults to `-` (hyphen). Set to `""` to use no delimiter at all. + EOT +} + +variable "attributes" { + type = list(string) + default = [] + description = <<-EOT + ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`, + in the order they appear in the list. New attributes are appended to the + end of the list. The elements of the list are joined by the `delimiter` + and treated as a single ID element. + EOT +} + +variable "labels_as_tags" { + type = set(string) + default = ["default"] + description = <<-EOT + Set of labels (ID elements) to include as tags in the `tags` output. + Default is to include all labels. + Tags with empty values will not be included in the `tags` output. + Set to `[]` to suppress all generated tags. + **Notes:** + The value of the `name` tag, if included, will be the `id`, not the `name`. + Unlike other `null-label` inputs, the initial setting of `labels_as_tags` cannot be + changed in later chained modules., and changes + to `labels_as_tags` will be ignored. + EOT +} + +variable "tags" { + type = map(string) + default = {} + description = <<-EOT + Additional tags (e.g. `{'BusinessUnit': 'XYZ'}`). + Neither the tag keys nor the tag values will be modified by this module. + EOT +} + +variable "additional_tag_map" { + type = map(string) + default = {} + description = <<-EOT + Additional key-value pairs to add to each map in `tags_as_list_of_maps`. Not added to `tags` or `id`. + This is for some rare cases where resources want additional configuration of tags + and therefore take a list of maps with tag key, value, and additional configuration. + EOT +} + +variable "label_order" { + type = list(string) + default = null + description = <<-EOT + The order in which the labels (ID elements) appear in the `id`. + Defaults to ["namespace", "environment", "stage", "name", "attributes"]. + You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present. + EOT +} + +variable "regex_replace_chars" { + type = string + default = null + description = <<-EOT + Terraform regular expression (regex) string. + Characters matching the regex will be removed from the ID elements. + If not set, `"/[^a-zA-Z0-9-]/"` is used to remove all characters other than hyphens, letters and digits. + EOT +} + +variable "id_length_limit" { + type = number + default = null + description = <<-EOT + Limit `id` to this many characters (minimum 6). + Set to `0` for unlimited length. + Set to `null` for keep the existing setting, which defaults to `0`. + Does not affect `id_full`. + EOT + validation { + condition = var.id_length_limit == null ? true : var.id_length_limit >= 6 || var.id_length_limit == 0 + error_message = "The id_length_limit must be >= 6 if supplied (not null), or 0 for unlimited length." + } +} + +variable "label_key_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of the `tags` keys (label names) for tags generated by this module. + Does not affect keys of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper`. + Default value: `title`. + EOT + + validation { + condition = var.label_key_case == null ? true : contains(["lower", "title", "upper"], var.label_key_case) + error_message = "Allowed values: `lower`, `title`, `upper`." + } +} + +variable "label_value_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of ID elements (labels) as included in `id`, + set as tag values, and output by this module individually. + Does not affect values of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper` and `none` (no transformation). + Set this to `title` and set `delimiter` to `""` to yield Pascal Case IDs. + Default value: `lower`. + EOT + + validation { + condition = var.label_value_case == null ? true : contains(["lower", "title", "upper", "none"], var.label_value_case) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "descriptor_formats" { + type = any + default = {} + description = <<-EOT + Describe additional descriptors to be output in the `descriptors` output map. + Map of maps. Keys are names of descriptors. Values are maps of the form + `{ + format = string + labels = list(string) + }` + (Type is `any` so the map values can later be enhanced to provide additional options.) + `format` is a Terraform format string to be passed to the `format()` function. + `labels` is a list of labels, in order, to pass to `format()` function. + Label values will be normalized before being passed to `format()` so they will be + temporary be blank instead of null. + EOT +} diff --git a/examples/complete/main.tf b/examples/complete/main.tf new file mode 100644 index 0000000..bc078ac --- /dev/null +++ b/examples/complete/main.tf @@ -0,0 +1,215 @@ +provider "aws" { + region = "us-east-1" +} + +module "github_ops_app" { + source = "../../" + + # naming context + namespace = "eg" + environment = "uw2" + stage = "prod" + name = "github-ops" + + # bot configuration + bot_version = "latest" # or use a specific version like "v0.1.0" + + # github app configuration (required) + # webhook_secret is optional - if not provided, one will be generated + github_app_config = { + app_id = var.github_app_id + private_key = var.github_app_private_key + installation_id = var.github_app_installation_id + org = var.github_org + # webhook_secret = var.github_webhook_secret # optional - auto-generated if omitted + } + + # okta configuration (optional) + okta_config = { + enabled = true + domain = var.okta_domain + client_id = var.okta_client_id + private_key = var.okta_private_key + key_id = var.okta_key_id # optional + github_user_field = "login" + sync_safety_threshold = 0.5 + orphaned_user_notifications = true + sync_rules = [ + # simple format - direct mapping + { + okta_group = "engineering-team" + github_team = "engineers" + }, + { + okta_group = "platform-team" + github_team = "platform" + }, + # pattern-based format - for multiple groups + # { + # name = "sync-all-github-teams" + # enabled = true + # okta_group_pattern = "^github-.*" + # github_team_prefix = "" + # strip_prefix = "github-" + # sync_members = true + # create_team_if_missing = true + # } + ] + } + + # schedule okta sync every hour + okta_sync_schedule = { + enabled = true + schedule_expression = "rate(1 hour)" + } + + # pr compliance monitoring + pr_compliance_config = { + enabled = true + monitored_branches = ["main", "master", "release/*"] + } + + # slack notifications (optional) + slack_config = { + enabled = true + token = var.slack_token + channel = var.slack_channel + channel_pr_bypass = var.slack_channel_pr_bypass # optional: override for PR bypass alerts + channel_okta_sync = var.slack_channel_okta_sync # optional: override for sync reports + channel_orphaned_users = var.slack_channel_orphaned_users # optional: override for orphaned user alerts + } + + # lambda configuration + lambda_config = { + memory_size = 256 + timeout = 30 + architecture = "x86_64" + } + + lambda_log_retention_days = 30 + + # api gateway configuration + api_gateway_config = { + enabled = true + stage_name = "$default" + cors_allow_origins = ["*"] + } +} + +# ----------------------------------------------------------------------------- +# variables +# ----------------------------------------------------------------------------- + +variable "github_app_id" { + type = string + description = "GitHub App ID" +} + +variable "github_app_private_key" { + type = string + sensitive = true + description = "GitHub App private key (PEM format)" +} + +variable "github_app_installation_id" { + type = string + description = "GitHub App installation ID" +} + +variable "github_org" { + type = string + description = "GitHub organization name" +} + +variable "github_webhook_secret" { + type = string + sensitive = true + description = "GitHub webhook secret (optional - auto-generated if not provided)" + default = "" +} + +variable "okta_domain" { + type = string + description = "Okta domain (e.g., 'mycompany.okta.com')" + default = "" +} + +variable "okta_client_id" { + type = string + description = "Okta OAuth client ID" + default = "" +} + +variable "okta_private_key" { + type = string + sensitive = true + description = "Okta private key for OAuth" + default = "" +} + +variable "okta_key_id" { + type = string + description = "Okta private key ID (optional)" + default = "" +} + +variable "slack_token" { + type = string + sensitive = true + description = "Slack bot token" + default = "" +} + +variable "slack_channel" { + type = string + description = "Slack channel ID for notifications" + default = "" +} + +variable "slack_channel_pr_bypass" { + type = string + description = "Slack channel ID for PR bypass alerts (optional, falls back to slack_channel)" + default = "" +} + +variable "slack_channel_okta_sync" { + type = string + description = "Slack channel ID for Okta sync reports (optional, falls back to slack_channel)" + default = "" +} + +variable "slack_channel_orphaned_users" { + type = string + description = "Slack channel ID for orphaned user alerts (optional, falls back to slack_channel)" + default = "" +} + +# ----------------------------------------------------------------------------- +# outputs +# ----------------------------------------------------------------------------- + +output "lambda_function_arn" { + description = "ARN of the GitHub Ops App Lambda function" + value = module.github_ops_app.lambda_function_arn +} + +output "lambda_function_name" { + description = "Name of the GitHub Ops App Lambda function" + value = module.github_ops_app.lambda_function_name +} + +output "webhook_url" { + description = "Webhook URL to configure in GitHub App settings" + value = module.github_ops_app.webhook_url +} + +output "api_gateway_endpoint" { + description = "API Gateway endpoint URL" + value = module.github_ops_app.api_gateway_endpoint +} + +output "webhook_secret" { + description = "Webhook secret to configure in GitHub App settings" + value = module.github_ops_app.webhook_secret + sensitive = true +} diff --git a/main.tf b/main.tf new file mode 100644 index 0000000..11072e3 --- /dev/null +++ b/main.tf @@ -0,0 +1,294 @@ +# =================================================================== locals === + +locals { + enabled = module.this.enabled + + aws_account_id = data.aws_caller_identity.current.account_id + aws_region_name = data.aws_region.current.id + aws_partition = data.aws_partition.current.partition + + # use provided webhook secret or generate one + github_webhook_secret = var.github_app_config.webhook_secret != "" ? var.github_app_config.webhook_secret : random_password.webhook_secret[0].result + + lambda_environment = merge( + { + # github app config + APP_GITHUB_APP_ID = var.github_app_config.app_id + APP_GITHUB_APP_PRIVATE_KEY = var.github_app_config.private_key + APP_GITHUB_INSTALLATION_ID = var.github_app_config.installation_id + APP_GITHUB_ORG = var.github_app_config.org + APP_GITHUB_WEBHOOK_SECRET = local.github_webhook_secret + + # api gateway config + APP_BASE_PATH = var.api_gateway_config.enabled ? "/${var.api_gateway_config.stage_name}" : "" + + # pr compliance config + APP_PR_COMPLIANCE_ENABLED = tostring(var.pr_compliance_config.enabled) + APP_PR_MONITORED_BRANCHES = var.pr_compliance_config.enabled ? join(",", var.pr_compliance_config.monitored_branches) : "" + }, + # okta config (conditional) + var.okta_config.enabled ? merge({ + APP_OKTA_DOMAIN = var.okta_config.domain + APP_OKTA_CLIENT_ID = var.okta_config.client_id + APP_OKTA_PRIVATE_KEY = var.okta_config.private_key + APP_OKTA_GITHUB_USER_FIELD = var.okta_config.github_user_field + APP_OKTA_SYNC_RULES = length(var.okta_config.sync_rules) > 0 ? jsonencode(var.okta_config.sync_rules) : "" + APP_OKTA_SYNC_SAFETY_THRESHOLD = tostring(var.okta_config.sync_safety_threshold) + APP_OKTA_ORPHANED_USER_NOTIFICATIONS = tostring(var.okta_config.orphaned_user_notifications) + }, var.okta_config.key_id != "" ? { APP_OKTA_KEY_ID = var.okta_config.key_id } : {}) : {}, + # slack config (conditional) + var.slack_config.enabled ? merge({ + APP_SLACK_TOKEN = var.slack_config.token + APP_SLACK_CHANNEL = var.slack_config.channel + }, + var.slack_config.channel_pr_bypass != "" ? { APP_SLACK_CHANNEL_PR_BYPASS = var.slack_config.channel_pr_bypass } : {}, + var.slack_config.channel_okta_sync != "" ? { APP_SLACK_CHANNEL_OKTA_SYNC = var.slack_config.channel_okta_sync } : {}, + var.slack_config.channel_orphaned_users != "" ? { APP_SLACK_CHANNEL_ORPHANED_USERS = var.slack_config.channel_orphaned_users } : {} + ) : {}, + # additional environment variables + var.lambda_environment_variables + ) +} + +data "aws_caller_identity" "current" {} +data "aws_region" "current" {} +data "aws_partition" "current" {} + +# ======================================================== webhook secret === + +resource "random_password" "webhook_secret" { + count = local.enabled && var.github_app_config.webhook_secret == "" ? 1 : 0 + + length = 32 + special = false +} + +# ================================================================== lambda === + +module "bot_artifact" { + source = "github.com/cruxstack/terraform-docker-artifact-packager?ref=v1.4.0" + + count = local.enabled ? 1 : 0 + + attributes = ["lambda"] + artifact_src_path = "/tmp/package.zip" + artifact_dst_directory = "${path.module}/dist" + docker_build_context = abspath("${path.module}/assets/lambda-function") + docker_build_target = "package" + force_rebuild_id = var.bot_force_rebuild_id + + docker_build_args = { + BOT_VERSION = var.bot_version + BOT_REPO = var.bot_repo + } + + context = module.this.context +} + +resource "aws_lambda_function" "this" { + count = local.enabled ? 1 : 0 + + function_name = module.this.id + description = "GitHub Ops App - Automates GitHub organization operations including Okta sync, PR compliance, and team management" + role = aws_iam_role.this[0].arn + handler = "bootstrap" + runtime = var.lambda_config.runtime + memory_size = var.lambda_config.memory_size + timeout = var.lambda_config.timeout + reserved_concurrent_executions = var.lambda_config.reserved_concurrent_executions + architectures = [var.lambda_config.architecture] + + filename = module.bot_artifact[0].artifact_package_path + + environment { + variables = local.lambda_environment + } + + depends_on = [ + aws_cloudwatch_log_group.lambda, + aws_iam_role_policy.this, + module.bot_artifact + ] + + tags = module.this.tags +} + +resource "aws_cloudwatch_log_group" "lambda" { + count = local.enabled ? 1 : 0 + + name = "/aws/lambda/${module.this.id}" + retention_in_days = var.lambda_log_retention_days + tags = module.this.tags +} + +# ============================================================= api gateway === + +resource "aws_apigatewayv2_api" "this" { + count = local.enabled && var.api_gateway_config.enabled ? 1 : 0 + + name = module.this.id + protocol_type = "HTTP" + description = "API Gateway for GitHub Ops App webhooks" + + cors_configuration { + allow_origins = var.api_gateway_config.cors_allow_origins + allow_methods = ["POST", "GET", "OPTIONS"] + allow_headers = ["Content-Type", "X-Hub-Signature-256", "X-GitHub-Event", "X-GitHub-Delivery"] + max_age = 300 + } + + tags = module.this.tags +} + +resource "aws_apigatewayv2_stage" "this" { + count = local.enabled && var.api_gateway_config.enabled ? 1 : 0 + + api_id = aws_apigatewayv2_api.this[0].id + name = var.api_gateway_config.stage_name + auto_deploy = true + + access_log_settings { + destination_arn = aws_cloudwatch_log_group.api_gateway[0].arn + format = jsonencode({ + requestId = "$context.requestId" + ip = "$context.identity.sourceIp" + requestTime = "$context.requestTime" + httpMethod = "$context.httpMethod" + routeKey = "$context.routeKey" + status = "$context.status" + protocol = "$context.protocol" + responseLength = "$context.responseLength" + integrationStatus = "$context.integrationStatus" + }) + } + + tags = module.this.tags +} + +resource "aws_cloudwatch_log_group" "api_gateway" { + count = local.enabled && var.api_gateway_config.enabled ? 1 : 0 + + name = "/aws/apigateway/${module.this.id}" + retention_in_days = var.lambda_log_retention_days + tags = module.this.tags +} + +resource "aws_apigatewayv2_integration" "this" { + count = local.enabled && var.api_gateway_config.enabled ? 1 : 0 + + api_id = aws_apigatewayv2_api.this[0].id + integration_type = "AWS_PROXY" + integration_uri = aws_lambda_function.this[0].invoke_arn + payload_format_version = "2.0" +} + +resource "aws_apigatewayv2_route" "proxy" { + count = local.enabled && var.api_gateway_config.enabled ? 1 : 0 + + api_id = aws_apigatewayv2_api.this[0].id + route_key = "ANY /{proxy+}" + target = "integrations/${aws_apigatewayv2_integration.this[0].id}" +} + +resource "aws_lambda_permission" "api_gateway" { + count = local.enabled && var.api_gateway_config.enabled ? 1 : 0 + + statement_id = "AllowExecutionFromAPIGateway" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.this[0].function_name + principal = "apigateway.amazonaws.com" + source_arn = "${aws_apigatewayv2_api.this[0].execution_arn}/*/*" +} + +# ============================================================= eventbridge === + +resource "aws_cloudwatch_event_rule" "okta_sync" { + count = local.enabled && var.okta_sync_schedule.enabled ? 1 : 0 + + name = "${module.this.id}-okta-sync" + description = "Scheduled trigger for Okta-GitHub team sync" + schedule_expression = var.okta_sync_schedule.schedule_expression + tags = module.this.tags +} + +resource "aws_cloudwatch_event_target" "okta_sync" { + count = local.enabled && var.okta_sync_schedule.enabled ? 1 : 0 + + rule = aws_cloudwatch_event_rule.okta_sync[0].name + target_id = "OktaSyncLambda" + arn = aws_lambda_function.this[0].arn + + input = jsonencode({ + path = "/scheduled/okta-sync" + httpMethod = "POST" + headers = {} + body = "" + }) +} + +resource "aws_lambda_permission" "eventbridge" { + count = local.enabled && var.okta_sync_schedule.enabled ? 1 : 0 + + statement_id = "AllowExecutionFromEventBridge" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.this[0].function_name + principal = "events.amazonaws.com" + source_arn = aws_cloudwatch_event_rule.okta_sync[0].arn +} + +# ---------------------------------------------------------------------- iam --- + +resource "aws_iam_role" "this" { + count = local.enabled ? 1 : 0 + + name = module.this.id + description = "IAM role for GitHub Ops App Lambda function" + + assume_role_policy = jsonencode({ + Version = "2012-10-17", + Statement = [{ + Effect = "Allow" + Principal = { "Service" : "lambda.amazonaws.com" } + Action = ["sts:AssumeRole", "sts:TagSession"] + }] + }) + + tags = module.this.tags +} + +data "aws_iam_policy_document" "this" { + count = local.enabled ? 1 : 0 + + statement { + sid = "CloudWatchLogsAccess" + effect = "Allow" + actions = [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + resources = ["arn:${local.aws_partition}:logs:${local.aws_region_name}:${local.aws_account_id}:log-group:/aws/lambda/${module.this.id}:*"] + } + + dynamic "statement" { + for_each = length(var.ssm_parameter_arns) > 0 ? [1] : [] + + content { + sid = "SSMParameterAccess" + effect = "Allow" + actions = [ + "ssm:GetParameter", + "ssm:GetParameters" + ] + resources = var.ssm_parameter_arns + } + } +} + +resource "aws_iam_role_policy" "this" { + count = local.enabled ? 1 : 0 + + name = module.this.id + role = aws_iam_role.this[0].id + policy = data.aws_iam_policy_document.this[0].json +} diff --git a/outputs.tf b/outputs.tf new file mode 100644 index 0000000..2c23b0a --- /dev/null +++ b/outputs.tf @@ -0,0 +1,90 @@ +# ================================================================== lambda === + +output "lambda_function_arn" { + description = "ARN of the GitHub Ops App Lambda function" + value = try(aws_lambda_function.this[0].arn, null) +} + +output "lambda_function_name" { + description = "Name of the GitHub Ops App Lambda function" + value = try(aws_lambda_function.this[0].function_name, null) +} + +output "lambda_function_qualified_arn" { + description = "Qualified ARN of the GitHub Ops App Lambda function" + value = try(aws_lambda_function.this[0].qualified_arn, null) +} + +output "lambda_function_invoke_arn" { + description = "Invoke ARN of the GitHub Ops App Lambda function" + value = try(aws_lambda_function.this[0].invoke_arn, null) +} + +# --------------------------------------------------------------------- iam --- + +output "lambda_role_arn" { + description = "ARN of the IAM role used by the Lambda function" + value = try(aws_iam_role.this[0].arn, null) +} + +output "lambda_role_name" { + description = "Name of the IAM role used by the Lambda function" + value = try(aws_iam_role.this[0].name, null) +} + +# --------------------------------------------------------------- cloudwatch --- + +output "cloudwatch_log_group_name" { + description = "Name of the CloudWatch Log Group for Lambda function logs" + value = try(aws_cloudwatch_log_group.lambda[0].name, null) +} + +output "cloudwatch_log_group_arn" { + description = "ARN of the CloudWatch Log Group for Lambda function logs" + value = try(aws_cloudwatch_log_group.lambda[0].arn, null) +} + +# -------------------------------------------------------------- api gateway --- + +output "api_gateway_id" { + description = "ID of the API Gateway HTTP API" + value = try(aws_apigatewayv2_api.this[0].id, null) +} + +output "api_gateway_arn" { + description = "ARN of the API Gateway HTTP API" + value = try(aws_apigatewayv2_api.this[0].arn, null) +} + +output "api_gateway_endpoint" { + description = "Base URL of the API Gateway (use this as the GitHub webhook URL base)" + value = try(aws_apigatewayv2_api.this[0].api_endpoint, null) +} + +output "api_gateway_execution_arn" { + description = "Execution ARN of the API Gateway HTTP API" + value = try(aws_apigatewayv2_api.this[0].execution_arn, null) +} + +output "webhook_url" { + description = "Full webhook URL to configure in GitHub App settings" + value = try("${aws_apigatewayv2_stage.this[0].invoke_url}/webhooks", null) +} + +output "webhook_secret" { + description = "Webhook secret to configure in GitHub App settings (generated if not provided)" + value = try(local.github_webhook_secret, null) + sensitive = true +} + +# ============================================================== eventbridge === + +output "eventbridge_rule_arn" { + description = "ARN of the EventBridge rule for scheduled Okta sync (if enabled)" + value = try(aws_cloudwatch_event_rule.okta_sync[0].arn, null) +} + +output "eventbridge_rule_name" { + description = "Name of the EventBridge rule for scheduled Okta sync (if enabled)" + value = try(aws_cloudwatch_event_rule.okta_sync[0].name, null) +} diff --git a/variables.tf b/variables.tf new file mode 100644 index 0000000..66c8fc2 --- /dev/null +++ b/variables.tf @@ -0,0 +1,189 @@ +# ================================================================== general === + +variable "bot_version" { + description = "Version of the GitHub Ops App to use. Use 'latest' for the main branch or a specific version tag like 'v0.1.0'." + type = string + default = "latest" +} + +variable "bot_repo" { + description = "GitHub repository URL for the GitHub Ops App source code." + type = string + default = "https://github.com/cruxstack/github-ops-app.git" +} + +variable "bot_force_rebuild_id" { + description = "ID to force rebuilding the Lambda function source code. Increment this value to trigger a rebuild." + type = string + default = "" +} + +# ------------------------------------------------------------------- lambda --- + +variable "lambda_config" { + description = "Configuration for the GitHub Ops App Lambda function." + type = object({ + memory_size = optional(number, 256) + timeout = optional(number, 30) + runtime = optional(string, "provided.al2023") + architecture = optional(string, "x86_64") + reserved_concurrent_executions = optional(number, -1) + }) + default = {} + + validation { + condition = var.lambda_config.memory_size >= 128 && var.lambda_config.memory_size <= 10240 + error_message = "Lambda memory_size must be between 128 and 10240 MB." + } + + validation { + condition = var.lambda_config.timeout >= 1 && var.lambda_config.timeout <= 900 + error_message = "Lambda timeout must be between 1 and 900 seconds." + } +} + +variable "lambda_log_retention_days" { + description = "Number of days to retain Lambda function logs in CloudWatch Logs." + type = number + default = 30 + + validation { + condition = contains([0, 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653], var.lambda_log_retention_days) + error_message = "Lambda log retention days must be a valid CloudWatch Logs retention period." + } +} + +variable "lambda_environment_variables" { + description = "Additional environment variables for the Lambda function." + type = map(string) + default = {} +} + +# ------------------------------------------------------------------- github --- + +variable "github_app_config" { + description = "GitHub App configuration for authentication and webhook handling. If webhook_secret is not provided, one will be automatically generated." + sensitive = true + type = object({ + app_id = string + private_key = string + installation_id = string + org = string + webhook_secret = optional(string, "") + }) + + validation { + condition = var.github_app_config.app_id != "" + error_message = "GitHub App ID is required." + } + + validation { + condition = var.github_app_config.private_key != "" + error_message = "GitHub App private key is required." + } + + validation { + condition = var.github_app_config.installation_id != "" + error_message = "GitHub App installation ID is required." + } + + validation { + condition = var.github_app_config.org != "" + error_message = "GitHub organization name is required." + } +} + +# --------------------------------------------------------------------- okta --- + +variable "okta_config" { + description = "Okta configuration for user and group synchronization with GitHub teams." + sensitive = true + type = object({ + enabled = optional(bool, false) + domain = optional(string, "") + client_id = optional(string, "") + private_key = optional(string, "") + key_id = optional(string, "") + github_user_field = optional(string, "login") + sync_rules = optional(list(any), []) + sync_safety_threshold = optional(number, 0.5) + orphaned_user_notifications = optional(bool, true) + }) + default = {} + + validation { + condition = !var.okta_config.enabled || (var.okta_config.domain != "" && var.okta_config.client_id != "" && var.okta_config.private_key != "") + error_message = "When Okta is enabled, domain, client_id, and private_key must all be specified." + } + + validation { + condition = var.okta_config.sync_safety_threshold >= 0 && var.okta_config.sync_safety_threshold <= 1 + error_message = "Okta sync safety threshold must be between 0 and 1." + } +} + +variable "okta_sync_schedule" { + description = "EventBridge schedule configuration for automatic Okta-GitHub team synchronization." + type = object({ + enabled = optional(bool, false) + schedule_expression = optional(string, "rate(1 hour)") + }) + default = {} + + validation { + condition = !var.okta_sync_schedule.enabled || can(regex("^(rate|cron)\\(", var.okta_sync_schedule.schedule_expression)) + error_message = "Schedule expression must be a valid EventBridge rate or cron expression." + } +} + +# ----------------------------------------------------------- pr compliance --- + +variable "pr_compliance_config" { + description = "Configuration for PR compliance monitoring to detect branch protection bypasses." + type = object({ + enabled = optional(bool, false) + monitored_branches = optional(list(string), ["main", "master"]) + }) + default = {} +} + +# -------------------------------------------------------------------- slack --- + +variable "slack_config" { + description = "Slack integration configuration for sending notifications." + sensitive = true + type = object({ + enabled = optional(bool, false) + token = optional(string, "") + channel = optional(string, "") + channel_pr_bypass = optional(string, "") + channel_okta_sync = optional(string, "") + channel_orphaned_users = optional(string, "") + }) + default = {} + + validation { + condition = !var.slack_config.enabled || (var.slack_config.token != "" && var.slack_config.channel != "") + error_message = "When Slack is enabled, both token and channel must be specified." + } +} + +# -------------------------------------------------------------- api gateway --- + +variable "api_gateway_config" { + description = "Configuration for the API Gateway that exposes webhook endpoints." + type = object({ + enabled = optional(bool, true) + stage_name = optional(string, "v1") + cors_allow_origins = optional(list(string), ["*"]) + }) + default = {} +} + +# --------------------------------------------------------------------- ssm --- + +variable "ssm_parameter_arns" { + description = "List of SSM Parameter Store ARNs that the Lambda function should have access to for secrets retrieval." + type = list(string) + default = [] +} diff --git a/versions.tf b/versions.tf new file mode 100644 index 0000000..29ec41d --- /dev/null +++ b/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.0" + } + } +}