# Authentication context and Conditional Access policy for the lab, with Microsoft's msgraph provider.
# Sign in as an app (not the Azure CLI): set ARM_TENANT_ID, ARM_CLIENT_ID, ARM_CLIENT_SECRET_FILE_PATH, ARM_USE_CLI=false.
# Application permissions it needs: Policy.Read.All, Policy.ReadWrite.ConditionalAccess, AuthenticationContext.ReadWrite.All
terraform {
  required_providers {
    msgraph = {
      source  = "microsoft/msgraph"
      version = "~> 0.6.0"
    }
  }
}

provider "msgraph" {}

variable "context_id" {
  description = "A free authentication context ID in your tenant"
  type        = string
  default     = "c1"
}

variable "user_object_id" {
  description = "Object ID of the one test user the policy applies to"
  type        = string
}

variable "policy_state" {
  description = "Start in report-only; use enabled when you are ready (security defaults must be off)"
  type        = string
  default     = "enabledForReportingButNotEnforced"
}

locals {
  context_url = "identity/conditionalAccess/authenticationContextClassReferences/${var.context_id}"
}

# Why three "actions" and not one msgraph_resource: in this lab, v1.0 refused POST (405),
# and reading a context back answered 201, which the provider reports as an error.
# An action sends one request and does not read the object back, so Terraform
# does not detect later changes to the context.
# Terraform destroys in reverse order: policy, then unpublish, then delete.
resource "msgraph_resource_action" "context_delete" {
  resource_url = local.context_url
  method       = "DELETE"
  when         = "destroy"
  retry = {
    error_message_regex = ["(?i)policy", "(?i)conflict", "(?i)in use"]
  }
}

resource "msgraph_resource_action" "context_unpublish" {
  resource_url = local.context_url
  method       = "PATCH"
  body         = { isAvailable = false }
  when         = "destroy"
  depends_on   = [msgraph_resource_action.context_delete]
}

# PATCH creates the context if the ID is free and overwrites it if it is not.
resource "msgraph_resource_action" "context" {
  resource_url = local.context_url
  method       = "PATCH"
  body = {
    displayName = "lab payment step-up"
    description = "lab-authctx"
    isAvailable = true
  }
  depends_on = [msgraph_resource_action.context_unpublish]
}

resource "msgraph_resource" "policy" {
  url = "identity/conditionalAccess/policies"
  body = {
    displayName = "lab-authctx-tf MFA for the payment context"
    state       = var.policy_state
    conditions = {
      clientAppTypes = ["all"]
      users          = { includeUsers = [var.user_object_id] }
      applications   = { includeAuthenticationContextClassReferences = [var.context_id] }
    }
    grantControls = { operator = "OR", builtInControls = ["mfa"] }
  }
  depends_on = [msgraph_resource_action.context]
}

output "context_id" {
  value = var.context_id
}
