# workload-identity / oci / t0 "Quick start"
#
# Lets one GitHub repository's main branch act as an Oracle Cloud service user
# with a short-lived session token, so no API key exists at all.
#
# Change the values below, then:
#   terraform init && terraform apply
#   terraform output workflow
#   terraform output -raw client_secret
#
# Store the secret in the repository as OCI_EXCHANGE_CLIENT_SECRET, paste the
# printed workflow into .github/workflows/, and run it. It signs in and reads
# the compartment. Any other branch or repository is refused.
#
# What the secret is. Oracle's token exchange is an OAuth endpoint, and it
# requires a confidential client to authenticate. That client has no role
# and no policy names it, so the secret alone cannot call any Oracle Cloud
# API. It only lets the client present a GitHub token for exchange, and the
# trust below decides whose tokens count. The session that reaches Oracle
# Cloud APIs is never stored. It lasts at most an hour, and no longer than
# the GitHub token that bought it; the workflow prints when it ends.
#
# Needs: a user with manage on the identity domain (Identity Domain
# Administrator, or Domain Administrator of this domain) and on policies in
# the compartment. Credentials come from ~/.oci/config.

locals {
  tenancy_ocid     = "ocid1.tenancy.oc1..aaaaaaaa"                        # change me
  compartment_ocid = "ocid1.compartment.oc1..aaaaaaaa"                    # change me
  domain_url       = "https://idcs-0123456789ab.identity.oraclecloud.com" # change me: the identity domain's URL, from its Overview page
  region           = "us-ashburn-1"                                       # change me
  repository       = "your-org/your-repo"                                 # change me
  branch           = "main"

  # GitHub names the repository and the branch in one claim. Repositories
  # created after 15 July 2026 carry IDs in it:
  #   repo:your-org@123456/your-repo@456789:ref:refs/heads/main
  # The trust matches the subject exactly, so for such a repository paste the
  # value from a real token here. The workflow below prints it.
  subject = "repo:${local.repository}:ref:refs/heads/${local.branch}"

  # The audience the workflow asks GitHub for, and the trust requires.
  audience = "https://cloud.oracle.com"
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = "~> 9.0"
    }
  }
}

provider "oci" {
  region = local.region
}

# The confidential client that may call the exchange endpoint. No role, no
# policy: it can exchange tokens and nothing else.
resource "oci_identity_domains_app" "exchange" {
  idcs_endpoint = local.domain_url
  display_name  = "github-token-exchange"
  description   = "Lets ${local.repository} exchange GitHub tokens for sessions. Has no role."
  schemas       = ["urn:ietf:params:scim:schemas:oracle:idcs:App"]
  active        = true

  based_on_template {
    value = "CustomWebAppTemplateId"
  }

  is_oauth_client = true
  client_type     = "confidential"
  allowed_grants  = ["client_credentials"]
}

# The identity the workflow becomes. A service user cannot sign in, have a
# password, or have an API key.
resource "oci_identity_domains_user" "deploy" {
  idcs_endpoint = local.domain_url
  user_name     = "github-deploy"
  description   = "Acted as by ${local.repository} through token exchange"
  schemas = [
    "urn:ietf:params:scim:schemas:core:2.0:User",
    "urn:ietf:params:scim:schemas:oracle:idcs:extension:user:User",
  ]

  urnietfparamsscimschemasoracleidcsextensionuser_user {
    service_user = true
  }
}

# Policies name groups, so the user gets one of its own.
resource "oci_identity_domains_group" "deploy" {
  idcs_endpoint = local.domain_url
  display_name  = "github-deploy"
  schemas       = ["urn:ietf:params:scim:schemas:core:2.0:Group"]

  members {
    type  = "User"
    value = oci_identity_domains_user.deploy.id
  }
}

# The trust is the whole control. It accepts GitHub's tokens, checked against
# GitHub's published keys, for the one client above, with the one audience,
# and maps exactly one subject to the service user. Every other subject is
# refused.
resource "oci_identity_domains_identity_propagation_trust" "github" {
  idcs_endpoint = local.domain_url
  name          = "github-actions"
  description   = "GitHub Actions, ${local.repository}, ${local.branch} branch"
  schemas       = ["urn:ietf:params:scim:schemas:oracle:idcs:IdentityPropagationTrust"]
  type          = "JWT"
  active        = true

  issuer              = "https://token.actions.githubusercontent.com"
  public_key_endpoint = "https://token.actions.githubusercontent.com/.well-known/jwks"
  oauth_clients       = [oci_identity_domains_app.exchange.name]
  client_claim_name   = "aud"
  client_claim_values = [local.audience]
  subject_claim_name  = "sub"
  subject_type        = "User"
  allow_impersonation = true

  impersonation_service_users {
    rule  = "sub eq '${local.subject}'"
    value = oci_identity_domains_user.deploy.id
  }
}

# Enough to prove the sign-in: read the compartment's own details.
resource "oci_identity_policy" "deploy" {
  compartment_id = local.compartment_ocid
  name           = "github-deploy"
  description    = "Lets ${local.repository} read the compartment, to prove the sign-in"
  statements = [
    "Allow group id ${oci_identity_domains_group.deploy.ocid} to inspect compartments in compartment id ${local.compartment_ocid}",
  ]
}

output "client_id" {
  description = "The exchange client's ID. A public identifier."
  value       = oci_identity_domains_app.exchange.name
}

output "client_secret" {
  description = "Store this in the repository as OCI_EXCHANGE_CLIENT_SECRET. It cannot call Oracle Cloud APIs; it only lets GitHub tokens be exchanged."
  value       = oci_identity_domains_app.exchange.client_secret
  sensitive   = true
}

output "workflow" {
  description = "A workflow that proves the sign-in. id-token: write is what lets it ask GitHub for a token."
  value       = <<-EOT
    name: prove-oci-sign-in
    on: workflow_dispatch
    permissions:
      id-token: write
      contents: read
    jobs:
      whoami:
        runs-on: ubuntu-latest
        env:
          CLIENT_ID: ${oci_identity_domains_app.exchange.name}
          CLIENT_SECRET: $${{ secrets.OCI_EXCHANGE_CLIENT_SECRET }}
        steps:
          - name: Exchange the GitHub token for a session
            shell: bash
            run: |
              JWT=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=${local.audience}" | jq -r .value)
              echo "subject: $(printf %s "$JWT" | python3 -c 'import base64,json,sys; p=sys.stdin.read().split(".")[1]; print(json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))["sub"])')"
              mkdir -p ~/.oci && chmod 700 ~/.oci
              openssl genrsa -out ~/.oci/session.pem 2048 2>/dev/null
              PUBLIC_KEY=$(openssl rsa -in ~/.oci/session.pem -pubout 2>/dev/null | grep -v -- '-----' | tr -d '\n')
              FINGERPRINT=$(openssl rsa -in ~/.oci/session.pem -pubout -outform DER 2>/dev/null | openssl md5 -c | awk '{print $2}')
              curl -sS --fail-with-body -u "$CLIENT_ID:$CLIENT_SECRET" ${local.domain_url}/oauth2/v1/token \
                --data-urlencode grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
                --data-urlencode requested_token_type=urn:oci:token-type:oci-upst \
                --data-urlencode subject_token_type=jwt \
                --data-urlencode "subject_token=$JWT" \
                --data-urlencode "public_key=$PUBLIC_KEY" | jq -er .token > ~/.oci/session.token
              echo "session ends: $(cut -d. -f2 < ~/.oci/session.token | python3 -c 'import base64,datetime,json,sys; p=sys.stdin.read().strip(); print(datetime.datetime.fromtimestamp(json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))["exp"], datetime.timezone.utc).isoformat())' 2>/dev/null || echo unknown)"
              printf '[DEFAULT]\nuser=not used\nfingerprint=%s\nkey_file=%s\ntenancy=%s\nregion=%s\nsecurity_token_file=%s\n' \
                "$FINGERPRINT" "$HOME/.oci/session.pem" "${local.tenancy_ocid}" "${local.region}" "$HOME/.oci/session.token" > ~/.oci/config
              chmod 600 ~/.oci/config
          - run: pip install -q oci-cli
          - run: oci --auth security_token iam compartment get --compartment-id ${local.compartment_ocid} --query data.name --raw-output
  EOT
}
