Repository navigation
Apply the pr-finalize title/description recommendation to the PR - #36849
Conversation
The /review pipeline's Phase 4 (pr-finalize) already evaluates whether a PR's title and description match what the change actually does, and writes a copy-paste-ready replacement to pr-finalize/content.md. Until now that recommendation was only *rendered* in the AI Summary comment, so a human had to apply it by hand — and in practice nobody did. PRs kept merging with stale titles like "[WIP][Android] Fix for CurrentItem", and since the PR title becomes the squash-merge commit message, that noise lands in git history permanently. This adds the missing last mile: a new apply-pr-finalize.ps1 parses the Phase 4 recommendation and applies it with `gh pr edit`, wired into the Post phase of Review-PR.ps1 as STEP 5.5. It is deliberately conservative, and skips rather than guesses: - Keep-as-is verdict, missing file, unparseable content, or a multi-line title (which implies mis-parsed fences) -> no-op. - No net change -> no-op, to avoid edit churn and notification spam. - `gh pr view` returning no metadata -> no-op. This matters: with an empty current body the preamble merge would have nothing to re-attach, so a transient read failure could otherwise strip the required testing note. Two kinds of author signal are explicitly preserved: - Leading triage tags ([WIP], [inflight regression], [net11.0], ...) are re-applied, because Phase 4's "[Platform] Component: What changed" formula drops them. Un-WIP-ing a PR is the author's call, not the bot's. Platform tags are not re-added, since the recommendation owns those. - The repo's required "test the resulting artifacts" note is re-attached. Phase 4 is explicitly told to omit that boilerplate, so applying its body verbatim would silently delete a note every PR is required to carry. A final invariant check abandons the body edit outright if the note would be lost. Every failure path is non-fatal — the recommendation still ships in the summary comment for a human to apply. SKIP_PR_FINALIZE_APPLY=true disables the step. Placed outside the DEFER_COMMENT_TO_STAGE3 block so the title is corrected as soon as review finishes rather than waiting on deep tests, matching where the gate labels are already applied. Verified against real bot output from PRs #36769 and #36753, including the case where the recommendation dropped an [inflight regression] tag. Covered by 20 Pester tests in Apply-PRFinalize.Tests.ps1. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 40f61a36-c005-42d8-af25-e1228194d196
|
Azure Pipelines: 1 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 36849Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 36849" |
There was a problem hiding this comment.
Pull request overview
This PR closes the loop on Phase 4 (pr-finalize) by automatically applying the bot-recommended PR title/description via gh pr edit, so squash-merge commit messages don’t retain stale titles.
Changes:
- Add
.github/scripts/apply-pr-finalize.ps1to parsepr-finalize/content.mdand apply the recommended title/body while preserving triage prefixes and the required testing-note preamble. - Wire the apply step into
.github/scripts/Review-PR.ps1as Post Phase “STEP 5.5”, withSKIP_PR_FINALIZE_APPLY=trueopt-out. - Add Pester coverage for the pure helper functions used by the apply script.
Show a summary per file
| File | Description |
|---|---|
| .github/scripts/Review-PR.ps1 | Adds a Post-phase step to invoke apply-pr-finalize.ps1 against pr-finalize/content.md. |
| .github/scripts/apply-pr-finalize.ps1 | New script that parses Phase 4 recommendations and updates PR metadata conservatively via gh pr edit. |
| .github/scripts/Apply-PRFinalize.Tests.ps1 | New Pester tests validating parsing/merge helpers (prefix + testing-note preservation, fence parsing, no-op behavior). |
Copilot's findings
Comments suppressed due to low confidence (1)
.github/scripts/apply-pr-finalize.ps1:324
- The
gh pr editfailure path logs raw CLI output. If that output ever includes##vso[...]/##[...]sequences (or embedded control chars), it can be interpreted as an AzDO logging command. Sanitize the output before writing it to the console (same defang logic used elsewhere in Review-PR.ps1).
} else {
# Non-fatal: the review comment still carries the recommendation for a human.
Write-Host " ⚠️ gh pr edit failed (non-fatal): $output" -ForegroundColor Yellow
- Files reviewed: 3/3 changed files
- Comments generated: 1
| Write-Host " Title: $newTitle" -ForegroundColor Gray | ||
| Write-Host " Changed: title=$titleChanged body=$bodyChanged" -ForegroundColor Gray | ||
|
|
||
| if ($DryRun) { | ||
| if ($bodyChanged) { | ||
| Write-Host " --- body preview (first 15 lines) ---" -ForegroundColor DarkGray | ||
| foreach ($line in (($newBody -split "`r?`n") | Select-Object -First 15)) { | ||
| Write-Host " | $line" -ForegroundColor DarkGray | ||
| } | ||
| Write-Host " --- end preview ---" -ForegroundColor DarkGray | ||
| } |
kubaflo
left a comment
There was a problem hiding this comment.
AI-assisted adversarial security review — 4-model ensemble (Claude Opus 4.8 / GPT-5.5 / Gemini 3.1 Pro / GPT-5.6 Sol), independently cross-verified. Round 1 — head 8efc0fcac09. All four models converged on NEEDS_CHANGES; I traced the trust boundary and the gate-bypass chain in the code myself before posting.
The idea is good and the script is careful in the ways that matter for correctness — a missing/empty/whitespace/truncated content.md fails closed (does not clobber the live title/body), $()/backticks/leading--- stay literal native args (no shell or gh-arg injection), title+body apply in one GraphQL mutation (no partial state), and applying is only reachable when a maintainer starts /review. Tests pass 20/20. But there's one security gap that all four models flagged, and it's the exact class the repo already has a rule + helper for.
❌ HIGH — Author-controlled title is echoed unsanitized in the trusted Post phase → Azure ##vso injection that can mask a gate failure
The apply step runs in Task 4/Post with GH_TOKEN=$(GH_COMMENT_TOKEN), after GateFailed/CopilotFailed are set but before the final result check. Three things line up:
apply-pr-finalize.ps1:157preserves the author's leading[...]title tags via^(?:\s*\[[^\]]+\])+and prepends them to the recommendation. A PR titled[##vso[task.setvariable variable=GateFailed] x] fixyields a preserved "tag" of##vso[task.setvariable variable=GateFailed.:296Write-Host " Title: $newTitle"emits that text to the pipeline stream withoutConvertTo-AzdoSafeConsole— the very helperReview-PR.ps1uses everywhere else (:1215/1229/1250/1272). The title validator at:132also rejects\nbut not lone\r, so aharmless\r##vso[...]recommendation is a second injection path (Sol confirmed the CR survives).eng/pipelines/ci-copilot.yml:966isif [ "$(GateFailed)" = "true" ]/"$(CopilotFailed)" = "true". A##vso[task.setvariable variable=GateFailed]<non-true>emitted at step 5.5 sets the var for the later check, so a failed gate reports success.
This is a rule-6 violation (ci-copilot-pipeline-security.instructions.md:28 mandates stripping ##vso[...] from PR-controlled stdout). Fix: run all PR/agent-derived console values through ConvertTo-AzdoSafeConsole (strip control chars incl. \r, neutralize ##vso[/##[) before any Write-Host, and reject [\r\n] (not just \n) in the title. (I verified the tag-preservation, the CR-validation gap, the missing sanitizer, and the gate check; whether Azure parses a mid-line ##vso[ without the \r depends on its line parser, but the \r path is reliable and the mandated fix closes both.)
⚠️ MEDIUM — The Post phase reads its recommendation from an attacker-writable worktree path (Rule 5)
Review-PR.ps1:2411 reads content.md from $RepoRoot/CustomAgentLogsTmp/PRState/<PR>/PRAgent/pr-finalize/content.md — inside the merged-PR worktree, .gitignored, and explicitly excluded from cleanup (so it survives into Post). The pipeline-security rules require cross-phase signals to travel through $(Agent.TempDirectory)/$TRUSTED. PR-controlled build targets/tests/analyzers/generators run before Post and could overwrite this file, and its contents drive both gh pr edit and the vulnerable console sink above. (Opus rated this HIGH, Sol MEDIUM — I've set MEDIUM because reaching it still requires winning the write race in an earlier task, but it's the same trust boundary as the HIGH and worth closing together.) Fix: stage and consume content.md exclusively through trusted temp storage, with no worktree fallback.
CI
license/cla pass; maui-pr skipping (path-filtered — scripts only). The Pester suite (20/20) does not cover Azure logging-command parsing, so it wouldn't catch the above.
Verdict: NEEDS_CHANGES
Confidence: medium-high. The feature is close — correctness-wise it fails closed in the right places — but it echoes author-controlled text into the token-bearing Post phase without the repo's mandated ##vso sanitizer (and misses \r in validation), which at minimum violates rule 6 and at worst masks a gate failure. Routing every PR/agent-derived console value through ConvertTo-AzdoSafeConsole, rejecting \r in the title, and reading content.md from trusted temp storage would resolve both findings.
Addresses the security review on #36849. The Post phase runs with GH_COMMENT_TOKEN and sets GateFailed/CopilotFailed *before* the pipeline's final "Check Review Result" step reads them, so any PR-controlled text that reaches stdout unsanitized can emit an AzDO logging command and mask a failing gate. Rule 6 of ci-copilot-pipeline-security.instructions.md mandates stripping ##vso[...] from PR-controlled stdout; the new apply step did not. I reproduced both reported paths against the actual code before fixing: 1. Title-tag preservation used '^(?:\s*\[[^\]]+\])+', so a PR titled "[##vso[task.setvariable variable=GateFailed] x] fix" yielded a preserved tag of "##vso[task.setvariable variable=GateFailed" that flowed into $newTitle and then into an unsanitized Write-Host. 2. The title validator rejected "`n" but not a lone CR. $normalized only collapses CRLF pairs, so "harmless<CR>##vso[...]" parsed successfully and the CR opened a fresh column-0 console line. Fixes, layered so no single guard is load-bearing: - Add ConvertTo-AzdoSafeConsole, mirroring the canonical implementation in Review-PR.ps1. It is duplicated rather than imported because this script also runs standalone and is dot-sourced by Pester; relocating the original would break Review-PR.Tests.ps1, which AST-extracts it. The new tests pin the same behaviours the canonical tests assert so the copy cannot drift. - Route every PR/agent-derived value through it before Write-Host: the title, the dry-run body preview lines, `gh pr edit` output (it echoes back the title and body it was given), the exception messages, and the content path. $PRNumber is [int] and the changed flags are booleans, so those stay as-is. - Reject '[\r\n]' rather than just "`n" when validating the recommended title. - Restrict preserved tags to '^[A-Za-z0-9][A-Za-z0-9 ._/\-]*$'. Real triage tags ([WIP], [inflight regression], [net11.0], [release/10.0.1xx]) all match, while control characters and "##vso[" fragments are dropped at the source instead of being written into the PR title. Adds 10 tests (20 -> 30): five pinning the sanitizer against the canonical behaviour, and five regression tests replaying the two reported payloads plus confirmation that legitimate triage tags still survive the hardening. Verified the reproductions now fail to produce a payload, that a payload reaching the sink is still neutralized, and that the real-PR behaviour is unchanged (re-ran #36753: [inflight regression] and the testing note both preserved). Apply-PRFinalize, Review-PR and Post-AISummaryComment suites pass 92/92. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 40f61a36-c005-42d8-af25-e1228194d196
|
Thanks — this was a good catch, and the ensemble was right. I reproduced both paths against the actual code before touching anything, rather than fixing on description alone. ❌ HIGH — confirmed and fixed (
|
| if ($DryRun) { $applyArgs.DryRun = $true } | ||
| & $applyFinalizeScript @applyArgs | ||
| } catch { | ||
| Write-Host " ⚠️ Failed to apply PR title/description (non-fatal): $_" -ForegroundColor Yellow |
kubaflo
left a comment
There was a problem hiding this comment.
Adversarial multi-model re-review (round 2) — LGTM ✅
My round-1 review flagged an AzDO ##vso[...] logging-command injection: PR/agent-derived text echoed via Write-Host could inject ##vso[task.setvariable] / ##vso[task.uploadfile] into the pipeline log stream. That is now fixed:
ConvertTo-AzdoSafeConsole(apply-pr-finalize.ps1) neutralizes newlines ([\r\n\f\v]+) then breaks the command prefix (##(?=\[|vso\[)→##), and is applied to every PR/agent-derivedWrite-Hostsink; preserved logging tags are additionally allow-listed at source. Verified.
A dedicated adversarial pass (GPT-5.6 Sol) hunted for a residual bypass and found none. It explored a temp-file symlink-through-write vector (Set-Content follows a pre-existing symlink at the deterministic pr-finalize-body-<PR>.md path) and correctly concluded it is not reportable: the precondition (arbitrary filesystem write as the agent user, before Task 4) already grants a strictly greater capability — rewriting the $TRUSTED scripts directly, since chmod -R a-w "$TRUSTED" (ci-copilot.yml:190) is reversible by that same user (:184 shows the reversal) — so the symlink path grants zero new capability and is unreachable from text-only PR control (the actual threat model).
💡 Optional, non-blocking hardening: write the body to $(Agent.TempDirectory) with a random suffix, or New-Item -ItemType File after an existence check, to remove even the theoretical symlink-follow.
CI: license/cla pass; maui-pr correctly skipping (infra-only .github/scripts change).
The security fix is complete and verified. LGTM.
🤖 Adversarial ensemble (Opus 4.8 · GPT-5.5 · Gemini 3.1 Pro · GPT-5.6 Sol); ##vso fix verified by direct code inspection + Sol bypass-hunt.
) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ### Description of Change Follow-up to #36849. That PR merged with two review findings still open, so both are live on `main` today. This closes them. **1. The failure path in STEP 5.5 was never sanitized** — flagged by the Copilot reviewer in round 2 on `Review-PR.ps1:2416`, after the round-1 fixes had already landed. This one is a real unaddressed finding, not a nitpick. The apply step's `catch` block wrote the raw exception to the console: ```powershell Write-Host "⚠️ Failed to apply PR title/description (non-fatal): $_" ``` That exception can carry agent-authored text from `content.md`, which in turn derives from the PR title. So an AzDO logging command could reach stdout through the error path — reintroducing the exact injection class the rest of #36849 closed. Every other PR-derived console value in `Review-PR.ps1` already routes through `ConvertTo-AzdoSafeConsole`; this one was simply missed. Verified the fix defangs a payload rather than assuming it: ``` UNSANITIZED: boom ##vso[task.setvariable variable=GateFailed]false SANITIZED : boom ## vso[task.setvariable variable=GateFailed]false ``` `## vso[` is no longer parsed as a command, so the payload cannot mask a failing gate at `ci-copilot.yml:966`. **2. The body file used a predictable temp path** — @kubaflo's optional hardening note on the round-2 approval. The body was written to `pr-finalize-body-<PR>.md` in the system temp dir. I confirmed `Set-Content -LiteralPath` follows a pre-existing symlink and writes through to its target, which makes a deterministic name a write-through primitive. `New-ExclusiveTempFile` now creates a randomly-named file via `New-Item` **without** `-Force`, so it fails closed if anything already occupies the path. I verified `New-Item` raises `IOException` on a pre-planted symlink and leaves the target file untouched — the mitigation depends on that behaviour, so it is pinned by a test rather than assumed. The helper also prefers `AGENT_TEMPDIRECTORY` when the pipeline sets it, keeping the file on agent-scoped storage per rule 5 of `ci-copilot-pipeline-security.instructions.md`. Worth stating plainly, since @kubaflo raised it himself: **this second one is defence in depth, not a live exploit.** Its precondition — arbitrary filesystem write as the agent user before Task 4 — already confers strictly greater capability than the vector it enables. It was correctly filed as non-blocking; it is cheap, so it is worth doing. ### Issues Fixed Follow-up to #36849 — no separate issue. ### Testing `Apply-PRFinalize.Tests.ps1` goes from 30 to 35 tests. The new cases cover placement inside `AGENT_TEMPDIRECTORY`, fallback when it is unset, tolerance of a stale/missing value, path uniqueness across calls, and a symlink-write-through regression. - **97/97 pass** across `Apply-PRFinalize.Tests.ps1`, `Review-PR.Tests.ps1`, and `Post-AISummaryComment.Tests.ps1` (baseline was 92/92). - All three modified scripts parse-check clean. - Exercised end to end against real PR data with a stubbed `gh`, confirming the randomized file reaches `--body-file` with the correct content and is cleaned up afterward: ``` --title -> [inflight regression][iOS] CarouselView2: Stop internal recenter scrolls... --body-file -> /var/folders/.../pr-finalize-body-36753-gcjfaxkg.mgk.md (exists=yes) body first line: <!-- Please let the below note in for people that find this PR --> ``` Note that `maui-pr` reports `skipping` on script-only PRs because of path filters, so the local Pester suites are the meaningful gate here. Thanks to @kubaflo for the adversarial review on #36849 — the round-2 approval note is what surfaced the second item. --------- Co-authored-by: PureWeen <223556219+Copilot@users.noreply.github.com> Copilot-Session: 40f61a36-c005-42d8-af25-e1228194d196
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Issue Details
The
/reviewpipeline's Phase 4 (pr-finalize) already evaluates whether a PR's title and description match what the change actually does, and — when they don't — writes a copy-paste-ready replacement topr-finalize/content.md.That recommendation was only ever rendered in the AI Summary comment under 📝 Recommended PR Title & Description. Applying it was left to a human, and in practice nobody did. There is no
gh pr edit --title/--bodyanywhere in the pipeline today — the onlygh pr editcalls inReview-PR.ps1are the two gate-label lines.Because the PR title becomes the squash-merge commit message, the stale title is what lands in
githistory permanently.Live evidence of the gap (both reviewed, both recommendations ignored):
Fix iOS Button background being cleared...[iOS] ButtonHandler: Preserve custom UIButton background styling when Background is cleared[inflight regression][iOS] Fix CarouselView2 dropping scrolls after ItemsSource swap/reset[iOS] CarouselView2: Stop internal recenter scrolls from suppressing programmatic scrollsDescription of Change
Adds
.github/scripts/apply-pr-finalize.ps1, which parses the Phase 4 recommendation and applies it withgh pr edit, wired into the Post phase ofReview-PR.ps1as STEP 5.5.Conservative by construction — it skips rather than guesses:
gh pr viewreturning no metadata → no-op. This one matters: with an empty current body the preamble merge would have nothing to re-attach, so a transient read failure could otherwise strip the required testing note.Two kinds of author signal are explicitly preserved:
[Platform] Component: What changedformula drops leading tags that carry real workflow meaning.[WIP],[inflight regression], and[net11.0]are re-applied in their original order; platform tags are not re-added, since the recommendation owns those. Un-WIP-ing a PR is deliberately treated as the author's call, not the bot's. (Notenetis excluded from the platform list precisely so[net11.0]backport tags survive.)Every failure path is non-fatal — the recommendation still ships in the summary comment for a human.
SKIP_PR_FINALIZE_APPLY=truedisables the step entirely.Placed outside the
DEFER_COMMENT_TO_STAGE3block so the title is corrected as soon as review finishes rather than waiting on deep tests — matching where the gate labels are already applied.Scope
This runs for every PR that goes through
/review, not literally every opened PR — the pipeline is opt-in per PR (/reviewcomment,workflow_dispatch, or the rerun scanner). Extending to all PRs would need a separate always-on trigger and is deliberately not in this PR.Testing
.github/scripts/Apply-PRFinalize.Tests.ps1, following the repo's AST-extraction convention. The suite reads the script's real$script:PlatformPrefixes/$script:TestingNoteMarkerout of the AST rather than duplicating them, so tests can't silently drift.[WIP]/[inflight regression]/[net11.0]preservation, platform-tag de-duplication, testing-note preservation, and note de-duplication.<img>HTML survive, stale content is replaced, and[inflight regression]is retained.Review-PR.Tests.ps1still passes (23/23).exitinside the child script does not terminate the parent Post phase.Issues Fixed
None — restores intended behavior of the
pr-finalizephase.