data "aws_iam_policy_document" "okta_saml_assume_role_policy" {
  statement {
    sid    = "AllowAssumeRoleViaOkta"
    effect = "Allow"
    principals {
      type        = "Federated"
      identifiers = [aws_iam_saml_provider.okta.arn]
    }

    actions = [
      "sts:AssumeRoleWithSAML",
    ]

    condition {
      test     = "StringEquals"
      variable = "SAML:aud"
      values = [
        local.saml_signin_page[local.aws_partition]
      ]
    }
  }

  # Note this could be a security issue.  We are counting on 
  # All of the other roles, groups, etc in the account to have reasonable
  # limitations on sts:AssumeRole
  statement {
    sid    = "AllowAssumeRoleFromOtherRolesInThisAccount"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = [
        "arn:${local.aws_partition}:iam::${local.aws_account}:root"
      ]
    }

    actions = [
      "sts:AssumeRole",
    ]
  }
}

# Notice the source_json here.  I had forgotten how this worked and
# had to refresh myself.  See terraform AWS provider docs at
# https://www.terraform.io/docs/providers/aws/d/iam_policy_document.html
#   "Statements with non-blank sids in the current policy document will overwrite 
#    statements with the same sid in the source json."
# The idea here is that IF var.trusted_arns is set, then we append a new SID
# to the policy to enable AssumeRole from other accounts.
#
# This ties to local.tf:
# assume_role_policy = (length(var.trusted_arns) > 0) ? 
# data.aws_iam_policy_document.okta_saml_plus_crossaccount_assume_role_policy.json : 
# data.aws_iam_policy_document.okta_saml_assume_role_policy.json
#
# Maybe that local should be defined here in this file and not in locals.tf, not sure which
# is clearer.
data "aws_iam_policy_document" "okta_saml_plus_crossaccount_assume_role_policy" {

  source_json = data.aws_iam_policy_document.okta_saml_assume_role_policy.json

  statement {
    sid    = "AllowAssumeRoleFromOtherAccounts"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = var.trusted_arns
    }

    actions = [
      "sts:AssumeRole",
    ]
  }
}
