Improve OCI authentication priority in tofu_authenticate_oci function

Summary

The current tofu_authenticate_oci function (lines 275-298) uses CI_REGISTRY_USER and CI_REGISTRY_PASSWORD as hardcoded credentials. This should be improved to prioritize GITLAB_TOFU_TOKEN when available, with fallback to existing credentials.

Current Implementation

tofu_authenticate_oci() {
  if command -v oras >/dev/null 2>&1; then
    oras login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
  else
    # ... writes hardcoded CI_REGISTRY_USER/CI_REGISTRY_PASSWORD
  fi
}

Proposed Solution

Implement a priority-based credential selection:

tofu_authenticate_oci() {
  # Priority: GITLAB_TOFU_TOKEN > CI_REGISTRY_PASSWORD > CI_JOB_TOKEN
  registry_user="${CI_REGISTRY_USER:-gitlab-ci-token}"
  registry_password="${GITLAB_TOFU_TOKEN:-${CI_REGISTRY_PASSWORD:-${CI_JOB_TOKEN}}}"
  
  if command -v oras >/dev/null 2>&1; then
    oras login -u "$registry_user" -p "$registry_password" "$CI_REGISTRY"
  else
    oci_credentials_marker="# OCI credentials have automatically added by gitlab-tofu"
    
    if [ -z "${TF_CLI_CONFIG_FILE}" ]; then
      export TF_CLI_CONFIG_FILE="${default_tf_cli_config_file}"
    fi

    if ! grep -q "${oci_credentials_marker}" "${TF_CLI_CONFIG_FILE}" 2>/dev/null; then
      cat <<EOF >> "${TF_CLI_CONFIG_FILE}"

${oci_credentials_marker}
oci_credentials "${CI_REGISTRY}" {
  username = "${registry_user}"
  password = "${registry_password}"
}
EOF
    fi
  fi
}

Benefits

  • Consistent with other authentication mechanisms in the script
  • Allows users to use GITLAB_TOFU_TOKEN for OCI authentication
  • Maintains backward compatibility with existing setups
  • Provides fallback chain for maximum flexibility