Skip to content

Apply the pr-finalize title/description recommendation to the PR - #36849

Merged
kubaflo merged 2 commits into
mainfrom
PureWeen/pr-finalize-apply
Jul 29, 2026
Merged

kubaflo merged 2 commits into
mainfrom
PureWeen/pr-finalize-apply

Conversation

@PureWeen

Copy link
Copy Markdown
Member

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 /review pipeline'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 to pr-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/--body anywhere in the pipeline today — the only gh pr edit calls in Review-PR.ps1 are the two gate-label lines.

Because the PR title becomes the squash-merge commit message, the stale title is what lands in git history permanently.

Live evidence of the gap (both reviewed, both recommendations ignored):

PR Live title Bot recommended
#36769 Fix iOS Button background being cleared... [iOS] ButtonHandler: Preserve custom UIButton background styling when Background is cleared
#36753 [inflight regression][iOS] Fix CarouselView2 dropping scrolls after ItemsSource swap/reset [iOS] CarouselView2: Stop internal recenter scrolls from suppressing programmatic scrolls

Description of Change

Adds .github/scripts/apply-pr-finalize.ps1, which 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.

Conservative by construction — it 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, avoiding edit churn and notification spam.
  • gh pr view returning 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:

  • Triage prefixes. Phase 4's [Platform] Component: What changed formula 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. (Note net is excluded from the platform list precisely so [net11.0] backport tags survive.)
  • The required testing note. Phase 4 is explicitly instructed to omit the "test the resulting artifacts" boilerplate, so applying its body verbatim would silently delete a note every PR is required to carry. The preamble is detected on the current body and re-attached, and a final invariant check abandons the body edit outright if the note would still be lost.

Every failure path is non-fatal — the recommendation still ships in the summary comment for a human. SKIP_PR_FINALIZE_APPLY=true disables the step entirely.

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.

Scope

This runs for every PR that goes through /review, not literally every opened PR — the pipeline is opt-in per PR (/review comment, 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

  • 20 Pester tests in .github/scripts/Apply-PRFinalize.Tests.ps1, following the repo's AST-extraction convention. The suite reads the script's real $script:PlatformPrefixes / $script:TestingNoteMarker out of the AST rather than duplicating them, so tests can't silently drift.
  • Covers: no-op verdict, unparseable content, 3- and 6-backtick fences, fenced blocks nested inside the description, multi-line title rejection, [WIP] / [inflight regression] / [net11.0] preservation, platform-tag de-duplication, testing-note preservation, and note de-duplication.
  • Verified end-to-end against real bot output extracted from [iOS] Fix ButtonHandler clearing custom UIButton styling when Background null #36769 and [inflight regression][iOS] Fix CarouselView2 dropping scrolls after ItemsSource swap/reset #36753, confirming the note is preserved exactly once, markdown tables and <img> HTML survive, stale content is replaced, and [inflight regression] is retained.
  • Existing Review-PR.Tests.ps1 still passes (23/23).
  • Verified that exit inside the child script does not terminate the parent Post phase.

Issues Fixed

None — restores intended behavior of the pr-finalize phase.

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
Copilot AI review requested due to automatic review settings July 27, 2026 21:28
@PureWeen
PureWeen temporarily deployed to copilot-pat-pool July 27, 2026 21:28 — with GitHub Actions Inactive
@azure-pipelines

Copy link
Copy Markdown
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.

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 36849

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 36849"

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ps1 to parse pr-finalize/content.md and apply the recommended title/body while preserving triage prefixes and the required testing-note preamble.
  • Wire the apply step into .github/scripts/Review-PR.ps1 as Post Phase “STEP 5.5”, with SKIP_PR_FINALIZE_APPLY=true opt-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 edit failure 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

Comment thread .github/scripts/apply-pr-finalize.ps1 Outdated
Comment on lines +296 to +306
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
}
@PureWeen
PureWeen temporarily deployed to copilot-pat-pool July 27, 2026 21:33 — with GitHub Actions Inactive
@PureWeen
PureWeen temporarily deployed to copilot-pat-pool July 27, 2026 21:33 — with GitHub Actions Inactive
@github-actions github-actions Bot added the area-infrastructure CI, Maestro / Coherency, upstream dependencies/versions label Jul 27, 2026
@PureWeen
PureWeen temporarily deployed to copilot-pat-pool July 27, 2026 21:34 — with GitHub Actions Inactive

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. apply-pr-finalize.ps1:157 preserves the author's leading [...] title tags via ^(?:\s*\[[^\]]+\])+ and prepends them to the recommendation. A PR titled [##vso[task.setvariable variable=GateFailed] x] fix yields a preserved "tag" of ##vso[task.setvariable variable=GateFailed.
  2. :296 Write-Host " Title: $newTitle" emits that text to the pipeline stream without ConvertTo-AzdoSafeConsole — the very helper Review-PR.ps1 uses everywhere else (:1215/1229/1250/1272). The title validator at :132 also rejects \n but not lone \r, so a harmless\r##vso[...] recommendation is a second injection path (Sol confirmed the CR survives).
  3. eng/pipelines/ci-copilot.yml:966 is if [ "$(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
Copilot AI review requested due to automatic review settings July 28, 2026 21:52
@PureWeen

Copy link
Copy Markdown
Member Author

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 (20f6cc06af)

Both links in the chain reproduced exactly as described:

1. Tag preservation carried the payload. Merge-PreservedTitlePrefix with [##vso[task.setvariable variable=GateFailed] x] fix returned:

[##vso[task.setvariable variable=GateFailed][iOS] Clean title

2. Lone CR passed validation. You were right that $normalized only collapses CRLF pairs, so a bare CR survived -match "n". The parser accepted harmless##vso[task.setvariable variable=GateFailed]x` as a valid single-line title.

Fixed in layers so no single guard is load-bearing:

  • Added ConvertTo-AzdoSafeConsole, mirroring the canonical impl. I duplicated it rather than importing because this script also runs standalone and is dot-sourced by Pester — and relocating the original would break Review-PR.Tests.ps1, which AST-extracts it from Review-PR.ps1. The new tests pin the same behaviours the canonical tests assert so the copy can't drift.
  • Routed every PR/agent-derived value through it before Write-Host: title, dry-run body preview lines, gh pr edit output (it echoes back the title/body it was given — thanks to the Copilot reviewer for flagging that second sink), exception messages, and the content path. $PRNumber is [int] and the changed flags are booleans, so those stay as-is.
  • Reject [\r\n], not just `n.
  • Restricted preserved tags to ^[A-Za-z0-9][A-Za-z0-9 ._/\-]*$ — kills the payload at the source instead of only at the sink. [WIP], [inflight regression], [net11.0], [release/10.0.1xx] all still pass; control chars and ##vso[ fragments are dropped.

Both reproductions now yield no payload, and I separately confirmed that a payload reaching the sink is still neutralized. Tests 20 → 30 (5 pinning the sanitizer, 5 replaying the reported payloads + confirming legit tags survive). 92/92 across Apply-PRFinalize, Review-PR, and Post-AISummaryComment. Real-PR behaviour unchanged — re-ran #36753, [inflight regression] and the testing note both still preserved.

⚠️ MEDIUM — I'd like to push back on the framing, and propose a separate issue

Two things I verified that I think change the calculus:

It's pre-existing, not introduced here. post-ai-summary-comment.ps1:70-73 already reads every phase's content.md from that same $RepoRoot/CustomAgentLogsTmp/PRState/... path. This PR consumes an existing convention rather than establishing a new one.

More importantly — relocating it wouldn't actually buy trust. content.md is authored by the Copilot agent itself inside the untrusted phase (the write instruction is the Phase 4 prompt at Review-PR.ps1:2208). Rule 5 exists to keep trusted signals — a gate verdict, a sentinel — out of attacker-writable space. content.md isn't a trusted signal at any point in its life; it's agent-generated prose that must be treated as untrusted no matter where it sits. Staging it through $(Agent.TempDirectory) would move a file that was already attacker-influenceable at the moment it was written, which I think risks false assurance rather than real defence.

The correct mitigation for untrusted-by-construction content is to harden the point of use, which is what the HIGH fix does. On the write side specifically: -Repo is fixed to dotnet/maui and $PRNumber is an [int] validated upstream, so the only reachable target is the PR under review — whose title and body the author can already edit freely in the UI. I don't see a privilege gain there once the console sink is closed.

Happy to be wrong on this. If you'd still like phase content staged through trusted temp, I think it's genuinely worth doing — but as a pipeline-wide change covering all five phases and the comment path, not a partial fix for one consumer here. Glad to open that as a follow-up issue and take it.

CI note

Agreed the Pester suite can't catch AzDO log parsing — that's why I added the payload-replay tests at the boundary the script actually controls (what it emits) rather than trying to simulate Azure's parser.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

  • Files reviewed: 3/3 changed files
  • Comments generated: 1

if ($DryRun) { $applyArgs.DryRun = $true }
& $applyFinalizeScript @applyArgs
} catch {
Write-Host " ⚠️ Failed to apply PR title/description (non-fatal): $_" -ForegroundColor Yellow

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-derived Write-Host sink; 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.

@kubaflo
kubaflo merged commit 5da1f5d into main Jul 29, 2026
5 of 6 checks passed
@kubaflo
kubaflo deleted the PureWeen/pr-finalize-apply branch July 29, 2026 12:53
@github-actions github-actions Bot added this to the .NET 10 SR10 milestone Jul 29, 2026
kubaflo pushed a commit that referenced this pull request Aug 1, 2026
)

<!-- 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
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 29, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-infrastructure CI, Maestro / Coherency, upstream dependencies/versions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants