#!/usr/bin/env bash
# CyberTwin export recipe: Okta sign-on, MFA, password and access policies, each with its rules.
# Read-only: use a token from a Read-Only Administrator. Runs on your machine,
# writes local files, sends nothing to CyberTwin. Upload okta-policies.json (and the other files it writes) at /upload.
#
# Calls, both read from Okta's API reference on 2026-11-11:
#   List all policies       GET /api/v1/policies?type=<type>
#     https://developer.okta.com/docs/api/openapi/okta-management/management/tags/policy/other/listpolicies
#   List all policy rules   GET /api/v1/policies/{policyId}/rules
#     https://developer.okta.com/docs/api/openapi/okta-management/management/tags/policy/other/listpolicyrules
# Okta's policy object has no "rules" member, so the rules of each policy are fetched with the
# second call and attached to the policy as "rules". Long lists are read page by page, by the
# Link header Okta sends (https://developer.okta.com/docs/api/ , Pagination).
#
# A policy whose rules Okta did not return is written WITHOUT a "rules" member, and the script
# says so. CyberTwin then reports those rules as not in the file. It never reads them as "no rule".
#
# The script then reads nine more Okta answers and writes each, as Okta sends it, to its own file
# (upload each file at /upload as Okta). Each was read from Okta's API reference on 2026-11-23,
# https://developer.okta.com/docs/api/openapi/okta-management/management/tag/<Tag>/ :
#   List all authenticators            GET /api/v1/authenticators         okta-authenticators.json   (tag Authenticator)
#   Retrieve the ThreatInsight config  GET /api/v1/threats/configuration  okta-threatinsight.json    (tag ThreatInsight)
#   List all network zones             GET /api/v1/zones                  okta-network-zones.json    (tag NetworkZone)
#   List all event hooks               GET /api/v1/eventHooks             okta-event-hooks.json      (tag EventHook)
#   List all trusted origins           GET /api/v1/trustedOrigins         okta-trusted-origins.json  (tag TrustedOrigin)
#   List all behavior detection rules  GET /api/v1/behaviors              okta-behaviors.json        (tag Behavior)
#   List all identity providers        GET /api/v1/idps                   okta-idps.json             (tag IdentityProvider)
#   List all applications              GET /api/v1/apps                   okta-apps.json             (tag Application)
#   List all group rules               GET /api/v1/groups/rules?expand=groupIdToGroupNameMap
#                                                                          okta-group-rules.json      (tag GroupRule; the expand adds the
#                                                                          name of each group a rule assigns)
# An answer Okta does not return (for example a feature your org does not have) is skipped and named;
# the other files are still written.
#
# Usage: OKTA_ORG=acme.okta.com OKTA_TOKEN=... ./okta-policies.sh
set -euo pipefail
: "${OKTA_ORG:?set OKTA_ORG, e.g. acme.okta.com}"
: "${OKTA_TOKEN:?set OKTA_TOKEN (a read-only admin API token)}"
out="okta-policies.json"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

# fetch_all <url> <file>: every page of one list, one JSON object per line, into <file>.
# Returns 1 when Okta answers with anything other than HTTP 200 and a JSON list.
fetch_all() {
  local url="$1" dest="$2" code next
  : > "$dest"
  while [ -n "$url" ]; do
    code=$(curl -sS -o "$work/body" -D "$work/head" -w '%{http_code}' \
      -H "Accept: application/json" -H "Authorization: SSWS ${OKTA_TOKEN}" "$url") || return 1
    if [ "$code" != "200" ]; then
      echo "  Okta answered HTTP $code for ${url%%\?*}" >&2
      return 1
    fi
    jq -c 'if type == "array" then .[] else error("not a list") end' "$work/body" >> "$dest" 2>/dev/null || return 1
    # The next page, if any: the Link header whose rel is "next".
    next=$(tr -d '\r' < "$work/head" | grep -i '^link:' | grep 'rel="next"' \
      | sed -E 's/.*<([^>]+)>; *rel="next".*/\1/' | head -n 1 || true)
    # Follow it only inside your own Okta org, so the token is never sent anywhere else.
    case "$next" in
      "https://${OKTA_ORG}/"*) url="$next" ;;
      *) url="" ;;
    esac
  done
}

: > "$work/policies"
types_read=0
for type in OKTA_SIGN_ON MFA_ENROLL PASSWORD ACCESS_POLICY; do
  if fetch_all "https://${OKTA_ORG}/api/v1/policies?type=${type}" "$work/list"; then
    types_read=$((types_read + 1))
    cat "$work/list" >> "$work/policies"
  else
    echo "Okta did not return the ${type} policies. They are left out of the file." >&2
  fi
done
if [ "$types_read" -eq 0 ]; then
  echo "Okta returned no policy list, so no file was written. Check OKTA_ORG and OKTA_TOKEN." >&2
  exit 1
fi

: > "$work/out"
without_rules=0
while IFS= read -r policy; do
  [ -z "$policy" ] && continue
  id=$(printf '%s' "$policy" | jq -r '.id // empty')
  if [ -n "$id" ] && fetch_all "https://${OKTA_ORG}/api/v1/policies/${id}/rules" "$work/rules"; then
    printf '%s' "$policy" | jq -c --slurpfile rules "$work/rules" '. + {rules: $rules}' >> "$work/out"
  else
    # No "rules" member: the rules of this policy are not in the file.
    printf '%s\n' "$policy" >> "$work/out"
    without_rules=$((without_rules + 1))
    echo "Okta did not return the rules of policy ${id:-with no id}. It is written without rules." >&2
  fi
done < "$work/policies"

jq -s '.' "$work/out" > "$out"
echo "Wrote $out. Upload it at /upload."
if [ "$without_rules" -gt 0 ]; then
  echo "$without_rules policies are in the file without their rules. CyberTwin reports those rules as not in the file."
fi

# The other Okta answers, one file each. A list is read page by page and written as one JSON list; the
# ThreatInsight configuration is one object and is written as Okta sends it.
for pair in authenticators:okta-authenticators.json zones:okta-network-zones.json eventHooks:okta-event-hooks.json \
  trustedOrigins:okta-trusted-origins.json behaviors:okta-behaviors.json idps:okta-idps.json apps:okta-apps.json \
  'groups/rules?expand=groupIdToGroupNameMap:okta-group-rules.json'; do
  path="${pair%:*}"; file="${pair##*:}"
  if fetch_all "https://${OKTA_ORG}/api/v1/${path}" "$work/list"; then
    if [ -s "$work/list" ]; then
      jq -s '.' "$work/list" > "$file"
      echo "Wrote $file. Upload it at /upload."
    else
      echo "Okta returned an empty list for /api/v1/${path%%\?*}. $file was not written: there is nothing in it to review."
    fi
  else
    echo "Okta did not return /api/v1/${path%%\?*}. $file was not written." >&2
  fi
done
code=$(curl -sS -o "$work/body" -w '%{http_code}' \
  -H "Accept: application/json" -H "Authorization: SSWS ${OKTA_TOKEN}" "https://${OKTA_ORG}/api/v1/threats/configuration") || code=""
if [ "$code" = "200" ] && jq -e 'type == "object"' "$work/body" > /dev/null 2>&1; then
  jq '.' "$work/body" > okta-threatinsight.json
  echo "Wrote okta-threatinsight.json. Upload it at /upload."
else
  echo "Okta did not return /api/v1/threats/configuration. okta-threatinsight.json was not written." >&2
fi
