openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(ci): harden contributor-rewards pull_request_target (#2621)

Open oxoxDev opened this issue 6 months ago • 2 comments

Summary

  • Add a top-of-file YAML comment block documenting why pull_request_target is intentional and what's intentionally constrained.
  • Introduce safeLogin + safeUrl helpers inside the inline actions/github-script body and apply them at the targetFromEvent() trust boundary.
  • Drop on empty: events with unexpected user/url shape now skip cleanly instead of producing @ mentions or invalid search queries.

Problem

.github/workflows/contributor-rewards.yml uses the high-risk pull_request_target trigger. Permissions are already minimal (contents:read, issues:write, pull-requests:read) and the workflow doesn't check out fork code, so the realistic injection surface is narrow. Two real gaps remained:

  1. Documentation gap: no inline justification explaining why the trigger is intentional + bounded. Future contributors expanding permissions had no signal.
  2. Implicit-trust on attacker-controlled fields: pr.user.login is interpolated into a GitHub search query (author:${login}) and PR comment bodies; pr.html_url into comment bodies. The script trusted GitHub's server-side constraints without normalization at the trust boundary.

Identified by audit #2575 (H-2). CWE-1287.

Solution

  1. Top-of-file YAML comment block (L2-17, above name:) documents the trigger choice, what is intentionally narrow (no fork checkout, no script execution, minimal permissions, templated comment + label only), and warns reviewers not to widen the trust boundary without security review.
  2. Two pure helpers added inside the script: block:
    const safeLogin = (s) => String(s || '').replace(/[^A-Za-z0-9-]/g, '').slice(0, 39);
    const safeUrl = (s) => {
      try {
        const u = new URL(String(s || ''));
        const okHost = u.hostname === 'github.com' || u.hostname.endsWith('.github.com');
        return okHost ? `${u.origin}${u.pathname}` : '';
      } catch {
        return '';
      }
    };
    
  3. targetFromEvent() now computes safeLogin(pr.user?.login) / safeLogin(issue.user?.login) once per branch, bails with core.info(...) + return null if empty, and constructs the return object using the validated login and safeUrl(html_url). Optional chaining (pr.user?.login) is a strictly-safer deviation from the plan: malformed payloads missing the user object now hit the drop guard instead of throwing.

Downstream helpers (markerFor, isFirstMergedPullRequest search, renderCustomMessage, renderDefaultMessage, summary write) see already-sanitized values without per-call sanitization.

Submission Checklist

  • [x] N/A: Tests added or updated — actions/github-script script: directive accepts inline JS only. Extracting the script to a standalone .js for unit-testing would require switching to run: node and lose the typed github/context/core injection — refactor not warranted for ~4 helpers. Manual validation via workflow_dispatch dry-run.
  • [x] Diff coverage ≥ 80% — single YAML file; coverage gate doesn't apply (YAML / inline JS not tracked by Vitest or cargo-llvm-cov).
  • [x] N/A: Coverage matrix updated — behaviour-only change to existing CI workflow
  • [x] N/A: All affected feature IDs from the matrix are listed in ## Related — contributor-rewards workflow is not a matrix-tracked feature
  • [x] No new external network dependencies introduced
  • [x] N/A: Manual smoke checklist updated — contributor-rewards is not a release-cut surface
  • [x] Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Security: explicit trust-boundary sanitization closes CWE-1287 finding from audit #2575. Defense-in-depth — GitHub's server-side username/URL constraints make the realistic injection narrow today, but the script no longer relies implicitly on that constraint.
  • Operations: workflow behavior unchanged for valid PR/issue payloads (real GitHub logins all match [A-Za-z0-9-]{1,39} already). Malformed payloads (hypothetical future GitHub feature) now skip rather than throw.
  • Maintainability: top-of-file comment makes future-contributor pushes that try to widen permissions / add fork-checkout steps obvious code-review red flags.

Related

  • Closes #2621
  • Parent: #2575

AI Authored PR Metadata

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/2621-pr-target-sanitize
  • Commit SHA: 2d3a2f2c

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: workflow YAML
  • [x] pnpm typecheck — N/A: no TypeScript touched
  • [x] Focused tests: YAML parses via PyYAML (yaml.safe_load succeeds, top-level keys: name, on, permissions, concurrency, jobs)
  • [x] Rust fmt/check: N/A
  • [x] Tauri fmt/check: N/A

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: malformed PR/issue payloads with missing/odd user.login or html_url now skip cleanly with an info log.
  • User-visible effect: none for real GitHub payloads.

Parity Contract

  • Legacy behavior preserved: yes for all valid GitHub PR/issue payloads.
  • Guard/fallback/dispatch parity checks: existing actorIsBot, targetAlreadyRewarded, contributorAlreadyRewardedElsewhere guards unchanged.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this PR
  • Resolution: N/A

Summary by CodeRabbit

  • Bug Fixes
    • Improved the contributor rewards workflow with enhanced validation of author logins and URLs to ensure robust handling of edge cases and malformed GitHub metadata during processing.

Review Change Stack

oxoxDev avatar May 25 '26 11:05 oxoxDev

📝 Walkthrough

Walkthrough

The workflow hardens the high-risk pull_request_target trigger by adding security documentation and sanitizing untrusted GitHub metadata. New helper functions validate logins (alphanumeric and hyphen only, max 39 characters) and GitHub URLs (github.com/subdomains only, stripped of query/fragment). All three event paths (PR closed/merged, PR labeled, and issue labeled) now use sanitized values for constructing targets and avoid processing invalid authors.

Changes

Metadata sanitization in contributor-rewards workflow

Layer / File(s) Summary
Security documentation and sanitization helpers
.github/workflows/contributor-rewards.yml
Adds inline security justification for pull_request_target usage and introduces safeLogin (alphanumeric/hyphen, max 39 chars) and safeUrl (github.com domains only, normalized origin+pathname) helper functions to validate metadata before display/search.
Apply sanitization to PR and issue event handlers
.github/workflows/contributor-rewards.yml
PR closed/merged, PR labeled, and issue labeled event handlers construct targets using sanitized login and htmlUrl values from helpers; skips flow when sanitized login is invalid.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A rabbit hops through scripts with care, Sanitizing logins floating in the air! No pull_request_target exploit here— Safe helpers guard the workflow zone, crystal clear! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: hardening the contributor-rewards workflow's pull_request_target trigger through security improvements.
Linked Issues check ✅ Passed The PR implements all coding requirements: adds justification comment, sanitizes login/URL fields, applies sanitization at trust boundary, and includes the sanitization pattern in the workflow.
Out of Scope Changes check ✅ Passed All changes are scoped to hardening the contributor-rewards workflow as specified in issue #2621; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 25 '26 11:05 coderabbitai[bot]

CI status (post body fix)

PR Submission Checklist: now passing after marking N/A items as [x] N/A: <text> per the parser regex in scripts/lib/checklist-parser.mjs.

Other failures all inherited, none caused by the contributor-rewards.yml change:

  • test / Rust Core Tests + Quality: openhuman::memory_tools::tools::put::tests::execute_success_path_persists_rule_in_isolated_workspace panics with document namespace/key cannot contain personal identifiers. This is the PII guard (safety::pii::has_likely_pii) added in PR #2574 / commit a47740d4 flagging tool_name: "bash" as PII-like. Memory-domain regression on main; this YAML-only PR doesn't touch any Rust path. Re-running the failed job in case it's order-dependent.
  • e2e / E2E (Linux / Appium Chromium): same job failing on upstream/main (run 26391619635) — inherited.

oxoxDev avatar May 25 '26 12:05 oxoxDev