Skip to content

fix: target-namespace annotation for gitops /test, /cancel comments#2472

Merged
chmouel merged 2 commits intotektoncd:mainfrom
chmouel:fix-target-namespace-on-watcher
Feb 13, 2026
Merged

fix: target-namespace annotation for gitops /test, /cancel comments#2472
chmouel merged 2 commits intotektoncd:mainfrom
chmouel:fix-target-namespace-on-watcher

Conversation

@chmouel
Copy link
Copy Markdown
Member

@chmouel chmouel commented Feb 11, 2026

Fix target-namespace resolution for explicit /test and /cancel commands. When a PipelineRun template specifies a target-namespace annotation, these explicit commands now use that annotated namespace instead of falling back to the URL-matched repository.

This resolves cross-namespace issues where explicit commands targeted templates in different namespaces than the URL-derived repository, while maintaining backward compatibility for templates without annotations.

📝 Description of the Change

👨🏻‍ Linked Jira

🔗 Linked GitHub Issue

Fixes #

🚀 Type of Change

  • 🐛 Bug fix (fix:)
  • ✨ New feature (feat:)
  • 💥 Breaking change (feat!:, fix!:)
  • 📚 Documentation update (docs:)
  • ⚙️ Chore (chore:)
  • 💅 Refactor (refactor:)
  • 🔧 Enhancement (enhance:)
  • 📦 Dependency update (deps:)

🧪 Testing Strategy

  • Unit tests
  • Integration tests
  • End-to-end tests
  • Manual testing
  • Not Applicable

🤖 AI Assistance

  • I have not used any AI assistance for this PR.
  • I have used AI assistance for this PR.

If you have used AI assistance, please provide the following details:

Which LLM was used?

  • GitHub Copilot
  • ChatGPT (OpenAI)
  • Claude (Anthropic)
  • Cursor
  • Gemini (Google)
  • Other: ____________

Extent of AI Assistance:

  • Documentation and research only
  • Unit tests or E2E tests only
  • Code generation (parts of the code)
  • Full code generation (most of the PR)
  • PR description and comments
  • Commit message(s)

Important

If the majority of the code in this PR was generated by an AI, please add a Co-authored-by trailer to your commit message.
For example:

Co-authored-by: Gemini gemini@google.com
Co-authored-by: ChatGPT noreply@chatgpt.com
Co-authored-by: Claude noreply@anthropic.com
Co-authored-by: Cursor noreply@cursor.com
Co-authored-by: Copilot Copilot@users.noreply.github.com

**💡You can use the script ./hack/add-llm-coauthor.sh to automatically add
these co-author trailers to your commits.

✅ Submitter Checklist

  • 📝 My commit messages are clear, informative, and follow the project's How to write a git commit message guide. The Gitlint linter ensures in CI it's properly validated
  • ✨ I have ensured my commit message prefix (e.g., fix:, feat:) matches the "Type of Change" I selected above.
  • ♽ I have run make test and make lint locally to check for and fix any
    issues. For an efficient workflow, I have considered installing
    pre-commit and running pre-commit install to
    automate these checks.
  • 📖 I have added or updated documentation for any user-facing changes.
  • 🧪 I have added sufficient unit tests for my code changes.
  • 🎁 I have added end-to-end tests where feasible. See README for more details.
  • 🔎 I have addressed any CI test flakiness or provided a clear reason to bypass it.
  • If adding a provider feature, I have filled in the following and updated the provider documentation:
    • GitHub App
    • GitHub Webhook
    • Gitea/Forgejo
    • GitLab
    • Bitbucket Cloud
    • Bitbucket Data Center

Copilot AI review requested due to automatic review settings February 11, 2026 19:27
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @chmouel, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines how explicit /test and /cancel commands interact with PipelineRuns, enabling them to honor a specified target namespace. By reading the target-namespace annotation from PipelineRun templates, the system can now accurately direct these commands to the intended namespace, thereby supporting more flexible and robust multi-namespace deployments without disrupting existing configurations.

Highlights

  • Target Namespace Resolution for /test and /cancel: Explicit /test and /cancel commands now correctly resolve the target namespace for PipelineRuns based on the pipelinesascode.tekton.dev/target-namespace annotation in the PipelineRun template, rather than defaulting to the repository's namespace.
  • Cross-Namespace Command Support: This enhancement allows users to trigger or cancel PipelineRuns in namespaces different from where the repository is defined, addressing issues with cross-namespace operations.
  • Backward Compatibility: The change maintains backward compatibility, ensuring that PipelineRun templates without the target-namespace annotation continue to function as before, falling back to the URL-matched repository's namespace.
Changelog
  • pkg/pipelineascode/cancel_pipelineruns.go
    • Imported matcher and resolve packages to support target namespace resolution.
    • Introduced resolveRepoForTargetCancelPipelineRun function to determine the correct repository based on the PipelineRun's target-namespace annotation.
    • Modified cancelPipelineRunsOpsComment to utilize the newly resolved repository for cancellation operations.
  • pkg/pipelineascode/cancel_pipelineruns_test.go
    • Imported testprovider package for testing purposes.
    • Added TestCancelPipelineRunsOpsCommentResolvesTargetNamespaceFromTemplate test case to verify the correct resolution of target namespaces for /cancel commands.
  • pkg/pipelineascode/match.go
    • Updated getPipelineRunsFromRepo to incorporate resolveTargetNamespaceRepo when processing explicit /test commands.
    • Added pipelineRunIdentifier helper function to provide a consistent identifier for PipelineRuns.
    • Implemented resolveTargetNamespaceRepo function to find the appropriate repository based on a PipelineRun's target-namespace annotation.
  • pkg/pipelineascode/match_test.go
    • Imported testprovider package for testing.
    • Added TestGetPipelineRunsFromRepoExplicitTestUsesTargetNamespaceRepo test case to validate that explicit /test commands correctly use the target namespace specified in the PipelineRun template.
Activity
  • The pull request author, chmouel, utilized Claude Sonnet 4.5 (via Claude Code) for assistance in developing this feature.
  • The changes include new unit tests to validate the correct resolution of target namespaces for both /test and /cancel commands.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@pipelines-as-code
Copy link
Copy Markdown

pipelines-as-code bot commented Feb 11, 2026

🔍 PR Lint Feedback

Note: This automated check helps ensure your PR follows our contribution guidelines.

⚠️ Items that need attention:

🎫 Jira reference

Add a Jira reference in the description using one of the following formats:

  • https://issues.redhat.com/browse/SRVKP-<number>

If no SRVKP ticket exists yet, link a GitHub issue instead (e.g., Fixes #123).
Minor housekeeping PRs without Jira coverage can skip this after confirming with reviewers.


🤖 AI attribution

The following commits lack an explicit AI attribution footer:

  • a6d0b01 fix: Improve handling of duplicate GitHub comments

If no AI assistance was used for a commit, you can ignore this warning.
Otherwise add an Assisted-by: or Co-authored-by: footer referencing the AI used.


ℹ️ Next Steps

  • Review and address the items above
  • Push new commits to update this PR
  • This comment will be automatically updated when issues are resolved
🔧 Admin Tools (click to expand)

Automated Issue/Ticket Creation:

  • /issue-create - Generate a GitHub issue from this PR content using AI
  • /jira-create - Create a SRVKP Jira ticket from this PR content using AI

⚠️ Important: Always review and edit generated content before finalizing tickets/issues.
The AI-generated content should be used as a starting point and may need adjustments.

These commands are available to maintainers and will post the generated content as PR comments for review.

🤖 This feedback was generated automatically by the PR CI system

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly implements support for the target-namespace annotation for /test and /cancel commands, ensuring that explicit commands can target resources across namespaces. The changes are well-structured, with new functions to handle the repository resolution logic for both commands, and the addition of new tests provides good coverage for the new functionality. I have a few suggestions to improve code conciseness and reduce duplication, including addressing a redundant check as per repository guidelines, but overall the changes are solid.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

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 fixes target-namespace resolution for explicit /test and /cancel commands in Pipelines as Code. When a PipelineRun template specifies a target-namespace annotation, these commands now correctly use the annotated namespace instead of always falling back to the URL-matched repository namespace. This addresses cross-namespace scenarios where templates are deployed in different namespaces than the repository that triggered them.

Changes:

  • Added resolveTargetNamespaceRepo function to resolve the target repository based on the target-namespace annotation for /test commands
  • Added resolveRepoForTargetCancelPipelineRun function to resolve the target repository for /cancel commands by parsing templates
  • Added pipelineRunIdentifier helper function for consistent pipeline run identification in logging
  • Added comprehensive test coverage for both /test and /cancel command scenarios

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.

File Description
pkg/pipelineascode/match.go Implements target-namespace resolution logic for explicit /test commands, adds helper functions for PR identification and namespace resolution
pkg/pipelineascode/match_test.go Adds test coverage for /test command with and without target-namespace annotation
pkg/pipelineascode/cancel_pipelineruns.go Implements target-namespace resolution for /cancel commands by fetching and parsing templates
pkg/pipelineascode/cancel_pipelineruns_test.go Adds test coverage for /cancel command resolving target namespace from templates

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@chmouel chmouel force-pushed the fix-target-namespace-on-watcher branch 2 times, most recently from e45a0c1 to 34f3a0e Compare February 12, 2026 08:33
@chmouel chmouel changed the title fix: honor target-namespace annotation for explicit /test /cancel commands fix: target-namespace annotation for gitops /test, /cancel comments Feb 12, 2026
@chmouel chmouel force-pushed the fix-target-namespace-on-watcher branch from c443c48 to a6d0b01 Compare February 12, 2026 10:35
@chmouel
Copy link
Copy Markdown
Member Author

chmouel commented Feb 12, 2026

/review

@chmouel
Copy link
Copy Markdown
Member Author

chmouel commented Feb 12, 2026

/gemini review

@qodo-code-review
Copy link
Copy Markdown

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Silent Fallback

The new target-namespace resolution path for /cancel silently falls back to the original repository on multiple error paths (fetching tekton dir, parsing templates, resolving metadata). This can hide real misconfigurations and make cross-namespace cancellation appear to “not work” without any visible signal. Consider emitting an event/log for the main failure cases so operators can distinguish “no annotation” from “resolution failed”.

func (p *PacRun) resolveRepoForTargetCancelPipelineRun(ctx context.Context, repo *v1alpha1.Repository) *v1alpha1.Repository {
	if repo == nil || p.event.TargetCancelPipelineRun == "" || p.vcx == nil {
		return repo
	}

	provenance := "source"
	if repo.Spec.Settings != nil && repo.Spec.Settings.PipelineRunProvenance != "" {
		provenance = repo.Spec.Settings.PipelineRunProvenance
	}

	rawTemplates, err := p.vcx.GetTektonDir(ctx, p.event, tektonDir, provenance)
	if err != nil || rawTemplates == "" {
		return repo
	}

	allTemplates := p.makeTemplate(ctx, repo, rawTemplates)
	types, err := resolve.ReadTektonTypes(ctx, p.logger, allTemplates)
	if err != nil {
		return repo
	}

	pipelineRuns, err := resolve.MetadataResolve(types.PipelineRuns)
	if err != nil || len(pipelineRuns) == 0 {
		return repo
	}

	targetPR := filterRunningPipelineRunOnTargetTest(p.event.TargetCancelPipelineRun, pipelineRuns)
	if targetPR == nil {
		for _, pr := range pipelineRuns {
			prName := strings.TrimSuffix(pipelineRunIdentifier(pr), "-")
			if prName == p.event.TargetCancelPipelineRun {
				targetPR = pr
				break
			}
		}
	}
	if targetPR == nil {
		return repo
	}

	return p.resolveTargetNamespaceRepo(ctx, repo, targetPR)
}
Overmatching Marker

Marker matching uses regexp.QuoteMeta(marker) and re.MatchString(comment.GetBody()), which will match the marker anywhere in the body. With the new deduplication behavior, this could delete comments that merely contain the marker substring (e.g., user text or other automation). Consider tightening the matching semantics (e.g., anchored marker block, or a structured hidden HTML comment marker) before treating matches as authoritative for deletion.

func (v *Provider) listCommentsByMarker(ctx context.Context, event *info.Event, marker string) ([]*github.IssueComment, error) {
	comments, _, err := wrapAPI(v, "list_comments", func() ([]*github.IssueComment, *github.Response, error) {
		return v.Client().Issues.ListComments(ctx, event.Organization, event.Repository, event.PullRequestNumber, &github.IssueListCommentsOptions{
			ListOptions: github.ListOptions{
				Page:    1,
				PerPage: 100,
			},
		})
	})
	if err != nil {
		return nil, err
	}

	re := regexp.MustCompile(regexp.QuoteMeta(marker))
	matchedComments := make([]*github.IssueComment, 0, len(comments))
	for _, comment := range comments {
		if re.MatchString(comment.GetBody()) {
			matchedComments = append(matchedComments, comment)
		}
	}
	return matchedComments, nil
}

func (v *Provider) ensureSingleMarkerComment(
	ctx context.Context,
	event *info.Event,
	comments []*github.IssueComment,
	commit string,
) error {
	if len(comments) == 0 {
		return nil
	}

	primaryComment := comments[0]
	for _, comment := range comments {
		if comment.GetBody() == commit {
			primaryComment = comment
			break
		}
	}

	if primaryComment.GetBody() != commit {
		if _, _, err := wrapAPI(v, "edit_comment", func() (*github.IssueComment, *github.Response, error) {
			return v.Client().Issues.EditComment(ctx, event.Organization, event.Repository, primaryComment.GetID(), &github.IssueComment{
				Body: github.Ptr(commit),
			})
		}); err != nil {
			return err
		}
	}

	// Best-effort cleanup to collapse duplicates into a single canonical marker comment.
	for _, comment := range comments {
		if comment.GetID() == primaryComment.GetID() {
			continue
		}
		if _, _, err := wrapAPI(v, "delete_comment", func() (struct{}, *github.Response, error) {
			resp, err := v.Client().Issues.DeleteComment(ctx, event.Organization, event.Repository, comment.GetID())
			return struct{}{}, resp, err
		}); err != nil && v.Logger != nil {
			v.Logger.Warnf("failed to delete duplicate comment %d on %s/%s#%d: %v",
				comment.GetID(), event.Organization, event.Repository, event.PullRequestNumber, err)
		}
	}
	return nil
}
Error Swallowing

After creating a comment, the post-create reconciliation ignores list errors by returning nil. This can mask GitHub API/permission/rate-limit issues and leave duplicates uncollapsed without any visibility. Consider logging the error (at least debug/warn) or returning it when appropriate, while still keeping reconciliation best-effort.

if err != nil {
	return err
}

if updateMarker == "" {
	return nil
}

// Best-effort post-create reconciliation to collapse duplicates created by
// concurrent processors handling the same event.
matchedComments, listErr := v.listCommentsByMarker(ctx, event, updateMarker)
if listErr != nil {
	return nil
}
return v.ensureSingleMarkerComment(ctx, event, matchedComments, commit)

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request enhances the handling of /test and /cancel commands by respecting the target-namespace annotation in PipelineRun templates. However, it introduces critical cross-namespace authorization bypass vulnerabilities, as the code fails to re-verify user permissions against the newly resolved Repository CR after resolving the target-namespace annotation, potentially allowing unauthorized operations. Furthermore, a critical security vulnerability exists in the GitHub App's comment handling, as it does not verify the author of comments it attempts to modify, potentially allowing unauthorized edits. The review also suggests improvements for code maintainability and consistency by extracting duplicated logic and harmonizing template resolution between /test and /cancel commands.

@chmouel chmouel force-pushed the fix-target-namespace-on-watcher branch from d91679b to 0f7b7c6 Compare February 12, 2026 15:03
@tektoncd tektoncd deleted a comment from qodo-code-review bot Feb 12, 2026
@tektoncd tektoncd deleted a comment from qodo-code-review bot Feb 12, 2026
Fix target-namespace resolution for explicit `/test` and `/cancel`
commands. When a PipelineRun template specifies a `target-namespace`
annotation, these explicit commands now use that annotated namespace
instead of falling back to the URL-matched repository.

This resolves cross-namespace issues where explicit commands targeted
templates in different namespaces than the URL-derived repository, while
maintaining backward compatibility for templates without annotations.

Assisted-by: Claude Sonnet 4.5 (via Claude Code)
Signed-off-by: Chmouel Boudjnah <chmouel@redhat.com>
The logic for updating and creating comments on GitHub pull requests was
updated to better handle scenarios with duplicate comments. Previously,
the system might create multiple identical comments or fail to correctly
update an existing one.

This change refactored the comment handling to first retrieve all
comments matching a marker. If duplicates are found, it now prioritizes
one comment to update and deletes the others. Additionally, a jittered
retry mechanism was introduced when creating new comments to reduce the
chance of race conditions where multiple processors might simultaneously
create duplicate comments. The test suite was also updated to cover
these deduplication scenarios.

Signed-off-by: Chmouel Boudjnah <chmouel@redhat.com>
@chmouel chmouel force-pushed the fix-target-namespace-on-watcher branch from 0f7b7c6 to 88e08bc Compare February 12, 2026 22:01
@chmouel chmouel merged commit 31f0397 into tektoncd:main Feb 13, 2026
10 checks passed
@chmouel chmouel deleted the fix-target-namespace-on-watcher branch February 13, 2026 07:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants