name: RemedyProof site release checks

on:
  workflow_call:
    inputs:
      deployment_id:
        description: Stable ID for the successful deployment, reused on retries
        required: true
        type: string
      require_passing_checks:
        description: Require verified passing HSTS and TLS results for downstream promotion
        default: false
        type: boolean
    secrets:
      REMEDYPROOF_CI_TOKEN:
        required: true

permissions: {}

jobs:
  queue:
    runs-on: ubuntu-24.04
    timeout-minutes: 2
    steps:
      - name: Report HSTS and TLS certificate results
        env:
          REMEDYPROOF_ENDPOINT: https://remedyproof.com/api/site-ci-release
          DEPLOYMENT_ID: ${{ inputs.deployment_id }}
          REMEDYPROOF_CI_TOKEN: ${{ secrets.REMEDYPROOF_CI_TOKEN }}
          REMEDYPROOF_RESULT_WAIT_SECONDS: '70'
          REMEDYPROOF_REQUIRE_PASSING_CHECKS: ${{ inputs.require_passing_checks }}
        run: |
          python3 - <<'PY'
          import http.client
          import json
          import os
          import re
          import time
          import urllib.error
          import urllib.parse
          import urllib.request

          class NoRedirect(urllib.request.HTTPRedirectHandler):
              def redirect_request(self, req, fp, code, msg, headers, newurl):
                  return None

          summary = os.environ.get('GITHUB_STEP_SUMMARY')
          access_next_step = (
              'Sign in to RemedyProof and open Properties → CI release checks. Check DNS authorization, '
              'monitoring access and the workflow credential. Retry the same deployment ID after restoring access. '
              'If DNS renewal retired the original evidence, verify a new deployment with a new ID.'
          )

          def stop_submission(message, next_step):
              if summary:
                  with open(summary, 'a', encoding='utf-8') as output:
                      output.write('## RemedyProof post-deploy checks\n\n')
                      output.write(f'**{message}**\n\n{next_step}\n')
              raise SystemExit(message) from None

          deployment = os.environ.get('DEPLOYMENT_ID', '')
          token = os.environ.get('REMEDYPROOF_CI_TOKEN', '')
          gate_input = os.environ.get('REMEDYPROOF_REQUIRE_PASSING_CHECKS', 'false')
          if gate_input not in ('true', 'false'):
              raise SystemExit('Invalid RemedyProof promotion gate setting')
          gate_enabled = gate_input == 'true'
          if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,60}', deployment):
              stop_submission('Invalid deployment ID', 'Set a valid deployment ID for this deploy in the workflow caller.')
          if not re.fullmatch(r'rpci_[a-f0-9]{64}\.[a-f0-9-]{36}\.[a-f0-9]{64}', token):
              stop_submission('Missing or invalid RemedyProof credential', access_next_step)
          endpoint = os.environ['REMEDYPROOF_ENDPOINT']
          opener = urllib.request.build_opener(NoRedirect)
          headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
          request = urllib.request.Request(
              endpoint,
              data=json.dumps({'deploymentId': deployment}).encode(),
              headers=headers,
              method='POST',
          )
          try:
              with opener.open(request, timeout=20) as response:
                  result = json.load(response)
                  if not isinstance(result, dict) or not isinstance(result.get('created'), bool):
                      raise ValueError('Invalid submission response')
                  print('Queued both checks' if result['created'] else 'Both checks already saved')
          except urllib.error.HTTPError as error:
              error_code = None
              try:
                  with error:
                      body = error.read(1025)
                  if len(body) <= 1024:
                      problem = json.loads(body)
                      if isinstance(problem, dict) and isinstance(problem.get('error'), str):
                          error_code = problem['error']
              except (OSError, ValueError, http.client.HTTPException):
                  pass
              next_step = {
                  (403, 'access_denied'): access_next_step,
                  (409, 'baselines_required'): (
                      'Open CI release checks in RemedyProof and establish current HSTS and TLS certificate '
                      'baselines. Then retry the same deployment ID.'
                  ),
                  (409, 'release_busy_or_conflicting'): (
                      'Open CI release checks in RemedyProof. If another check is running, wait for it to finish '
                      'and retry the same deployment ID. If the reference conflicts with a saved pair, verify '
                      'that you are using the ID for this deployment.'
                  ),
                  (409, 'release_queue_busy'): (
                      'Wait for the previous checks to finish and retry this deployment ID. '
                      'The current request has not queued another pair.'
                  ),
                  (409, 'release_conflict'): (
                      'A saved check already uses this release ID. Inspect the conflicting release in RemedyProof.'
                  ),
                  (409, 'authority_contended'): access_next_step,
                  (409, 'prior_authority'): access_next_step,
              }.get((error.code, error_code))
              stop_submission(
                  f'RemedyProof rejected the submission (HTTP {error.code})',
                  next_step or 'Check CI release checks in RemedyProof. Retry with the same deployment ID after the issue clears.',
              )
          except (OSError, ValueError, http.client.HTTPException):
              stop_submission(
                  'RemedyProof was unavailable.',
                  'Retry with the same deployment ID to resume this release.',
              )

          if not summary and not gate_enabled:
              raise SystemExit(0)

          uuid = r'[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}'
          rules = {'hsts': 'HSTS', 'certificate': 'TLS certificate'}
          jobs = {rule: result.get(rule) for rule in rules}
          release_path = result.get('releasePath')
          release = re.fullmatch(
              rf'/home/properties/response/release\?property=(?P<property>{uuid})&check=(?P<check>{uuid})',
              release_path if isinstance(release_path, str) else '',
          )
          if (
              not release or release['property'] != token.split('.')[1] or release['check'] != jobs['hsts']
              or any(not isinstance(job, str) or not re.fullmatch(uuid, job) for job in jobs.values())
              or jobs['hsts'] == jobs['certificate']
          ):
              raise SystemExit('RemedyProof returned an invalid release link')
          origin = urllib.parse.urlsplit(endpoint)
          site_origin = urllib.parse.urlunsplit((origin.scheme, origin.netloc, '', '', ''))
          release_url = site_origin + release_path
          query = urllib.parse.urlencode({'deploymentId': deployment, **jobs})
          status_request = urllib.request.Request(f'{endpoint}?{query}', headers=headers)
          labels = {
              'queued': 'Pending (queued)', 'claimed': 'Pending (starting)', 'running': 'Pending (running)',
              'stillPassing': 'Pass', 'recovered': 'Recovered', 'regressed': 'Regressed', 'stillFailing': 'Fail',
              'failed': 'Check failed', 'expired': 'Check expired', 'cancelled': 'Check canceled', 'unknown': 'Unknown',
          }
          pending = {'queued', 'claimed', 'running'}
          passing = {'stillPassing', 'recovered'}
          terminal = {'failed', 'expired', 'cancelled', 'unknown'}
          wait = max(0, min(70, int(os.environ.get('REMEDYPROOF_RESULT_WAIT_SECONDS', '70'))))
          deadline = time.monotonic() + wait
          states = {}
          note = ''
          error_code = None
          while True:
              try:
                  with opener.open(status_request, timeout=max(1, min(8, deadline - time.monotonic()))) as response:
                      outcome = json.load(response)
                  if not isinstance(outcome, dict) or any(
                      not isinstance(outcome.get(rule), str) or outcome[rule] not in labels for rule in rules
                  ):
                      raise ValueError('Invalid outcome')
                  states = {rule: outcome[rule] for rule in rules}
              except urllib.error.HTTPError as error:
                  states = {}
                  if error.code < 500:
                      error_code = error.code
                      note = 'Access denied.' if error.code == 403 else 'Exact release results are unavailable.'
                      break
                  note = 'The results service was unavailable.'
              except (OSError, ValueError, http.client.HTTPException):
                  states = {}
                  note = 'The results service was unavailable.'
              else:
                  note = ''
                  if (gate_enabled and 'regressed' in states.values()) or not any(
                      state in pending for state in states.values()
                  ):
                      break
              remaining = deadline - time.monotonic()
              if remaining <= 0:
                  note = note or 'Timed out waiting for pending checks.'
                  break
              time.sleep(min(3, remaining))

          gate_blocked = ''
          if gate_enabled:
              regressed = [name for rule, name in rules.items() if states.get(rule) == 'regressed']
              if regressed:
                  gate_blocked = f"Promotion blocked by a verified regression in {' and '.join(regressed)}."
              elif any(states.get(rule) not in passing for rule in rules):
                  gate_blocked = 'Promotion blocked until both checks have verified passing results.'

          next_step = ''
          if error_code == 403:
              next_step = access_next_step
          elif error_code is not None:
              next_step = 'Check the deployment ID and CI readiness in RemedyProof before retrying this release.'
          elif not states:
              next_step = 'Retry with the same deployment ID to read the saved checks once results are available.'
          elif any(state in terminal for state in states.values()):
              next_step = (
                  'Review the saved result in RemedyProof. Replaying this deployment ID reads the same result. '
                  'Resolve the issue, then verify a new deployment with a new ID.'
              )
          elif note and any(state in pending for state in states.values()):
              next_step = 'Wait for the checks to finish, then retry the same deployment ID to read the saved pair.'

          if summary:
              with open(summary, 'a', encoding='utf-8') as output:
                  output.write('## RemedyProof post-deploy checks\n\n')
                  output.write('| Check | Result |\n| --- | --- |\n')
                  for rule, name in rules.items():
                      output.write(f"| {name} | {labels.get(states.get(rule), 'Unavailable')} |\n")
                  output.write('\n')
                  if note:
                      output.write(f'{note}\n\n')
                  if gate_enabled:
                      output.write(f"**{gate_blocked or 'Promotion gate passed.'}**\n\n")
                  if next_step:
                      output.write(f'{next_step}\n\n')
                  if gate_blocked:
                      repairs = {
                          'hsts': (
                              'retest',
                              'Restore the `Strict-Transport-Security` header on the HTTPS root response '
                              'with `max-age` of at least `15552000` seconds.',
                          ),
                          'certificate': (
                              'certificate',
                              'Check that HTTPS connects and that the endpoint serves a currently valid, '
                              'trusted certificate for this hostname with its intermediate chain. '
                              'Renew the certificate if it has 21 days or fewer left.',
                          ),
                      }
                      failing = [rule for rule in rules if states.get(rule) in ('regressed', 'stillFailing')]
                      if failing:
                          output.write('### Repair next steps\n\n')
                          for rule in failing:
                              route, guidance = repairs[rule]
                              comparison = (
                                  f"{site_origin}/home/properties/response/{route}"
                                  f"?property={release['property']}&deployCheck={jobs[rule]}"
                              )
                              output.write(f"- **{rules[rule]}**. {guidance} ")
                              output.write(f"[Open dated {rules[rule]} comparison]({comparison}).\n")
                          output.write('\nDeploy the repair with a new deployment ID.\n\n')
                  if error_code is None:
                      output.write(f'[Open the private release comparison]({release_url})\n')
          if error_code is not None:
              raise SystemExit(f'RemedyProof rejected the result read (HTTP {error_code})')
          if gate_blocked:
              raise SystemExit(gate_blocked)
          PY
