Skip to content

fix(github): restrict comment editing to PAC-owned comments#2487

Merged
chmouel merged 1 commit intotektoncd:mainfrom
theakshaypant:SRKVP-10857-restricted-comment-editing
Mar 3, 2026
Merged

fix(github): restrict comment editing to PAC-owned comments#2487
chmouel merged 1 commit intotektoncd:mainfrom
theakshaypant:SRKVP-10857-restricted-comment-editing

Conversation

@theakshaypant
Copy link
Copy Markdown
Member

@theakshaypant theakshaypant commented Feb 18, 2026

📝 Description of the Change

Add check to ensure PAC only edits comments created by its own credentials, preventing accidental modification of comments from other users or bot accounts.
For GitHub Apps, fetch bot login from app slug during token generation.

👨🏻‍ Linked Jira

https://issues.redhat.com/browse/SRVKP-10857

🔗 Linked GitHub Issue

N/A

🚀 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

Controller logs

akpant@akpant-thinkpadp1gen7:~/code/tekton-pac$ klf pipelines-as-code-controller-58ff6b75b7-mdjgs | grep 'skipping comment edit'
{
  "level": "debug",
  "ts": "2026-02-23T11:31:13.020Z",
  "logger": "pipelinesascode",
  "caller": "github/github.go:897",
  "msg": "This comment was not created by PAC, skipping comment edit :3944224047, created by user akpant-rh, PAC user: theakshaypant",
  "commit": "7c6b6b8-dirty",
  "provider": "github",
  "event-id": "2587e0f0-10ab-11f1-81a9-079f36315cd4",
  "event-sha": "df7155b20c9d35f7036f5178bd8acda77389797c",
  "event-type": "pull_request",
  "source-repo-url": "https://github.com/theakshaypant/webhook-test",
  "target-branch": "main",
  "source-branch": "pac-e2e-test-lk8lz",
  "namespace": "pac-e2e-ns-gqv98"
}

Comments on PR
Screenshot From 2026-02-23 17-03-34

GitHub App test - deleted pac comment for cel validation error and added a duplicate comment. PAC creates a new comment instead of editing the duplicate comment from another user.
image

🤖 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

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @theakshaypant, 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 enhances the GitHub integration by introducing a critical safeguard: Pipelines-as-Code will now strictly manage only its own comments. This prevents unintended alterations to comments made by other users or automated systems. The change also refines how GitHub App bot identities are determined, ensuring accurate ownership checks.

Highlights

  • Comment Ownership Enforcement: Implemented a mechanism to ensure that Pipelines-as-Code (PAC) only attempts to edit comments that it originally created, preventing accidental modification of comments from other users or bots on GitHub.
  • GitHub App Bot Login Retrieval: Added functionality to fetch the GitHub App's bot login (slug) during token generation, which is crucial for identifying PAC-owned comments when operating as a GitHub App.
  • Provider State Enhancement: Introduced a new pacUserLogin field in the GitHub Provider struct to cache the authenticated user's login, optimizing subsequent checks for comment ownership.
  • Comprehensive Test Coverage: Expanded unit tests to cover the new comment ownership logic, including scenarios where comments from different users are encountered and new comments are created instead of being edited, and added tests for fetching the app slug.
Changelog
  • pkg/provider/github/app/token_test.go
    • Added a mock handler for the '/app' endpoint to simulate fetching the app slug during testing.
  • pkg/provider/github/github.go
    • Added a pacUserLogin field to the Provider struct to store the authenticated PAC user's login.
    • Modified listCommentsByMarker to retrieve and cache the PAC user's login (for PATs) and to filter comments, ensuring only PAC-owned comments are considered for editing.
  • pkg/provider/github/github_test.go
    • Added mock handlers for the '/user' endpoint to simulate fetching the PAC user's login in various test cases.
    • Updated existing test cases to include user information in mocked GitHub API responses for comments.
    • Introduced a new test case to verify that comments from other users are correctly skipped, leading to the creation of new comments rather than editing existing ones.
    • Updated Provider initialization in tests to include a logger instance.
  • pkg/provider/github/parse_payload.go
    • Imported the github.com/golang-jwt/jwt/v4 package.
    • Modified GetAppToken to fetch and cache the GitHub App bot's login using the newly introduced fetchAppSlug function.
    • Added a new private function fetchAppSlug responsible for retrieving the GitHub App's slug by generating and signing a JWT.
  • pkg/provider/github/parse_payload_test.go
    • Added a mock handler for the '/app' endpoint in TestAppTokenGeneration to support app slug retrieval.
    • Added a new test suite TestFetchAppSlug with multiple scenarios, including successful slug fetching, handling 404 responses, invalid private keys, empty slugs, and malformed JSON responses.
  • pkg/provider/github/scope_test.go
    • Added a mock handler for the '/app' endpoint to simulate fetching the app slug during token scoping tests.
Activity
  • The pull request author, theakshaypant, has addressed a bug related to comment editing.
  • Unit tests, end-to-end tests, and manual testing were performed to validate the changes.
  • AI assistance from Claude was utilized for generating unit/E2E tests and commit messages.
  • The submitter checklist indicates that commit messages are clear, the type of change matches, and make test and make lint were run locally.
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.

return token, err
}

// Refer https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation#using-an-installation-access-token-to-authenticate-as-an-app-installation
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

There is some code duplication in this method and GenerateJWT.

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 introduces an important security enhancement by restricting Pipelines-as-Code (PAC) comment editing to only those comments created by its own identity, preventing unauthorized modifications. While this is a significant security improvement, the current implementation unfortunately exacerbates an existing SSRF and credential leakage vulnerability. User-controlled HTTP headers, specifically X-GitHub-Enterprise-Host, are used to define API endpoints before webhook signature validation, which could allow an attacker to exfiltrate signed JWTs or installation tokens. It is strongly recommended to validate the host header against a trusted allow-list before use. The implementation correctly distinguishes between Personal Access Token (PAT) and GitHub App authentication and is well-tested, with a minor suggestion regarding a code comment.

Comment on lines +111 to +135
func (v *Provider) fetchAppSlug(ctx context.Context, applicationID int64, privateKey []byte, apiURL string) (string, error) {
parsedPK, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
return "", fmt.Errorf("failed to parse private key: %w", err)
}

token := jwt.NewWithClaims(jwt.SigningMethodRS256, &jwt.RegisteredClaims{
Issuer: fmt.Sprintf("%d", applicationID),
IssuedAt: jwt.NewNumericDate(time.Now()),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(5 * time.Minute)),
})

tokenString, err := token.SignedString(parsedPK)
if err != nil {
return "", fmt.Errorf("failed to sign private key: %w", err)
}

client, _, _ := MakeClient(ctx, apiURL, tokenString)
app, _, err := client.Apps.Get(ctx, "")
if err != nil {
return "", fmt.Errorf("failed to get app info: %w", err)
}

return app.GetSlug(), nil
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

security-critical critical

CRITICAL: SSRF and Credential Leakage. The newly introduced fetchAppSlug function uses the apiURL parameter, which is derived from the unvalidated X-GitHub-Enterprise-Host HTTP header, to define the GitHub API endpoint. This URL is used to create a GitHub client that authenticates using a JWT signed with the App's private key. An attacker can provide a malicious host in this header, causing PAC to send a signed JWT to the attacker's server. This JWT can be used by the attacker to impersonate the GitHub App and gain unauthorized access to repositories where the App is installed.

Recommendation: Validate the X-GitHub-Enterprise-Host header against an allow-list of trusted hosts or only use hosts explicitly configured in the controller's settings. Avoid making network requests to user-controlled endpoints before validating the webhook signature.

return token, err
}

// Refer https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation#using-an-installation-access-token-to-authenticate-as-an-app-installation
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The comment is slightly misleading. This function authenticates as a GitHub App, not as an installation. The linked documentation section is about authenticating as an installation. A more accurate link would be to the documentation for authenticating as a GitHub App.

Suggested change
// Refer https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation#using-an-installation-access-token-to-authenticate-as-an-app-installation
// Refer https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app

@theakshaypant theakshaypant force-pushed the SRKVP-10857-restricted-comment-editing branch 3 times, most recently from a007c67 to 8928fdf Compare February 23, 2026 11:33
@theakshaypant
Copy link
Copy Markdown
Member Author

Github test failing due to gh app being installed on the webhook tests repo. Duplicate comments are created on this test showing comments added by both, app and webhook integration. Also linking test that shows edit happening on a comment from different author from before this PR.

@theakshaypant theakshaypant force-pushed the SRKVP-10857-restricted-comment-editing branch 2 times, most recently from 0b9008f to 088863e Compare February 25, 2026 06:07
Comment on lines +99 to +104
// Type must be set explicitly so the incoming webhook handler
// (adapter.detectIncoming) knows this is a direct webhook setup.
// Without it, GitProvider.Type == "" causes the controller to
// assume GitHub App mode and attempt to fetch the global
// pipelines-as-code-secret, which doesn't exist for direct webhooks.
Type: "github",
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The said condition can be found here

@theakshaypant theakshaypant marked this pull request as ready for review February 25, 2026 06:21
if v.pacUserLogin == "" {
if event.InstallationID > 0 {
// For Apps, get the app slug.
slug, err := v.fetchAppSlug(ctx, event.Provider.URL)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

i think we use event.Provider.GHEURL on reconciler for GHE, which mean it would be broken.

can you double check this works there?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I had looked at GHEURL (considering the jwt token part used GHEURL in the reference code at GetAppToken) but looking at this assignment, I felt this would work.

Will test it nevertheless.


// Refer https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation
func (v *Provider) fetchAppSlug(ctx context.Context, apiURL string) (string, error) {
ns := info.GetNS(ctx)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is bugging that we to do this thrice, can you check if we can do this in one go without having to query the Github APP again ?

i.e

% g \\.GetAppIDAndPrivateKey
pkg/provider/github/github.go:1091:	applicationID, privateKey, err := v.GetAppIDAndPrivateKey(ctx, ns, v.Run.Clients.Kube)
pkg/provider/github/app/token.go:119:	applicationID, privateKey, err := gh.GetAppIDAndPrivateKey(ctx, ip.namespace, ip.run.Clients.Kube)
pkg/provider/github/parse_payload.go:55:	applicationID, privateKey, err := v.GetAppIDAndPrivateKey(ctx, ns, kube)

(withouth having to do crazy refactoring)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This change was introducing a bit of complexity and the said craziness, created a separate ticket to track it.

@theakshaypant theakshaypant force-pushed the SRKVP-10857-restricted-comment-editing branch from deded70 to acd2a7d Compare February 27, 2026 03:54
Copy link
Copy Markdown
Member

@chmouel chmouel left a comment

Choose a reason for hiding this comment

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

/lgtm

Add check to ensure PAC only edits comments created by its own
credentials, preventing accidental modification of comments from
other users or bot accounts.
For GitHub Apps, fetch bot login from app slug if needed on
comment match.

Jira: https://issues.redhat.com/browse/SRVKP-10857

Signed-off-by: Akshay Pant <akshay.akshaypant@gmail.com>
Assisted-by: Claude Sonnet 4.5 (via Claude Code)
@theakshaypant theakshaypant force-pushed the SRKVP-10857-restricted-comment-editing branch from acd2a7d to f49a44e Compare March 3, 2026 04:06
@zakisk
Copy link
Copy Markdown
Member

zakisk commented Mar 3, 2026

/test

@chmouel chmouel merged commit 95bb453 into tektoncd:main Mar 3, 2026
13 checks passed
@chmouel
Copy link
Copy Markdown
Member

chmouel commented Mar 3, 2026

plesae make sure to make a plan for the followup

@theakshaypant theakshaypant deleted the SRKVP-10857-restricted-comment-editing branch March 3, 2026 11:02
@theakshaypant
Copy link
Copy Markdown
Member Author

plesae make sure to make a plan for the followup

Will be taking it up this week itself.

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