Skip to content

Fix 403 error on private repos (attempt)#4831

Merged
lukaszgryglicki merged 3 commits intodevfrom
unicron-fix-get-latest-commit
Oct 20, 2025
Merged

Fix 403 error on private repos (attempt)#4831
lukaszgryglicki merged 3 commits intodevfrom
unicron-fix-get-latest-commit

Conversation

@lukaszgryglicki
Copy link
Member

Signed-off-by: Lukasz Gryglicki lgryglicki@cncf.io

Assisted by OpenAI

Assisted by GitHub Copilot

Signed-off-by: Lukasz Gryglicki <lgryglicki@cncf.io>

Assisted by [OpenAI](https://platform.openai.com/)

Assisted by [GitHub Copilot](https://github.com/features/copilot)
@coderabbitai
Copy link

coderabbitai bot commented Oct 20, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

GetPRHeadSHA (Go) now falls back to listing PR commits with paging when PullRequests.Get fails to derive the head SHA; Python update_pull_request similarly guards head SHA retrieval and falls back to the latest PR commit. Minor log-format and shell usage-example edits included.

Changes

Cohort / File(s) Summary
Go PR head SHA fallback
cla-backend-go/github/github_repository.go
GetPRHeadSHA logs a warning when PullRequests.Get fails and falls back to ListCommits (PerPage:1) to derive the head SHA; handles pagination (fetch last page if multiple), validates commit SHA presence, and propagates list errors. Public signature unchanged.
Python PR head SHA fallback & logging
cla-backend/cla/models/github_models.py
update_pull_request adds initial debug logging; protects pull_request.head.sha and get_commit() access with try/except (handles GithubException, AttributeError, TypeError), falls back to latest commit from pull_request.get_commits().reversed when needed, logs failures and aborts when SHA absent. create_commit_status log formatting fixed ("with SignUrl: ...").
Shell usage example
utils/search_aws_log_group.sh
Added an example invocation demonstrating searching for "Traceback" in the AWS log group; no logic or parameter changes.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Caller
    participant GetPRHeadSHA
    participant PullRequests
    participant ListCommits

    Caller->>GetPRHeadSHA: Request PR head SHA
    GetPRHeadSHA->>PullRequests: PullRequests.Get(PR)
    alt PullRequests.Get succeeds
        PullRequests-->>GetPRHeadSHA: PR (head.sha)
        GetPRHeadSHA-->>Caller: return head.sha
    else PullRequests.Get fails
        PullRequests--xGetPRHeadSHA: error
        Note right of GetPRHeadSHA #f9f7d9: log warning, fallback to REST commits
        GetPRHeadSHA->>ListCommits: ListCommits(PR, PerPage=1)
        ListCommits-->>GetPRHeadSHA: commits (page 1) + pagination info
        alt multiple pages
            GetPRHeadSHA->>ListCommits: ListCommits(lastPage)
            ListCommits-->>GetPRHeadSHA: commits(last page)
        end
        alt commit with SHA found
            GetPRHeadSHA-->>Caller: return commit.sha
        else no commits or missing SHA
            GetPRHeadSHA-->>Caller: return error
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description Check ❓ Inconclusive The pull request description consists only of a signed-off-by line and attribution to OpenAI and GitHub Copilot. It does not provide any meaningful description of the changes being made in the changeset. While the description is not technically off-topic, it is extremely vague and generic—essentially empty of substantive content about what the PR accomplishes. This falls short of conveying any information about the actual modifications to the codebase, making it difficult for reviewers to understand the intent from the description alone. Consider expanding the pull request description to include a brief explanation of the changes being made, such as describing the fallback mechanisms added to handle GitHub API failures in both the Go and Python files. This would help reviewers understand the intent and scope of the fix more clearly. Even a few sentences explaining the problem and solution would significantly improve the PR's clarity.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "Fix 403 error on private repos (attempt)" accurately describes the main objective of the changeset. The modifications to both the Go and Python files introduce fallback mechanisms to handle GitHub API failures, which aligns directly with addressing 403 errors (permission denied) that can occur when accessing private repositories. The title is concise, specific enough to understand the primary change, and the "(attempt)" qualifier appropriately reflects the exploratory nature of the fix. The title effectively communicates the core problem being addressed without being overly vague or generic.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch unicron-fix-get-latest-commit

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

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

Adds additional logging and fallback logic to retrieve the latest commit SHA for pull requests, aiming to mitigate 403 errors when accessing private repository data. Also adds a usage example comment to an AWS log search script.

  • Adds a debug log and try/except around commit retrieval in update_pull_request with a fallback to pull_request.get_commits()
  • Adds fallback logic in Go to derive PR head SHA via ListCommits when PullRequests.Get fails
  • Adds an extra usage example comment in a utility script

Reviewed Changes

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

File Description
utils/search_aws_log_group.sh Adds an additional example search pattern comment (documentation only).
cla-backend/cla/models/github_models.py Introduces error handling and fallback commit retrieval logic for PR updates.
cla-backend-go/github/github_repository.go Adds fallback method to obtain PR head SHA with enhanced logging.

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
utils/search_aws_log_group.sh (1)

4-4: Example LGTM; mirror quoting in DEBUG echo for clarity.

The added example is useful. Consider aligning the DEBUG echo with the actual invocation so operators see exactly what runs.

Apply this diff to Line 90:

-    echo "aws --region \"${REGION}\" --profile \"lfproduct-${STAGE}\" logs filter-log-events --log-group-name \"/aws/lambda/${log_group}\" --start-time \"${DTFROM}\" --end-time \"${DTTO}\" --filter-pattern \"${search}\""
+    echo "aws --region \"${REGION}\" --profile \"lfproduct-${STAGE}\" logs filter-log-events --log-group-name \"/aws/lambda/${log_group}\" --start-time \"${DTFROM}\" --end-time \"${DTTO}\" --filter-pattern \"\\\"${search}\\\"\""
cla-backend-go/github/github_repository.go (1)

1526-1550: Good fallback for PR head SHA; tighten edge handling.

Works as intended. Two small hardening tweaks:

  • Guard against a nil commit element.
  • Always fetch the last page if available (>=1) to consistently return the true head when PerPage=1.
-        opts := &github.ListOptions{PerPage: 1}
-        commits, resp, comErr := gh.PullRequests.ListCommits(ctx, owner, repo, prNumber, opts)
+        opts := &github.ListOptions{PerPage: 1}
+        commits, resp, comErr := gh.PullRequests.ListCommits(ctx, owner, repo, prNumber, opts)
         if comErr != nil {
             log.WithFields(f).WithError(comErr).Warnf("problem listing commits for repo: %s/%s pull request: %d", owner, repo, prNumber)
             return "", comErr
         }
-        if resp != nil && resp.LastPage > 1 {
-            opts.Page = resp.LastPage
-            commits, _, comErr = gh.PullRequests.ListCommits(ctx, owner, repo, prNumber, opts)
+        if resp != nil && resp.LastPage >= 1 {
+            // With PerPage=1, the last page contains the head commit.
+            opts.Page = resp.LastPage
+            commits, _, comErr = gh.PullRequests.ListCommits(ctx, owner, repo, prNumber, opts)
             if comErr != nil {
                 log.WithFields(f).WithError(comErr).Warnf("problem listing commits for repo: %s/%s pull request: %d (last page)", owner, repo, prNumber)
                 return "", comErr
             }
         }
-        if len(commits) == 0 || commits[0].SHA == nil {
+        if len(commits) == 0 || commits[0] == nil || commits[0].SHA == nil {
             return "", fmt.Errorf("missing head SHA for %s/%s PR #%d (via ListCommits)", owner, repo, prNumber)
         }
         return *commits[0].SHA, nil
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2d6e98d and fc190de.

📒 Files selected for processing (3)
  • cla-backend-go/github/github_repository.go (1 hunks)
  • cla-backend/cla/models/github_models.py (2 hunks)
  • utils/search_aws_log_group.sh (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-test-lint
  • GitHub Check: cypress-functional
🔇 Additional comments (1)
cla-backend/cla/models/github_models.py (1)

2825-2825: Minor log formatting change LGTM.

Signed-off-by: Lukasz Gryglicki <lgryglicki@cncf.io>

Assisted by [OpenAI](https://platform.openai.com/)

Assisted by [GitHub Copilot](https://github.com/features/copilot)
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
cla-backend/cla/models/github_models.py (1)

2645-2656: Critical: .reversed[0] iterator indexing will fail—past review guidance not implemented.

Past reviewers identified that pull_request.get_commits().reversed returns an iterator in PyGithub 1.55, which cannot be indexed with [0]. Line 2652 still uses this pattern, so the fallback will always raise TypeError and hit the exception handler on Line 2654, setting last_commit_sha = None and causing an early return on Line 2658.

This defeats the purpose of the fallback—status updates will be skipped when they should succeed using the latest commit from the PR.

Apply the fix suggested in past reviews:

     except (GithubException, AttributeError, TypeError) as exc:
         cla.log.error(f"{fn} - PR {pull_request.number}: exception getting head.sha: {exc}")
         try:
-            commit_obj = pull_request.get_commits().reversed[0]
-            last_commit_sha = commit_obj.sha
+            commits = pull_request.get_commits().reversed
+            commit_obj = next(iter(commits), None)
+            if commit_obj is None:
+                cla.log.error(f"{fn} - PR {pull_request.number}: no commits found in PR; cannot create statuses")
+                last_commit_sha = None
+            else:
+                last_commit_sha = commit_obj.sha
         except Exception as exc2:
             cla.log.error(f"{fn} - PR {pull_request.number}: exception getting last commit from PR commits: {exc2}")
             last_commit_sha = None

This properly consumes the iterator and handles empty commit lists.

Note: The static analysis warning about catching blind Exception on Line 2654 is acceptable here since we're in a fallback path, logging the error, and safely degrading.

Based on past reviews

🧹 Nitpick comments (1)
cla-backend-go/github/github_repository.go (1)

1526-1550: Fallback logic looks good; verify edge case handling.

The fallback implementation correctly addresses 403 errors on private repos by using ListCommits when PullRequests.Get fails. The pagination handling to reach the last page is sound.

However, there's a subtle edge case on Line 1547: after checking len(commits) == 0, you also check commits[0].SHA == nil in the same condition. If commits is empty, accessing commits[0] would panic. While the short-circuit evaluation of || prevents this in Go (left side is true, right side won't evaluate), consider separating these checks for clarity:

-		if len(commits) == 0 || commits[0].SHA == nil {
+		if len(commits) == 0 {
+			return "", fmt.Errorf("no commits found for %s/%s PR #%d (via ListCommits)", owner, repo, prNumber)
+		}
+		if commits[0].SHA == nil {
 			return "", fmt.Errorf("missing head SHA for %s/%s PR #%d (via ListCommits)", owner, repo, prNumber)
 		}

Also noting: The past review comment about error logging duplication has been properly addressed on Line 1532. ✓

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fc190de and 3d1c7cc.

📒 Files selected for processing (2)
  • cla-backend-go/github/github_repository.go (1 hunks)
  • cla-backend/cla/models/github_models.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.14.0)
cla-backend/cla/models/github_models.py

2654-2654: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-test-lint
  • GitHub Check: cypress-functional
🔇 Additional comments (1)
cla-backend/cla/models/github_models.py (1)

2828-2828: LGTM: Log formatting fix.

Correctly removed the extraneous space before the colon for cleaner log output.

Signed-off-by: Lukasz Gryglicki <lgryglicki@cncf.io>

Assisted by [OpenAI](https://platform.openai.com/)

Assisted by [GitHub Copilot](https://github.com/features/copilot)
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3d1c7cc and f009c56.

📒 Files selected for processing (1)
  • cla-backend/cla/models/github_models.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.14.0)
cla-backend/cla/models/github_models.py

2656-2656: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-test-lint
  • GitHub Check: cypress-functional
🔇 Additional comments (2)
cla-backend/cla/models/github_models.py (2)

2644-2644: LGTM!

The debug log is helpful for tracing PR update flow and notification modes.


2830-2830: LGTM!

Good catch on the formatting - removes the extra space for consistent log output.

@lukaszgryglicki lukaszgryglicki merged commit 79bf08d into dev Oct 20, 2025
4 of 6 checks passed
@lukaszgryglicki lukaszgryglicki deleted the unicron-fix-get-latest-commit branch October 20, 2025 13:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants