ci: Fix security vulnerabilities in remote compiler cache scripts

- Prevent GCS tokens from leaking via set -x or ps aux.
- Bind the credential server to an OS-assigned ephemeral port instead of a predictable port.
- Require a random connection path token to guard against unauthorized loopback access.
- Prevent common.linux.before_script.sh from dumping the token to stdout.
- Add retry logic to fallback curl downloads to wget or python to increase network resilience.
- Add .sccache/, ccache-stats.log and .cred_port to .gitignore.

TAG=agy
CONV=dccfb5eb-a8f3-447a-94d3-7d54f735f1ca
diff --git a/.gitignore b/.gitignore
index 6151903..cb34481 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,3 +51,6 @@
 .ccache/
 .ccache-bin/
 .sccache-bin/
+.sccache/
+ccache-stats.log
+.cred_port
diff --git a/ci/scripts/build.linux.script.sh b/ci/scripts/build.linux.script.sh
index 23cef26..6606974 100755
--- a/ci/scripts/build.linux.script.sh
+++ b/ci/scripts/build.linux.script.sh
@@ -36,42 +36,58 @@
     export SCCACHE_DIR="${CI_PROJECT_DIR}/.sccache"
     export SCCACHE_CACHE_SIZE="${CCACHE_MAXSIZE:-4G}"
     export SCCACHE_BASEDIRS="${rootdir}"
-    export SCCACHE_SERVER_PORT="$((4226 + (${CI_JOB_ID:-0} % 10000)))"
+    export SCCACHE_SERVER_PORT="$((4226 + ${CI_CONCURRENT_ID:-0}))"
 
     # Remote GCS caching via short-lived OAuth token injected from GitLab CI/CD variables:
     # EIGEN_GCS_CACHE_TOKEN_RW (protected branch / master) or EIGEN_GCS_CACHE_TOKEN_RO (MRs)
-    gcs_token="${EIGEN_GCS_CACHE_TOKEN_RW:-${EIGEN_GCS_CACHE_TOKEN_RO:-}}"
     sccache_cred_server_pid=""
-    if [[ -n "${gcs_token}" ]]; then
+    if [[ -n "${EIGEN_GCS_CACHE_TOKEN_RW:-}" || -n "${EIGEN_GCS_CACHE_TOKEN_RO:-}" ]]; then
       export SCCACHE_GCS_BUCKET="${EIGEN_CI_SCCACHE_GCS_BUCKET:-eigen-gitlab-ci-cache}"
       export SCCACHE_MULTILEVEL_CHAIN="disk,gcs"
-      if [[ -n "${EIGEN_GCS_CACHE_TOKEN_RW}" ]]; then
+      if [[ -n "${EIGEN_GCS_CACHE_TOKEN_RW:-}" ]]; then
         export SCCACHE_GCS_RW_MODE="READ_WRITE"
       else
         export SCCACHE_GCS_RW_MODE="READ_ONLY"
       fi
-      cred_port="$((8200 + (${CI_JOB_ID:-0} % 1000)))"
+      export GCS_URL_SECRET=$(od -vN 16 -An -tx1 /dev/urandom | tr -d ' \n')
+      cred_port_file="${PWD}/.cred_port"
+      
+      { set +x; } 2>/dev/null
       python3 -c "
-import http.server, json, sys
-token = sys.argv[1]
+import http.server, json, sys, os
+token = os.environ.get('EIGEN_GCS_CACHE_TOKEN_RW') or os.environ.get('EIGEN_GCS_CACHE_TOKEN_RO')
+secret = os.environ.get('GCS_URL_SECRET')
 class H(http.server.BaseHTTPRequestHandler):
     def do_GET(self):
+        if self.path != '/token/' + secret:
+            self.send_response(403)
+            self.end_headers()
+            return
         self.send_response(200)
         self.send_header('Content-Type', 'application/json')
         self.end_headers()
         self.wfile.write(json.dumps({'access_token': token, 'token_type': 'Bearer', 'expires_in': 3600}).encode())
     def log_message(self, *a): pass
-http.server.HTTPServer(('127.0.0.1', int(sys.argv[2])), H).serve_forever()
-" "${gcs_token}" "${cred_port}" &
+server = http.server.HTTPServer(('127.0.0.1', 0), H)
+with open('${cred_port_file}', 'w') as f:
+    f.write(str(server.server_port))
+server.serve_forever()
+" &
       sccache_cred_server_pid=$!
-      export SCCACHE_GCS_CREDENTIALS_URL="http://127.0.0.1:${cred_port}/token"
       trap '[[ -n "${sccache_cred_server_pid}" ]] && kill "${sccache_cred_server_pid}" 2>/dev/null || true' EXIT
+      set -x
 
-      # Wait up to 1 second for local credential server to be ready
-      for _ in {1..20}; do
-        if curl -s "http://127.0.0.1:${cred_port}/token" >/dev/null 2>&1; then break; fi
+      # Wait up to 2 seconds for local credential server to be ready
+      for _ in {1..40}; do
+        if [[ -s "${cred_port_file}" ]]; then
+          cred_port=$(cat "${cred_port_file}")
+          if curl -s "http://127.0.0.1:${cred_port}/token/${GCS_URL_SECRET}" >/dev/null 2>&1; then break; fi
+        fi
         sleep 0.05
       done
+      export SCCACHE_GCS_CREDENTIALS_URL="http://127.0.0.1:${cred_port}/token/${GCS_URL_SECRET}"
+      rm -f "${cred_port_file}"
+      unset GCS_URL_SECRET
     fi
 
     if "${sccache_bin}" --start-server >/dev/null 2>&1; then
@@ -81,6 +97,7 @@
     else
       echo "Notice: sccache server failed to start (check GCS credentials/network); falling back to ccache."
       [[ -n "${sccache_cred_server_pid}" ]] && kill "${sccache_cred_server_pid}" 2>/dev/null || true
+      sccache_cred_server_pid=""
     fi
   fi
 
@@ -104,7 +121,10 @@
   if [[ "${compiler_launcher}" == "sccache" && -n "${sccache_bin}" ]]; then
     "${sccache_bin}" --show-stats 2>&1 || true
     "${sccache_bin}" --stop-server >/dev/null 2>&1 || true
-    [[ -n "${sccache_cred_server_pid}" ]] && kill "${sccache_cred_server_pid}" 2>/dev/null || true
+    if [[ -n "${sccache_cred_server_pid}" ]]; then
+      kill "${sccache_cred_server_pid}" 2>/dev/null || true
+      sccache_cred_server_pid=""
+    fi
     # Incompatible cache formats: purge unused .ccache/ before cache upload so the
     # uploaded cache archive only holds .sccache/ and stays strictly below the 5 GB runner cap.
     rm -rf "${rootdir}/.ccache"
diff --git a/ci/scripts/build.windows.script.ps1 b/ci/scripts/build.windows.script.ps1
index cd92319..ed36e82 100644
--- a/ci/scripts/build.windows.script.ps1
+++ b/ci/scripts/build.windows.script.ps1
@@ -90,11 +90,11 @@
     # Rewrite paths relative to rootdir for cross-runner / cross-directory cache hits.
     $env:SCCACHE_BASEDIRS = $rootdir
     # Isolate daemon port per runner slot to avoid port collisions and process cross-kill.
-    $env:SCCACHE_SERVER_PORT = [string](4226 + ([int]($env:CI_JOB_ID ? $env:CI_JOB_ID : 0) % 10000))
+    $concurrent_id = if ($env:CI_CONCURRENT_ID) { [int]$env:CI_CONCURRENT_ID } else { 0 }
+    $env:SCCACHE_SERVER_PORT = [string](4226 + $concurrent_id)
 
-    $gcs_token = if ($env:EIGEN_GCS_CACHE_TOKEN_RW) { $env:EIGEN_GCS_CACHE_TOKEN_RW } else { $env:EIGEN_GCS_CACHE_TOKEN_RO }
     $cred_server_job = $null
-    if ($gcs_token) {
+    if ($env:EIGEN_GCS_CACHE_TOKEN_RW -or $env:EIGEN_GCS_CACHE_TOKEN_RO) {
       $env:SCCACHE_GCS_BUCKET = if ($env:EIGEN_CI_SCCACHE_GCS_BUCKET) { $env:EIGEN_CI_SCCACHE_GCS_BUCKET } else { "eigen-gitlab-ci-cache" }
       $env:SCCACHE_MULTILEVEL_CHAIN = "disk,gcs"
       if ($env:EIGEN_GCS_CACHE_TOKEN_RW) {
@@ -102,32 +102,56 @@
       } else {
         $env:SCCACHE_GCS_RW_MODE = "READ_ONLY"
       }
-      $cred_port = [string](8200 + ([int]($env:CI_JOB_ID ? $env:CI_JOB_ID : 0) % 1000))
+      $url_secret = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 16 | % {[char]$_})
+      
       $cred_server_job = Start-Job -ScriptBlock {
-        param($tok, $p)
+        param($path_secret)
+        $tok = if ($env:EIGEN_GCS_CACHE_TOKEN_RW) { $env:EIGEN_GCS_CACHE_TOKEN_RW } else { $env:EIGEN_GCS_CACHE_TOKEN_RO }
         $listener = New-Object System.Net.HttpListener
+        $tcp = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)
+        $tcp.Start()
+        $p = $tcp.Server.LocalEndPoint.Port
+        $tcp.Stop()
         $listener.Prefixes.Add("http://127.0.0.1:$p/")
         $listener.Start()
+        Write-Output "PORT:$p"
         while ($listener.IsListening) {
           $ctx = $listener.GetContext()
           $resp = $ctx.Response
+          if ($ctx.Request.RawUrl -ne "/token/$path_secret") {
+            $resp.StatusCode = 403
+            $resp.Close()
+            continue
+          }
           $resp.ContentType = "application/json"
           $body = [System.Text.Encoding]::UTF8.GetBytes("{`"access_token`":`"$tok`",`"token_type`":`"Bearer`",`"expires_in`":3600}")
           $resp.ContentLength64 = $body.Length
           $resp.OutputStream.Write($body, 0, $body.Length)
           $resp.Close()
         }
-      } -ArgumentList $gcs_token, $cred_port
-      $env:SCCACHE_GCS_CREDENTIALS_URL = "http://127.0.0.1:$cred_port/token"
-
-      # Wait up to 1 second for local credential server to be ready
-      for ($i = 0; $i -lt 20; $i++) {
-        try {
-          $res = Invoke-WebRequest -Uri "http://127.0.0.1:$cred_port/token" -UseBasicParsing -TimeoutSec 1
-          if ($res.StatusCode -eq 200) { break }
-        } catch {}
+      } -ArgumentList $url_secret
+      
+      # Wait up to 2 seconds for local credential server to be ready
+      $cred_port = $null
+      for ($i = 0; $i -lt 40; $i++) {
+        $out = Receive-Job $cred_server_job -ErrorAction SilentlyContinue
+        if ($out) {
+          foreach ($line in $out) {
+            if ($line -match "^PORT:(\d+)$") {
+              $cred_port = $Matches[1]
+              break
+            }
+          }
+        }
+        if ($cred_port) {
+          try {
+            $res = Invoke-WebRequest -Uri "http://127.0.0.1:$cred_port/token/$url_secret" -UseBasicParsing -TimeoutSec 1 -ErrorAction SilentlyContinue
+            if ($res -and $res.StatusCode -eq 200) { break }
+          } catch {}
+        }
         Start-Sleep -Milliseconds 50
       }
+      $env:SCCACHE_GCS_CREDENTIALS_URL = "http://127.0.0.1:$cred_port/token/$url_secret"
     }
 
     & $sccache_exe --start-server | Out-Null
diff --git a/ci/scripts/common.linux.before_script.sh b/ci/scripts/common.linux.before_script.sh
index 5e24c5e..251e04c 100755
--- a/ci/scripts/common.linux.before_script.sh
+++ b/ci/scripts/common.linux.before_script.sh
@@ -26,7 +26,7 @@
 echo "arch=$ARCH, target=${EIGEN_CI_TARGET_ARCH}"
 echo "Processors: ${NPROC}"
 echo "CI Variables:"
-export | grep EIGEN
+export | grep EIGEN | grep -v "CACHE_TOKEN"
 
 # Set noninteractive, otherwise tzdata may be installed and prompt for a
 # geographical region.
diff --git a/ci/scripts/install_compiler_cache.ps1 b/ci/scripts/install_compiler_cache.ps1
index 72eb180..9d9b3cf 100644
--- a/ci/scripts/install_compiler_cache.ps1
+++ b/ci/scripts/install_compiler_cache.ps1
@@ -33,9 +33,18 @@
     # 2. Download and verify sccache.zip
     if (-not $sccache_exe) {
       $zip = Join-Path ([System.IO.Path]::GetTempPath()) "sccache-${sccache_version}.zip"
-      try {
-        $ProgressPreference = "SilentlyContinue"
-        Invoke-WebRequest "https://github.com/mozilla/sccache/releases/download/v${sccache_version}/sccache-v${sccache_version}-x86_64-pc-windows-msvc.zip" -OutFile $zip -TimeoutSec 30
+      $download_success = $false
+      for ($attempt = 1; $attempt -le 3; $attempt++) {
+        try {
+          $ProgressPreference = "SilentlyContinue"
+          Invoke-WebRequest "https://github.com/mozilla/sccache/releases/download/v${sccache_version}/sccache-v${sccache_version}-x86_64-pc-windows-msvc.zip" -OutFile $zip -TimeoutSec 30
+          $download_success = $true
+          break
+        } catch {
+          if ($attempt -lt 3) { Start-Sleep -Seconds 2 } else { Write-Warning "sccache download failed: $_" }
+        }
+      }
+      if ($download_success) {
         if ((Get-FileHash $zip -Algorithm SHA256).Hash -eq $sccache_zip_sha256) {
           $unpack = Join-Path ([System.IO.Path]::GetTempPath()) "sccache-unpack"
           Expand-Archive $zip -DestinationPath $unpack -Force
@@ -53,8 +62,6 @@
           Write-Warning "sccache download failed SHA-256 verification."
         }
         Remove-Item $zip -Force -ErrorAction SilentlyContinue
-      } catch {
-        Write-Warning "sccache download failed ($_); falling back to ccache."
       }
     }
   }
@@ -101,9 +108,18 @@
 
   # 3. Download and verify ccache.zip
   $zip = Join-Path ([System.IO.Path]::GetTempPath()) "ccache-${ccache_version}.zip"
-  try {
-    $ProgressPreference = "SilentlyContinue"
-    Invoke-WebRequest "https://github.com/ccache/ccache/releases/download/v${ccache_version}/ccache-${ccache_version}-windows-x86_64.zip" -OutFile $zip -TimeoutSec 30
+  $download_success = $false
+  for ($attempt = 1; $attempt -le 3; $attempt++) {
+    try {
+      $ProgressPreference = "SilentlyContinue"
+      Invoke-WebRequest "https://github.com/ccache/ccache/releases/download/v${ccache_version}/ccache-${ccache_version}-windows-x86_64.zip" -OutFile $zip -TimeoutSec 30
+      $download_success = $true
+      break
+    } catch {
+      if ($attempt -lt 3) { Start-Sleep -Seconds 2 } else { Write-Warning "ccache download failed: $_" }
+    }
+  }
+  if ($download_success) {
     if ((Get-FileHash $zip -Algorithm SHA256).Hash -eq $ccache_zip_sha256) {
       $unpack = Join-Path ([System.IO.Path]::GetTempPath()) "ccache-unpack"
       Expand-Archive $zip -DestinationPath $unpack -Force
@@ -122,8 +138,6 @@
       Write-Warning "ccache download failed SHA-256 verification; building without ccache."
     }
     Remove-Item $zip -Force -ErrorAction SilentlyContinue
-  } catch {
-    Write-Warning "ccache download failed ($_); building without ccache."
   }
 
   return ""
diff --git a/ci/scripts/install_compiler_cache.sh b/ci/scripts/install_compiler_cache.sh
index c0e2abc..cc16828 100755
--- a/ci/scripts/install_compiler_cache.sh
+++ b/ci/scripts/install_compiler_cache.sh
@@ -13,14 +13,15 @@
   local url="$1"
   local dest="$2"
   if command -v curl >/dev/null 2>&1; then
-    curl -fsSL --connect-timeout 5 -m 30 "${url}" -o "${dest}"
-  elif command -v wget >/dev/null 2>&1; then
-    wget -q --timeout=30 -O "${dest}" "${url}"
-  elif command -v python3 >/dev/null 2>&1; then
-    python3 -c "import urllib.request; urllib.request.urlretrieve('${url}', '${dest}')"
-  else
-    return 1
+    curl -fsSL --connect-timeout 5 -m 30 "${url}" -o "${dest}" && return 0
   fi
+  if command -v wget >/dev/null 2>&1; then
+    wget -q --timeout=30 -O "${dest}" "${url}" && return 0
+  fi
+  if command -v python3 >/dev/null 2>&1; then
+    python3 -c "import sys, urllib.request; urllib.request.urlretrieve(sys.argv[1], sys.argv[2])" "${url}" "${dest}" && return 0
+  fi
+  return 1
 }
 
 # 1. Provision sccache